code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
|---|---|---|---|---|---|
var createStore = require('../../../addons/createStore');
module.exports = createStore({
storeName: 'BarStore',
handlers: {
'DOUBLE_UP': function () {
this.bar += this.bar;
this.emitChange();
}
},
initialize: function () {
this.bar = 'baz';
},
getBar: function () {
return this.bar;
}
});
|
IveWong/fluxible
|
tests/fixtures/stores/BarStore.js
|
JavaScript
|
bsd-3-clause
| 373
|
/**
* @license
* Copyright The Closure Library Authors.
* SPDX-License-Identifier: Apache-2.0
*/
goog.module('goog.editor.ContentEditableFieldTest');
goog.setTestOnly();
const ContentEditableField = goog.require('goog.editor.ContentEditableField');
const SafeHtml = goog.require('goog.html.SafeHtml');
const googDom = goog.require('goog.dom');
const testSuite = goog.require('goog.testing.testSuite');
const HTML = '<div id="testField">I am text.</div>';
globalThis.FieldConstructor = ContentEditableField;
testSuite({
setUp() {
googDom.getElement('parent').innerHTML = HTML;
assertTrue(
'FieldConstructor should be set by the test HTML file',
typeof FieldConstructor === 'function');
},
testNoIframeAndSameElement() {
const field = new ContentEditableField('testField');
field.makeEditable();
assertFalse(field.usesIframe());
assertEquals(
'Original element should equal field element',
field.getOriginalElement(), field.getElement());
assertEquals(
'Sanity check on original element', 'testField',
field.getOriginalElement().id);
assertEquals(
'Editable document should be same as main document', document,
field.getEditableDomHelper().getDocument());
field.dispose();
},
testMakeEditableAndUnEditable() {
const elem = googDom.getElement('testField');
googDom.setTextContent(elem, 'Hello world');
const field = new ContentEditableField('testField');
field.makeEditable();
assertEquals('true', String(elem.contentEditable));
assertEquals('Hello world', googDom.getTextContent(elem));
field.setSafeHtml(
false /* addParas */, SafeHtml.htmlEscape('Goodbye world'));
assertEquals('Goodbye world', googDom.getTextContent(elem));
field.makeUneditable();
assertNotEquals('true', String(elem.contentEditable));
assertEquals('Goodbye world', googDom.getTextContent(elem));
field.dispose();
},
});
|
scheib/chromium
|
third_party/google-closure-library/closure/goog/editor/contenteditablefield_test.js
|
JavaScript
|
bsd-3-clause
| 1,972
|
'use strict';
var _postcss = require('postcss');
var _postcss2 = _interopRequireDefault(_postcss);
var _postcssValueParser = require('postcss-value-parser');
var _postcssValueParser2 = _interopRequireDefault(_postcssValueParser);
var _rgbFunctionalNotation = require('./lib/rgb-functional-notation');
var _rgbFunctionalNotation2 = _interopRequireDefault(_rgbFunctionalNotation);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function transformRgb(value) {
return (0, _postcssValueParser2.default)(value).walk(function (node) {
/* istanbul ignore if */
if (node.type !== 'function' || node.value !== 'rgb' && node.value !== 'rgba') {
return;
}
node.value = _rgbFunctionalNotation2.default.legacy(_postcssValueParser2.default.stringify(node));
node.type = 'word';
}).toString();
}
module.exports = _postcss2.default.plugin('postcss-color-rgb', function (opts) {
opts = opts || {};
return function (root, result) {
root.walkDecls(function (decl) {
/* istanbul ignore if */
if (!decl.value || decl.value.indexOf('rgb(') === -1 && decl.value.indexOf('rgba(') === -1) {
return;
}
decl.value = transformRgb(decl.value);
});
};
});
|
vbillardm/vbillardm-webp2018-SI201704-la-truelle
|
wordpress/node_modules/postcss-color-rgb/dist/index.js
|
JavaScript
|
mit
| 1,335
|
/**
* Webpack config for production electron main process
*/
import webpack from 'webpack';
import merge from 'webpack-merge';
import BabiliPlugin from 'babili-webpack-plugin';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import baseConfig from './webpack.config.base';
export default merge.smart(baseConfig, {
devtool: 'source-map',
target: 'electron-main',
entry: ['babel-polyfill', './app/main.development'],
// 'main.js' in root
output: {
path: __dirname,
filename: './app/main.js'
},
plugins: [
/**
* Babli is an ES6+ aware minifier based on the Babel toolchain (beta)
*/
new BabiliPlugin(),
new BundleAnalyzerPlugin({
analyzerMode: process.env.OPEN_ANALYZER === 'true' ? 'server' : 'disabled',
openAnalyzer: process.env.OPEN_ANALYZER === 'true'
}),
/**
* Create global constants which can be configured at compile time.
*
* Useful for allowing different behaviour between development builds and
* release builds
*
* NODE_ENV should be production so that modules do not perform certain
* development checks
*/
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production'),
'process.env.DEBUG_PROD': JSON.stringify(process.env.DEBUG_PROD || 'false')
})
],
/**
* Disables webpack processing of __dirname and __filename.
* If you run the bundle in node.js it falls back to these values of node.js.
* https://github.com/webpack/webpack/issues/2010
*/
node: {
__dirname: false,
__filename: false
},
});
|
lhache/katalogz
|
webpack.config.main.prod.js
|
JavaScript
|
mit
| 1,627
|
throw (123);
|
facebook/flow
|
src/parser/test/flow/statement/throw/expression_with_parens.js
|
JavaScript
|
mit
| 13
|
export default class SparceCoverageCollector {
constructor() {
this.srcCoverage = {};
this.metaInfo = {};
}
getSourceCoverage(filename) {
let data = this.srcCoverage[filename];
if (!data) {
data = this.srcCoverage[filename] = {
path: filename,
statementMap: {},
fnMap: {},
branchMap: {},
s: {},
b: {},
f: {},
};
this.metaInfo[filename] = {
indexes: {},
lastIndex: {
s: 0,
b: 0,
f: 0,
},
};
}
return {
data,
meta: this.metaInfo[filename],
};
}
setCoverage(filePath, fileCoverage) {
this.srcCoverage[filePath] = fileCoverage;
}
setSourceCode(filePath, source) {
this.getSourceCoverage(filePath).data.code = source;
}
getFinalCoverage() {
return this.srcCoverage;
}
updateBranch(source, srcItem, hits) {
const { data, meta } = this.getSourceCoverage(source);
let key = ['b'];
srcItem.locations.map(loc => key.push(
loc.start.line, loc.start.column,
loc.end.line, loc.end.line
));
key = key.join(':');
let index = meta.indexes[key];
if (!index) {
meta.lastIndex.b += 1;
index = meta.lastIndex.b;
meta.indexes[key] = index;
data.branchMap[index] = srcItem;
}
if (!data.b[index]) {
data.b[index] = hits.map(v => v);
} else {
for (let i = 0; i < hits.length; i += 1) {
data.b[index][i] += hits[i];
}
}
}
updateFunction(source, srcItem, hits) {
const { data, meta } = this.getSourceCoverage(source);
const key = [
'f',
srcItem.loc.start.line, srcItem.loc.start.column,
srcItem.loc.end.line, srcItem.loc.end.column,
].join(':');
let index = meta.indexes[key];
if (!index) {
meta.lastIndex.f += 1;
index = meta.lastIndex.f;
meta.indexes[key] = index;
data.fnMap[index] = srcItem;
}
data.f[index] = data.f[index] || 0;
data.f[index] += hits;
}
updateStatement(source, srcItem, hits) {
const { data, meta } = this.getSourceCoverage(source);
const key = [
's',
srcItem.start.line, srcItem.start.column,
srcItem.end.line, srcItem.end.column,
].join(':');
let index = meta.indexes[key];
if (!index) {
meta.lastIndex.s += 1;
index = meta.lastIndex.s;
meta.indexes[key] = index;
data.statementMap[index] = srcItem;
}
data.s[index] = data.s[index] || 0;
data.s[index] += hits;
}
}
|
Dackng/eh-unmsm-client
|
node_modules/remap-istanbul/src/SparceCoverageCollector.js
|
JavaScript
|
mit
| 2,318
|
/*
* Author: Zion Orent <zorent@ics.com>
* Copyright (c) 2014 Intel Corporation.
*
* 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.
*/
//Load Grove Motion module
var grove_motion = require('jsupm_biss0001');
// Instantiate a Grove Motion sensor on GPIO pin D2
var myMotionObj = new grove_motion.BISS0001(2);
setInterval(function()
{
if (myMotionObj.value())
console.log("Detecting moving object");
else
console.log("No moving objects detected");
}, 1000);
// Print message when exiting
process.on('SIGINT', function()
{
console.log("Exiting...");
process.exit(0);
});
|
whbruce/upm
|
examples/javascript/biss0001.js
|
JavaScript
|
mit
| 1,586
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Background = void 0;
const OptionsColor_1 = require("../OptionsColor");
class Background {
constructor() {
this.color = new OptionsColor_1.OptionsColor();
this.color.value = "";
this.image = "";
this.position = "";
this.repeat = "";
this.size = "";
this.opacity = 1;
}
load(data) {
if (data === undefined) {
return;
}
if (data.color !== undefined) {
this.color = OptionsColor_1.OptionsColor.create(this.color, data.color);
}
if (data.image !== undefined) {
this.image = data.image;
}
if (data.position !== undefined) {
this.position = data.position;
}
if (data.repeat !== undefined) {
this.repeat = data.repeat;
}
if (data.size !== undefined) {
this.size = data.size;
}
if (data.opacity !== undefined) {
this.opacity = data.opacity;
}
}
}
exports.Background = Background;
|
cdnjs/cdnjs
|
ajax/libs/tsparticles/1.17.0-alpha.9/Options/Classes/Background/Background.js
|
JavaScript
|
mit
| 1,125
|
/**
* @fileoverview
* some functions for browser-side pretty printing of code contained in html.
* <p>
*
* For a fairly comprehensive set of languages see the
* <a href="http://google-code-prettify.googlecode.com/svn/trunk/README.html#langs">README</a>
* file that came with this source. At a minimum, the lexer should work on a
* number of languages including C and friends, Java, Python, Bash, SQL, HTML,
* XML, CSS, Javascript, and Makefiles. It works passably on Ruby, PHP and Awk
* and a subset of Perl, but, because of commenting conventions, doesn't work on
* Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class.
* <p>
* Usage: <ol>
* <li> include this source file in an html page via
* {@code <script type="text/javascript" src="/path/to/prettify.js"></script>}
* <li> define style rules. See the example page for examples.
* <li> mark the {@code <pre>} and {@code <code>} tags in your source with
* {@code class=prettyprint.}
* You can also use the (html deprecated) {@code <xmp>} tag, but the pretty
* printer needs to do more substantial DOM manipulations to support that, so
* some css styles may not be preserved.
* </ol>
* That's it. I wanted to keep the API as simple as possible, so there's no
* need to specify which language the code is in, but if you wish, you can add
* another class to the {@code <pre>} or {@code <code>} element to specify the
* language, as in {@code <pre class="prettyprint lang-java">}. Any class that
* starts with "lang-" followed by a file extension, specifies the file type.
* See the "lang-*.js" files in this directory for code that implements
* per-language file handlers.
* <p>
* Change log:<br>
* cbeust, 2006/08/22
* <blockquote>
* Java annotations (start with "@") are now captured as literals ("lit")
* </blockquote>
* @requires console
* @overrides window
*/
// JSLint declarations
/*global console, document, navigator, setTimeout, window */
/**
* Split {@code prettyPrint} into multiple timeouts so as not to interfere with
* UI events. If set to {@code false}, {@code prettyPrint()} is synchronous.
*/
window['PR_SHOULD_USE_CONTINUATION'] = true;
/** the number of characters between tab columns */
window['PR_TAB_WIDTH'] = 8;
/**
* Walks the DOM returning a properly escaped version of innerHTML.
*
* @param {Node}
* node
* @param {Array.
* <string>} out output buffer that receives chunks of HTML.
*/
window['PR_normalizedHtml']
/**
* Contains functions for creating and registering new language handlers.
*
* @type {Object}
*/
= window['PR']
/**
* Pretty print a chunk of code.
*
* @param {string}
* sourceCodeHtml code as html
* @return {string} code as html, but prettier
*/
= window['prettyPrintOne']
/**
* Find all the {@code <pre>} and {@code <code>} tags in the DOM with
* {@code class=prettyprint} and prettify them.
*
* @param {Function?}
* opt_whenDone if specified, called when the last entry has been
* finished.
*/
= window['prettyPrint'] = void 0;
/**
* browser detection.
*
* @extern
* @returns false if not IE, otherwise the major version.
*/
window['_pr_isIE6'] = function() {
var ieVersion = navigator && navigator.userAgent
&& navigator.userAgent.match(/\bMSIE ([678])\./);
ieVersion = ieVersion ? +ieVersion[1] : false;
window['_pr_isIE6'] = function() {
return ieVersion;
};
return ieVersion;
};
(function() {
// Keyword lists for various languages.
var FLOW_CONTROL_KEYWORDS = "break continue do else for if return while ";
var C_KEYWORDS = FLOW_CONTROL_KEYWORDS + "auto case char const default "
+ "double enum extern float goto int long register short signed sizeof "
+ "static struct switch typedef union unsigned void volatile ";
var COMMON_KEYWORDS = C_KEYWORDS + "catch class delete false import "
+ "new operator private protected public this throw true try typeof ";
var CPP_KEYWORDS = COMMON_KEYWORDS + "alignof align_union asm axiom bool "
+ "concept concept_map const_cast constexpr decltype "
+ "dynamic_cast explicit export friend inline late_check "
+ "mutable namespace nullptr reinterpret_cast static_assert static_cast "
+ "template typeid typename using virtual wchar_t where ";
var JAVA_KEYWORDS = COMMON_KEYWORDS
+ "abstract boolean byte extends final finally implements import "
+ "instanceof null native package strictfp super synchronized throws "
+ "transient ";
var CSHARP_KEYWORDS = JAVA_KEYWORDS
+ "as base by checked decimal delegate descending event "
+ "fixed foreach from group implicit in interface internal into is lock "
+ "object out override orderby params partial readonly ref sbyte sealed "
+ "stackalloc string select uint ulong unchecked unsafe ushort var ";
var JSCRIPT_KEYWORDS = COMMON_KEYWORDS
+ "debugger eval export function get null set undefined var with "
+ "Infinity NaN ";
var PERL_KEYWORDS = "caller delete die do dump elsif eval exit foreach for "
+ "goto if import last local my next no our print package redo require "
+ "sub undef unless until use wantarray while BEGIN END ";
var PYTHON_KEYWORDS = FLOW_CONTROL_KEYWORDS + "and as assert class def del "
+ "elif except exec finally from global import in is lambda "
+ "nonlocal not or pass print raise try with yield " + "False True None ";
var RUBY_KEYWORDS = FLOW_CONTROL_KEYWORDS
+ "alias and begin case class def"
+ " defined elsif end ensure false in module next nil not or redo rescue "
+ "retry self super then true undef unless until when yield BEGIN END ";
var SH_KEYWORDS = FLOW_CONTROL_KEYWORDS + "case done elif esac eval fi "
+ "function in local set then until ";
var ALL_KEYWORDS = (CPP_KEYWORDS + CSHARP_KEYWORDS + JSCRIPT_KEYWORDS
+ PERL_KEYWORDS + PYTHON_KEYWORDS + RUBY_KEYWORDS + SH_KEYWORDS);
// token style names. correspond to css classes
/** token style for a string literal */
var PR_STRING = 'str';
/** token style for a keyword */
var PR_KEYWORD = 'kwd';
/** token style for a comment */
var PR_COMMENT = 'com';
/** token style for a type */
var PR_TYPE = 'typ';
/** token style for a literal value. e.g. 1, null, true. */
var PR_LITERAL = 'lit';
/** token style for a punctuation string. */
var PR_PUNCTUATION = 'pun';
/** token style for a punctuation string. */
var PR_PLAIN = 'pln';
/** token style for an sgml tag. */
var PR_TAG = 'tag';
/** token style for a markup declaration such as a DOCTYPE. */
var PR_DECLARATION = 'dec';
/** token style for embedded source. */
var PR_SOURCE = 'src';
/** token style for an sgml attribute name. */
var PR_ATTRIB_NAME = 'atn';
/** token style for an sgml attribute value. */
var PR_ATTRIB_VALUE = 'atv';
/**
* A class that indicates a section of markup that is not code, e.g. to allow
* embedding of line numbers within code listings.
*/
var PR_NOCODE = 'nocode';
/**
* A set of tokens that can precede a regular expression literal in
* javascript. http://www.mozilla.org/js/language/js20/rationale/syntax.html
* has the full list, but I've removed ones that might be problematic when
* seen in languages that don't support regular expression literals.
*
* <p>
* Specifically, I've removed any keywords that can't precede a regexp literal
* in a syntactically legal javascript program, and I've removed the "in"
* keyword since it's not a keyword in many languages, and might be used as a
* count of inches.
*
* <p>
* The link a above does not accurately describe EcmaScript rules since it
* fails to distinguish between (a=++/b/i) and (a++/b/i) but it works very
* well in practice.
*
* @private
*/
var REGEXP_PRECEDER_PATTERN = function() {
var preceders = [ "!", "!=", "!==", "#", "%", "%=", "&", "&&", "&&=", "&=",
"(", "*", "*=", /* "+", */"+=", ",", /* "-", */"-=", "->", /*
* ".",
* "..",
* "...",
* handled
* below
*/
"/", "/=", ":", "::", ";", "<", "<<", "<<=", "<=", "=", "==", "===",
">", ">=", ">>", ">>=", ">>>", ">>>=", "?", "@", "[", "^", "^=", "^^",
"^^=", "{", "|", "|=", "||", "||=", "~" /* handles =~ and !~ */,
"break", "case", "continue", "delete", "do", "else", "finally",
"instanceof", "return", "throw", "try", "typeof" ];
var pattern = '(?:^^|[+-]';
for ( var i = 0; i < preceders.length; ++i) {
pattern += '|' + preceders[i].replace(/([^=<>:&a-z])/g, '\\$1');
}
pattern += ')\\s*'; // matches at end, and matches empty string
return pattern;
// CAVEAT: this does not properly handle the case where a regular
// expression immediately follows another since a regular expression may
// have flags for case-sensitivity and the like. Having regexp tokens
// adjacent is not valid in any language I'm aware of, so I'm punting.
// TODO: maybe style special characters inside a regexp as punctuation.
}();
// Define regexps here so that the interpreter doesn't have to create an
// object each time the function containing them is called.
// The language spec requires a new object created even if you don't access
// the $1 members.
var pr_amp = /&/g;
var pr_lt = /</g;
var pr_gt = />/g;
var pr_quot = /\"/g;
/** like textToHtml but escapes double quotes to be attribute safe. */
function attribToHtml(str) {
return str.replace(pr_amp, '&').replace(pr_lt, '<').replace(pr_gt,
'>').replace(pr_quot, '"');
}
/** escapest html special characters to html. */
function textToHtml(str) {
return str.replace(pr_amp, '&').replace(pr_lt, '<').replace(pr_gt,
'>');
}
var pr_ltEnt = /</g;
var pr_gtEnt = />/g;
var pr_aposEnt = /'/g;
var pr_quotEnt = /"/g;
var pr_ampEnt = /&/g;
var pr_nbspEnt = / /g;
/** unescapes html to plain text. */
function htmlToText(html) {
var pos = html.indexOf('&');
if (pos < 0) {
return html;
}
// Handle numeric entities specially. We can't use functional substitution
// since that doesn't work in older versions of Safari.
// These should be rare since most browsers convert them to normal chars.
for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0;) {
var end = html.indexOf(';', pos);
if (end >= 0) {
var num = html.substring(pos + 3, end);
var radix = 10;
if (num && num.charAt(0) === 'x') {
num = num.substring(1);
radix = 16;
}
var codePoint = parseInt(num, radix);
if (!isNaN(codePoint)) {
html = (html.substring(0, pos) + String.fromCharCode(codePoint) + html
.substring(end + 1));
}
}
}
return html.replace(pr_ltEnt, '<').replace(pr_gtEnt, '>').replace(
pr_aposEnt, "'").replace(pr_quotEnt, '"').replace(pr_nbspEnt, ' ')
.replace(pr_ampEnt, '&');
}
/** is the given node's innerHTML normally unescaped? */
function isRawContent(node) {
return 'XMP' === node.tagName;
}
var newlineRe = /[\r\n]/g;
/**
* Are newlines and adjacent spaces significant in the given node's innerHTML?
*/
function isPreformatted(node, content) {
// PRE means preformatted, and is a very common case, so don't create
// unnecessary computed style objects.
if ('PRE' === node.tagName) {
return true;
}
if (!newlineRe.test(content)) {
return true;
} // Don't care
var whitespace = '';
// For disconnected nodes, IE has no currentStyle.
if (node.currentStyle) {
whitespace = node.currentStyle.whiteSpace;
} else if (window.getComputedStyle) {
// Firefox makes a best guess if node is disconnected whereas Safari
// returns the empty string.
whitespace = window.getComputedStyle(node, null).whiteSpace;
}
return !whitespace || whitespace === 'pre';
}
function normalizedHtml(node, out) {
switch (node.nodeType) {
case 1: // an element
var name = node.tagName.toLowerCase();
out.push('<', name);
for ( var i = 0; i < node.attributes.length; ++i) {
var attr = node.attributes[i];
if (!attr.specified) {
continue;
}
out.push(' ');
normalizedHtml(attr, out);
}
out.push('>');
for ( var child = node.firstChild; child; child = child.nextSibling) {
normalizedHtml(child, out);
}
if (node.firstChild || !/^(?:br|link|img)$/.test(name)) {
out.push('<\/', name, '>');
}
break;
case 2: // an attribute
out.push(node.name.toLowerCase(), '="', attribToHtml(node.value), '"');
break;
case 3:
case 4: // text
out.push(textToHtml(node.nodeValue));
break;
}
}
/**
* Given a group of {@link RegExp}s, returns a {@code RegExp} that globally
* matches the union o the sets o strings matched d by the input RegExp. Since
* it matches globally, if the input strings have a start-of-input anchor
* (/^.../), it is ignored for the purposes of unioning.
*
* @param {Array.
* <RegExp>} regexs non multiline, non-global regexs.
* @return {RegExp} a global regex.
*/
function combinePrefixPatterns(regexs) {
var capturedGroupIndex = 0;
var needToFoldCase = false;
var ignoreCase = false;
for ( var i = 0, n = regexs.length; i < n; ++i) {
var regex = regexs[i];
if (regex.ignoreCase) {
ignoreCase = true;
} else if (/[a-z]/i.test(regex.source.replace(
/\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) {
needToFoldCase = true;
ignoreCase = false;
break;
}
}
function decodeEscape(charsetPart) {
if (charsetPart.charAt(0) !== '\\') {
return charsetPart.charCodeAt(0);
}
switch (charsetPart.charAt(1)) {
case 'b':
return 8;
case 't':
return 9;
case 'n':
return 0xa;
case 'v':
return 0xb;
case 'f':
return 0xc;
case 'r':
return 0xd;
case 'u':
case 'x':
return parseInt(charsetPart.substring(2), 16)
|| charsetPart.charCodeAt(1);
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
return parseInt(charsetPart.substring(1), 8);
default:
return charsetPart.charCodeAt(1);
}
}
function encodeEscape(charCode) {
if (charCode < 0x20) {
return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16);
}
var ch = String.fromCharCode(charCode);
if (ch === '\\' || ch === '-' || ch === '[' || ch === ']') {
ch = '\\' + ch;
}
return ch;
}
function caseFoldCharset(charSet) {
var charsetParts = charSet.substring(1, charSet.length - 1).match(
new RegExp('\\\\u[0-9A-Fa-f]{4}' + '|\\\\x[0-9A-Fa-f]{2}'
+ '|\\\\[0-3][0-7]{0,2}' + '|\\\\[0-7]{1,2}' + '|\\\\[\\s\\S]'
+ '|-' + '|[^-\\\\]', 'g'));
var groups = [];
var ranges = [];
var inverse = charsetParts[0] === '^';
for ( var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) {
var p = charsetParts[i];
switch (p) {
case '\\B':
case '\\b':
case '\\D':
case '\\d':
case '\\S':
case '\\s':
case '\\W':
case '\\w':
groups.push(p);
continue;
}
var start = decodeEscape(p);
var end;
if (i + 2 < n && '-' === charsetParts[i + 1]) {
end = decodeEscape(charsetParts[i + 2]);
i += 2;
} else {
end = start;
}
ranges.push([ start, end ]);
// If the range might intersect letters, then expand it.
if (!(end < 65 || start > 122)) {
if (!(end < 65 || start > 90)) {
ranges.push([ Math.max(65, start) | 32, Math.min(end, 90) | 32 ]);
}
if (!(end < 97 || start > 122)) {
ranges
.push([ Math.max(97, start) & ~32, Math.min(end, 122) & ~32 ]);
}
}
}
// [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]]
// -> [[1, 12], [14, 14], [16, 17]]
ranges.sort(function(a, b) {
return (a[0] - b[0]) || (b[1] - a[1]);
});
var consolidatedRanges = [];
var lastRange = [ NaN, NaN ];
for ( var i = 0; i < ranges.length; ++i) {
var range = ranges[i];
if (range[0] <= lastRange[1] + 1) {
lastRange[1] = Math.max(lastRange[1], range[1]);
} else {
consolidatedRanges.push(lastRange = range);
}
}
var out = [ '[' ];
if (inverse) {
out.push('^');
}
out.push.apply(out, groups);
for ( var i = 0; i < consolidatedRanges.length; ++i) {
var range = consolidatedRanges[i];
out.push(encodeEscape(range[0]));
if (range[1] > range[0]) {
if (range[1] + 1 > range[0]) {
out.push('-');
}
out.push(encodeEscape(range[1]));
}
}
out.push(']');
return out.join('');
}
function allowAnywhereFoldCaseAndRenumberGroups(regex) {
// Split into character sets, escape sequences, punctuation strings
// like ('(', '(?:', ')', '^'), and runs of characters that do not
// include any of the above.
var parts = regex.source.match(new RegExp('(?:'
+ '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]' // a character set
+ '|\\\\u[A-Fa-f0-9]{4}' // a unicode escape
+ '|\\\\x[A-Fa-f0-9]{2}' // a hex escape
+ '|\\\\[0-9]+' // a back-reference or octal escape
+ '|\\\\[^ux0-9]' // other escape sequence
+ '|\\(\\?[:!=]' // start of a non-capturing group
+ '|[\\(\\)\\^]' // start/emd of a group, or line start
+ '|[^\\x5B\\x5C\\(\\)\\^]+' // run of other characters
+ ')', 'g'));
var n = parts.length;
// Maps captured group numbers to the number they will occupy in
// the output or to -1 if that has not been determined, or to
// undefined if they need not be capturing in the output.
var capturedGroups = [];
// Walk over and identify back references to build the capturedGroups
// mapping.
for ( var i = 0, groupIndex = 0; i < n; ++i) {
var p = parts[i];
if (p === '(') {
// groups are 1-indexed, so max group index is count of '('
++groupIndex;
} else if ('\\' === p.charAt(0)) {
var decimalValue = +p.substring(1);
if (decimalValue && decimalValue <= groupIndex) {
capturedGroups[decimalValue] = -1;
}
}
}
// Renumber groups and reduce capturing groups to non-capturing groups
// where possible.
for ( var i = 1; i < capturedGroups.length; ++i) {
if (-1 === capturedGroups[i]) {
capturedGroups[i] = ++capturedGroupIndex;
}
}
for ( var i = 0, groupIndex = 0; i < n; ++i) {
var p = parts[i];
if (p === '(') {
++groupIndex;
if (capturedGroups[groupIndex] === undefined) {
parts[i] = '(?:';
}
} else if ('\\' === p.charAt(0)) {
var decimalValue = +p.substring(1);
if (decimalValue && decimalValue <= groupIndex) {
parts[i] = '\\' + capturedGroups[groupIndex];
}
}
}
// Remove any prefix anchors so that the output will match anywhere.
// ^^ really does mean an anchored match though.
for ( var i = 0, groupIndex = 0; i < n; ++i) {
if ('^' === parts[i] && '^' !== parts[i + 1]) {
parts[i] = '';
}
}
// Expand letters to groupts to handle mixing of case-sensitive and
// case-insensitive patterns if necessary.
if (regex.ignoreCase && needToFoldCase) {
for ( var i = 0; i < n; ++i) {
var p = parts[i];
var ch0 = p.charAt(0);
if (p.length >= 2 && ch0 === '[') {
parts[i] = caseFoldCharset(p);
} else if (ch0 !== '\\') {
// TODO: handle letters in numeric escapes.
parts[i] = p.replace(/[a-zA-Z]/g, function(ch) {
var cc = ch.charCodeAt(0);
return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']';
});
}
}
}
return parts.join('');
}
var rewritten = [];
for ( var i = 0, n = regexs.length; i < n; ++i) {
var regex = regexs[i];
if (regex.global || regex.multiline) {
throw new Error('' + regex);
}
rewritten.push('(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex)
+ ')');
}
return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g');
}
var PR_innerHtmlWorks = null;
function getInnerHtml(node) {
// inner html is hopelessly broken in Safari 2.0.4 when the content is
// an html description of well formed XML and the containing tag is a PRE
// tag, so we detect that case and emulate innerHTML.
if (null === PR_innerHtmlWorks) {
var testNode = document.createElement('PRE');
testNode.appendChild(document
.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />'));
PR_innerHtmlWorks = !/</.test(testNode.innerHTML);
}
if (PR_innerHtmlWorks) {
var content = node.innerHTML;
// XMP tags contain unescaped entities so require special handling.
if (isRawContent(node)) {
content = textToHtml(content);
} else if (!isPreformatted(node, content)) {
content = content.replace(/(<br\s*\/?>)[\r\n]+/g, '$1').replace(
/(?:[\r\n]+[ \t]*)+/g, ' ');
}
return content;
}
var out = [];
for ( var child = node.firstChild; child; child = child.nextSibling) {
normalizedHtml(child, out);
}
return out.join('');
}
/**
* returns a function that expand tabs to spaces. This function can be fed
* successive chunks of text, and will maintain its own internal state to keep
* track of how tabs are expanded.
*
* @return {function (string) : string} a function that takes plain text and
* return the text with tabs expanded.
* @private
*/
function makeTabExpander(tabWidth) {
var SPACES = ' ';
var charInLine = 0;
return function(plainText) {
// walk over each character looking for tabs and newlines.
// On tabs, expand them. On newlines, reset charInLine.
// Otherwise increment charInLine
var out = null;
var pos = 0;
for ( var i = 0, n = plainText.length; i < n; ++i) {
var ch = plainText.charAt(i);
switch (ch) {
case '\t':
if (!out) {
out = [];
}
out.push(plainText.substring(pos, i));
// calculate how much space we need in front of this part
// nSpaces is the amount of padding -- the number of spaces needed
// to move us to the next column, where columns occur at factors of
// tabWidth.
var nSpaces = tabWidth - (charInLine % tabWidth);
charInLine += nSpaces;
for (; nSpaces >= 0; nSpaces -= SPACES.length) {
out.push(SPACES.substring(0, nSpaces));
}
pos = i + 1;
break;
case '\n':
charInLine = 0;
break;
default:
++charInLine;
}
}
if (!out) {
return plainText;
}
out.push(plainText.substring(pos));
return out.join('');
};
}
var pr_chunkPattern = new RegExp('[^<]+' // A run of characters other than
// '<'
+ '|<\!--[\\s\\S]*?--\>' // an HTML comment
+ '|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>' // a CDATA section
// a probable tag that should not be highlighted
+ '|<\/?[a-zA-Z](?:[^>\"\']|\'[^\']*\'|\"[^\"]*\")*>' + '|<', // A '<'
// that does
// not begin
// a larger
// chunk
'g');
var pr_commentPrefix = /^<\!--/;
var pr_cdataPrefix = /^<!\[CDATA\[/;
var pr_brPrefix = /^<br\b/i;
var pr_tagNameRe = /^<(\/?)([a-zA-Z][a-zA-Z0-9]*)/;
/**
* split markup into chunks of html tags (style null) and plain text (style
* {@link #PR_PLAIN}), converting tags which are significant for tokenization (<br>)
* into their textual equivalent.
*
* @param {string}
* s html where whitespace is considered significant.
* @return {Object} source code and extracted tags.
* @private
*/
function extractTags(s) {
// since the pattern has the 'g' modifier and defines no capturing groups,
// this will return a list of all chunks which we then classify and wrap as
// PR_Tokens
var matches = s.match(pr_chunkPattern);
var sourceBuf = [];
var sourceBufLen = 0;
var extractedTags = [];
if (matches) {
for ( var i = 0, n = matches.length; i < n; ++i) {
var match = matches[i];
if (match.length > 1 && match.charAt(0) === '<') {
if (pr_commentPrefix.test(match)) {
continue;
}
if (pr_cdataPrefix.test(match)) {
// strip CDATA prefix and suffix. Don't unescape since it's CDATA
sourceBuf.push(match.substring(9, match.length - 3));
sourceBufLen += match.length - 12;
} else if (pr_brPrefix.test(match)) {
// <br> tags are lexically significant so convert them to text.
// This is undone later.
sourceBuf.push('\n');
++sourceBufLen;
} else {
if (match.indexOf(PR_NOCODE) >= 0 && isNoCodeTag(match)) {
// A <span class="nocode"> will start a section that should be
// ignored. Continue walking the list until we see a matching end
// tag.
var name = match.match(pr_tagNameRe)[2];
var depth = 1;
var j;
end_tag_loop: for (j = i + 1; j < n; ++j) {
var name2 = matches[j].match(pr_tagNameRe);
if (name2 && name2[2] === name) {
if (name2[1] === '/') {
if (--depth === 0) {
break end_tag_loop;
}
} else {
++depth;
}
}
}
if (j < n) {
extractedTags.push(sourceBufLen, matches.slice(i, j + 1).join(
''));
i = j;
} else { // Ignore unclosed sections.
extractedTags.push(sourceBufLen, match);
}
} else {
extractedTags.push(sourceBufLen, match);
}
}
} else {
var literalText = htmlToText(match);
sourceBuf.push(literalText);
sourceBufLen += literalText.length;
}
}
}
return {
source : sourceBuf.join(''),
tags : extractedTags
};
}
/** True if the given tag contains a class attribute with the nocode class. */
function isNoCodeTag(tag) {
return !!tag
// First canonicalize the representation of attributes
.replace(/\s(\w+)\s*=\s*(?:\"([^\"]*)\"|'([^\']*)'|(\S+))/g,
' $1="$2$3$4"')
// Then look for the attribute we want.
.match(/[cC][lL][aA][sS][sS]=\"[^\"]*\bnocode\b/);
}
/**
* Apply the given language handler to sourceCode and add the resulting
* decorations to out.
*
* @param {number}
* basePos the index of sourceCode within the chunk of source whose
* decorations are already present on out.
*/
function appendDecorations(basePos, sourceCode, langHandler, out) {
if (!sourceCode) {
return;
}
var job = {
source : sourceCode,
basePos : basePos
};
langHandler(job);
out.push.apply(out, job.decorations);
}
/**
* Given triples of [style, pattern, context] returns a lexing function, The
* lexing function interprets the patterns to find token boundaries and
* returns a decoration list of the form [index_0, style_0, index_1, style_1,
* ..., index_n, style_n] where index_n is an index into the sourceCode, and
* style_n is a style constant like PR_PLAIN. index_n-1 <= index_n, and
* style_n-1 applies to all characters in sourceCode[index_n-1:index_n].
*
* The stylePatterns is a list whose elements have the form [style : string,
* pattern : RegExp, DEPRECATED, shortcut : string].
*
* Style is a style constant like PR_PLAIN, or can be a string of the form
* 'lang-FOO', where FOO is a language extension describing the language of
* the portion of the token in $1 after pattern executes. E.g., if style is
* 'lang-lisp', and group 1 contains the text '(hello (world))', then that
* portion of the token will be passed to the registered lisp handler for
* formatting. The text before and after group 1 will be restyled using this
* decorator so decorators should take care that this doesn't result in
* infinite recursion. For example, the HTML lexer rule for SCRIPT elements
* looks something like ['lang-js', /<[s]cript>(.+?)<\/script>/]. This may
* match '<script>foo()<\/script>', which would cause the current decorator
* to be called with '<script>' which would not match the same rule since
* group 1 must not be empty, so it would be instead styled as PR_TAG by the
* generic tag rule. The handler registered for the 'js' extension would then
* be called with 'foo()', and finally, the current decorator would be called
* with '<\/script>' which would not match the original rule and so the
* generic tag rule would identify it as a tag.
*
* Pattern must only match prefixes, and if it matches a prefix, then that
* match is considered a token with the same style.
*
* Context is applied to the last non-whitespace, non-comment token
* recognized.
*
* Shortcut is an optional string of characters, any of which, if the first
* character, gurantee that this pattern and only this pattern matches.
*
* @param {Array}
* shortcutStylePatterns patterns that always start with a known
* character. Must have a shortcut string.
* @param {Array}
* fallthroughStylePatterns patterns that will be tried in order if
* the shortcut ones fail. May have shortcuts.
*
* @return {function (Object)} a function that takes source code and returns a
* list of decorations.
*/
function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) {
var shortcuts = {};
var tokenizer;
(function() {
var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns);
var allRegexs = [];
var regexKeys = {};
for ( var i = 0, n = allPatterns.length; i < n; ++i) {
var patternParts = allPatterns[i];
var shortcutChars = patternParts[3];
if (shortcutChars) {
for ( var c = shortcutChars.length; --c >= 0;) {
shortcuts[shortcutChars.charAt(c)] = patternParts;
}
}
var regex = patternParts[1];
var k = '' + regex;
if (!regexKeys.hasOwnProperty(k)) {
allRegexs.push(regex);
regexKeys[k] = null;
}
}
allRegexs.push(/[\0-\uffff]/);
tokenizer = combinePrefixPatterns(allRegexs);
})();
var nPatterns = fallthroughStylePatterns.length;
var notWs = /\S/;
/**
* Lexes job.source and produces an output array job.decorations of style
* classes preceded by the position at which they start in job.source in
* order.
*
* @param {Object}
* job an object like {@code source: {string} sourceText plain
* text, basePos: {int} position of job.source in the larger chunk
* of sourceCode. }
*/
var decorate = function(job) {
var sourceCode = job.source, basePos = job.basePos;
/**
* Even entries are positions in source in ascending order. Odd enties are
* style markers (e.g., PR_COMMENT) that run from that position until the
* end.
*
* @type {Array.<number|string>}
*/
var decorations = [ basePos, PR_PLAIN ];
var pos = 0; // index into sourceCode
var tokens = sourceCode.match(tokenizer) || [];
var styleCache = {};
for ( var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) {
var token = tokens[ti];
var style = styleCache[token];
var match = void 0;
var isEmbedded;
if (typeof style === 'string') {
isEmbedded = false;
} else {
var patternParts = shortcuts[token.charAt(0)];
if (patternParts) {
match = token.match(patternParts[1]);
style = patternParts[0];
} else {
for ( var i = 0; i < nPatterns; ++i) {
patternParts = fallthroughStylePatterns[i];
match = token.match(patternParts[1]);
if (match) {
style = patternParts[0];
break;
}
}
if (!match) { // make sure that we make progress
style = PR_PLAIN;
}
}
isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5);
if (isEmbedded && !(match && typeof match[1] === 'string')) {
isEmbedded = false;
style = PR_SOURCE;
}
if (!isEmbedded) {
styleCache[token] = style;
}
}
var tokenStart = pos;
pos += token.length;
if (!isEmbedded) {
decorations.push(basePos + tokenStart, style);
} else { // Treat group 1 as an embedded block of source code.
var embeddedSource = match[1];
var embeddedSourceStart = token.indexOf(embeddedSource);
var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length;
if (match[2]) {
// If embeddedSource can be blank, then it would match at the
// beginning which would cause us to infinitely recurse on the
// entire token, so we catch the right context in match[2].
embeddedSourceEnd = token.length - match[2].length;
embeddedSourceStart = embeddedSourceEnd - embeddedSource.length;
}
var lang = style.substring(5);
// Decorate the left of the embedded source
appendDecorations(basePos + tokenStart, token.substring(0,
embeddedSourceStart), decorate, decorations);
// Decorate the embedded source
appendDecorations(basePos + tokenStart + embeddedSourceStart,
embeddedSource, langHandlerForExtension(lang, embeddedSource),
decorations);
// Decorate the right of the embedded section
appendDecorations(basePos + tokenStart + embeddedSourceEnd, token
.substring(embeddedSourceEnd), decorate, decorations);
}
}
job.decorations = decorations;
};
return decorate;
}
/**
* returns a function that produces a list of decorations from source text.
*
* This code treats ", ', and ` as string delimiters, and \ as a string
* escape. It does not recognize perl's qq() style strings. It has no special
* handling for double delimiter escapes as in basic, or the tripled
* delimiters used in python, but should work on those regardless although in
* those cases a single string literal may be broken up into multiple adjacent
* string literals.
*
* It recognizes C, C++, and shell style comments.
*
* @param {Object}
* options a set of optional parameters.
* @return {function (Object)} a function that examines the source code in the
* input job and builds the decoration list.
*/
function sourceDecorator(options) {
var shortcutStylePatterns = [], fallthroughStylePatterns = [];
if (options['tripleQuotedStrings']) {
// '''multi-line-string''', 'single-line-string', and double-quoted
shortcutStylePatterns
.push([
PR_STRING,
/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
null, '\'"' ]);
} else if (options['multiLineStrings']) {
// 'multi-line-string', "multi-line-string"
shortcutStylePatterns
.push([
PR_STRING,
/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,
null, '\'"`' ]);
} else {
// 'single-line-string', "single-line-string"
shortcutStylePatterns.push([ PR_STRING,
/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
null, '"\'' ]);
}
if (options['verbatimStrings']) {
// verbatim-string-literal production from the C# grammar. See issue 93.
fallthroughStylePatterns.push([ PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/,
null ]);
}
if (options['hashComments']) {
if (options['cStyleComments']) {
// Stop C preprocessor declarations at an unclosed open comment
shortcutStylePatterns
.push([
PR_COMMENT,
/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,
null, '#' ]);
fallthroughStylePatterns
.push([
PR_STRING,
/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,
null ]);
} else {
shortcutStylePatterns.push([ PR_COMMENT, /^#[^\r\n]*/, null, '#' ]);
}
}
if (options['cStyleComments']) {
fallthroughStylePatterns.push([ PR_COMMENT, /^\/\/[^\r\n]*/, null ]);
fallthroughStylePatterns.push([ PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/,
null ]);
}
if (options['regexLiterals']) {
var REGEX_LITERAL = (
// A regular expression literal starts with a slash that is
// not followed by * or / so that it is not confused with
// comments.
'/(?=[^/*])'
// and then contains any number of raw characters,
+ '(?:[^/\\x5B\\x5C]'
// escape sequences (\x5C),
+ '|\\x5C[\\s\\S]'
// or non-nesting character sets (\x5B\x5D);
+ '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+'
// finally closed by a /.
+ '/');
fallthroughStylePatterns
.push([
'lang-regex',
new RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL
+ ')') ]);
}
var keywords = options['keywords'].replace(/^\s+|\s+$/g, '');
if (keywords.length) {
fallthroughStylePatterns.push([ PR_KEYWORD,
new RegExp('^(?:' + keywords.replace(/\s+/g, '|') + ')\\b'), null ]);
}
shortcutStylePatterns.push([ PR_PLAIN, /^\s+/, null, ' \r\n\t\xA0' ]);
fallthroughStylePatterns.push(
// TODO(mikesamuel): recognize non-latin letters and numerals in idents
[ PR_LITERAL, /^@[a-z_$][a-z_$@0-9]*/i, null ], [ PR_TYPE,
/^@?[A-Z]+[a-z][A-Za-z_$@0-9]*/, null ], [ PR_PLAIN,
/^[a-z_$][a-z_$@0-9]*/i, null ], [ PR_LITERAL, new RegExp('^(?:'
// A hex number
+ '0x[a-f0-9]+'
// or an octal or decimal number,
+ '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
// possibly in scientific notation
+ '(?:e[+\\-]?\\d+)?' + ')'
// with an optional modifier like UL for unsigned long
+ '[a-z]*', 'i'), null, '0123456789' ], [ PR_PUNCTUATION,
/^.[^\s\w\.$@\'\"\`\/\#]*/, null ]);
return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns);
}
var decorateSource = sourceDecorator({
'keywords' : ALL_KEYWORDS,
'hashComments' : true,
'cStyleComments' : true,
'multiLineStrings' : true,
'regexLiterals' : true
});
/**
* Breaks {@code job.source} around style boundaries in
* {@code job.decorations} while re-interleaving {@code job.extractedTags},
* and leaves the result in {@code job.prettyPrintedHtml}.
*
* @param {Object}
* job like { source: {string} source as plain text, extractedTags:
* {Array.<number|string>} extractedTags chunks of raw html preceded
* by their position in {@code job.source} in order decorations:
* {Array.<number|string} an array of style classes preceded by the
* position at which they start in job.source in order }
* @private
*/
function recombineTagsAndDecorations(job) {
var sourceText = job.source;
var extractedTags = job.extractedTags;
var decorations = job.decorations;
var html = [];
// index past the last char in sourceText written to html
var outputIdx = 0;
var openDecoration = null;
var currentDecoration = null;
var tagPos = 0; // index into extractedTags
var decPos = 0; // index into decorations
var tabExpander = makeTabExpander(window['PR_TAB_WIDTH']);
var adjacentSpaceRe = /([\r\n ]) /g;
var startOrSpaceRe = /(^| ) /gm;
var newlineRe = /\r\n?|\n/g;
var trailingSpaceRe = /[ \r\n]$/;
var lastWasSpace = true; // the last text chunk emitted ended with a space.
// A helper function that is responsible for opening sections of decoration
// and outputing properly escaped chunks of source
function emitTextUpTo(sourceIdx) {
if (sourceIdx > outputIdx) {
if (openDecoration && openDecoration !== currentDecoration) {
// Close the current decoration
html.push('</span>');
openDecoration = null;
}
if (!openDecoration && currentDecoration) {
openDecoration = currentDecoration;
html.push('<span class="', openDecoration, '">');
}
// This interacts badly with some wikis which introduces paragraph tags
// into pre blocks for some strange reason.
// It's necessary for IE though which seems to lose the preformattedness
// of <pre> tags when their innerHTML is assigned.
// http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html
// and it serves to undo the conversion of <br>s to newlines done in
// chunkify.
var htmlChunk = textToHtml(
tabExpander(sourceText.substring(outputIdx, sourceIdx))).replace(
lastWasSpace ? startOrSpaceRe : adjacentSpaceRe, '$1 ');
// Keep track of whether we need to escape space at the beginning of the
// next chunk.
lastWasSpace = trailingSpaceRe.test(htmlChunk);
// IE collapses multiple adjacient <br>s into 1 line break.
// Prefix every <br> with ' ' can prevent such IE's behavior.
var lineBreakHtml = window['_pr_isIE6']() ? ' <br />' : '<br />';
html.push(htmlChunk.replace(newlineRe, lineBreakHtml));
outputIdx = sourceIdx;
}
}
while (true) {
// Determine if we're going to consume a tag this time around. Otherwise
// we consume a decoration or exit.
var outputTag;
if (tagPos < extractedTags.length) {
if (decPos < decorations.length) {
// Pick one giving preference to extractedTags since we shouldn't open
// a new style that we're going to have to immediately close in order
// to output a tag.
outputTag = extractedTags[tagPos] <= decorations[decPos];
} else {
outputTag = true;
}
} else {
outputTag = false;
}
// Consume either a decoration or a tag or exit.
if (outputTag) {
emitTextUpTo(extractedTags[tagPos]);
if (openDecoration) {
// Close the current decoration
html.push('</span>');
openDecoration = null;
}
html.push(extractedTags[tagPos + 1]);
tagPos += 2;
} else if (decPos < decorations.length) {
emitTextUpTo(decorations[decPos]);
currentDecoration = decorations[decPos + 1];
decPos += 2;
} else {
break;
}
}
emitTextUpTo(sourceText.length);
if (openDecoration) {
html.push('</span>');
}
job.prettyPrintedHtml = html.join('');
}
/** Maps language-specific file extensions to handlers. */
var langHandlerRegistry = {};
/**
* Register a language handler for the given file extensions.
*
* @param {function
* (Object)} handler a function from source code to a list of
* decorations. Takes a single argument job which describes the state
* of the computation. The single parameter has the form {@code {
* source: {string} as plain text. decorations: {Array.<number|string>}
* an array of style classes preceded by the position at which they
* start in job.source in order. The language handler should assigned
* this field. basePos: {int} the position of source in the larger
* source chunk. All positions in the output decorations array are
* relative to the larger source chunk. } }
* @param {Array.
* <string>} fileExtensions
*/
function registerLangHandler(handler, fileExtensions) {
for ( var i = fileExtensions.length; --i >= 0;) {
var ext = fileExtensions[i];
if (!langHandlerRegistry.hasOwnProperty(ext)) {
langHandlerRegistry[ext] = handler;
} else if ('console' in window) {
console.warn('cannot override language handler %s', ext);
}
}
}
function langHandlerForExtension(extension, source) {
if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) {
// Treat it as markup if the first non whitespace character is a < and
// the last non-whitespace character is a >.
extension = /^\s*</.test(source) ? 'default-markup' : 'default-code';
}
return langHandlerRegistry[extension];
}
registerLangHandler(decorateSource, [ 'default-code' ]);
registerLangHandler(createSimpleLexer([], [ [ PR_PLAIN, /^[^<?]+/ ],
[ PR_DECLARATION, /^<!\w[^>]*(?:>|$)/ ],
[ PR_COMMENT, /^<\!--[\s\S]*?(?:-\->|$)/ ],
// Unescaped content in an unknown language
[ 'lang-', /^<\?([\s\S]+?)(?:\?>|$)/ ],
[ 'lang-', /^<%([\s\S]+?)(?:%>|$)/ ],
[ PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/ ],
[ 'lang-', /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i ],
// Unescaped content in javascript. (Or possibly vbscript).
[ 'lang-js', /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i ],
// Contains unescaped stylesheet content
[ 'lang-css', /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i ],
[ 'lang-in.tag', /^(<\/?[a-z][^<>]*>)/i ] ]), [ 'default-markup', 'htm',
'html', 'mxml', 'xhtml', 'xml', 'xsl' ]);
registerLangHandler(createSimpleLexer([
[ PR_PLAIN, /^[\s]+/, null, ' \t\r\n' ],
[ PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\'' ] ], [
[ PR_TAG, /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i ],
[ PR_ATTRIB_NAME, /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i ],
[ 'lang-uq.val', /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/ ],
[ PR_PUNCTUATION, /^[=<>\/]+/ ],
[ 'lang-js', /^on\w+\s*=\s*\"([^\"]+)\"/i ],
[ 'lang-js', /^on\w+\s*=\s*\'([^\']+)\'/i ],
[ 'lang-js', /^on\w+\s*=\s*([^\"\'>\s]+)/i ],
[ 'lang-css', /^style\s*=\s*\"([^\"]+)\"/i ],
[ 'lang-css', /^style\s*=\s*\'([^\']+)\'/i ],
[ 'lang-css', /^style\s*=\s*([^\"\'>\s]+)/i ] ]), [ 'in.tag' ]);
registerLangHandler(
createSimpleLexer([], [ [ PR_ATTRIB_VALUE, /^[\s\S]+/ ] ]), [ 'uq.val' ]);
registerLangHandler(sourceDecorator({
'keywords' : CPP_KEYWORDS,
'hashComments' : true,
'cStyleComments' : true
}), [ 'c', 'cc', 'cpp', 'cxx', 'cyc', 'm' ]);
registerLangHandler(sourceDecorator({
'keywords' : 'null true false'
}), [ 'json' ]);
registerLangHandler(sourceDecorator({
'keywords' : CSHARP_KEYWORDS,
'hashComments' : true,
'cStyleComments' : true,
'verbatimStrings' : true
}), [ 'cs' ]);
registerLangHandler(sourceDecorator({
'keywords' : JAVA_KEYWORDS,
'cStyleComments' : true
}), [ 'java' ]);
registerLangHandler(sourceDecorator({
'keywords' : SH_KEYWORDS,
'hashComments' : true,
'multiLineStrings' : true
}), [ 'bsh', 'csh', 'sh' ]);
registerLangHandler(sourceDecorator({
'keywords' : PYTHON_KEYWORDS,
'hashComments' : true,
'multiLineStrings' : true,
'tripleQuotedStrings' : true
}), [ 'cv', 'py' ]);
registerLangHandler(sourceDecorator({
'keywords' : PERL_KEYWORDS,
'hashComments' : true,
'multiLineStrings' : true,
'regexLiterals' : true
}), [ 'perl', 'pl', 'pm' ]);
registerLangHandler(sourceDecorator({
'keywords' : RUBY_KEYWORDS,
'hashComments' : true,
'multiLineStrings' : true,
'regexLiterals' : true
}), [ 'rb' ]);
registerLangHandler(sourceDecorator({
'keywords' : JSCRIPT_KEYWORDS,
'cStyleComments' : true,
'regexLiterals' : true
}), [ 'js' ]);
registerLangHandler(createSimpleLexer([], [ [ PR_STRING, /^[\s\S]+/ ] ]),
[ 'regex' ]);
function applyDecorator(job) {
var sourceCodeHtml = job.sourceCodeHtml;
var opt_langExtension = job.langExtension;
// Prepopulate output in case processing fails with an exception.
job.prettyPrintedHtml = sourceCodeHtml;
try {
// Extract tags, and convert the source code to plain text.
var sourceAndExtractedTags = extractTags(sourceCodeHtml);
/**
* Plain text.
*
* @type {string}
*/
var source = sourceAndExtractedTags.source;
job.source = source;
job.basePos = 0;
/**
* Even entries are positions in source in ascending order. Odd entries
* are tags that were extracted at that position.
*
* @type {Array.<number|string>}
*/
job.extractedTags = sourceAndExtractedTags.tags;
// Apply the appropriate language handler
langHandlerForExtension(opt_langExtension, source)(job);
// Integrate the decorations and tags back into the source code to produce
// a decorated html string which is left in job.prettyPrintedHtml.
recombineTagsAndDecorations(job);
} catch (e) {
if ('console' in window) {
console.log(e);
console.trace();
}
}
}
function prettyPrintOne(sourceCodeHtml, opt_langExtension) {
var job = {
sourceCodeHtml : sourceCodeHtml,
langExtension : opt_langExtension
};
applyDecorator(job);
return job.prettyPrintedHtml;
}
function prettyPrint(opt_whenDone) {
var isIE678 = window['_pr_isIE6']();
var ieNewline = isIE678 === 6 ? '\r\n' : '\r';
// See bug 71 and http://stackoverflow.com/questions/136443/why-doesnt-ie7-
// fetch a list of nodes to rewrite
var codeSegments = [ document.getElementsByTagName('pre'),
document.getElementsByTagName('code'),
document.getElementsByTagName('xmp') ];
var elements = [];
for ( var i = 0; i < codeSegments.length; ++i) {
for ( var j = 0, n = codeSegments[i].length; j < n; ++j) {
elements.push(codeSegments[i][j]);
}
}
codeSegments = null;
var clock = Date;
if (!clock['now']) {
clock = {
'now' : function() {
return (new Date).getTime();
}
};
}
// The loop is broken into a series of continuations to make sure that we
// don't make the browser unresponsive when rewriting a large page.
var k = 0;
var prettyPrintingJob;
function doWork() {
var endTime = (window['PR_SHOULD_USE_CONTINUATION'] ? clock.now() + 250 /* ms */
: Infinity);
for (; k < elements.length && clock.now() < endTime; k++) {
var cs = elements[k];
if (cs.className && cs.className.indexOf('prettyprint') >= 0) {
// If the classes includes a language extensions, use it.
// Language extensions can be specified like
// <pre class="prettyprint lang-cpp">
// the language extension "cpp" is used to find a language handler as
// passed to PR_registerLangHandler.
var langExtension = cs.className.match(/\blang-(\w+)\b/);
if (langExtension) {
langExtension = langExtension[1];
}
// make sure this is not nested in an already prettified element
var nested = false;
for ( var p = cs.parentNode; p; p = p.parentNode) {
if ((p.tagName === 'pre' || p.tagName === 'code' || p.tagName === 'xmp')
&& p.className && p.className.indexOf('prettyprint') >= 0) {
nested = true;
break;
}
}
if (!nested) {
// fetch the content as a snippet of properly escaped HTML.
// Firefox adds newlines at the end.
var content = getInnerHtml(cs);
content = content.replace(/(?:\r\n?|\n)$/, '');
// do the pretty printing
prettyPrintingJob = {
sourceCodeHtml : content,
langExtension : langExtension,
sourceNode : cs
};
applyDecorator(prettyPrintingJob);
replaceWithPrettyPrintedHtml();
}
}
}
if (k < elements.length) {
// finish up in a continuation
setTimeout(doWork, 250);
} else if (opt_whenDone) {
opt_whenDone();
}
}
function replaceWithPrettyPrintedHtml() {
var newContent = prettyPrintingJob.prettyPrintedHtml;
if (!newContent) {
return;
}
var cs = prettyPrintingJob.sourceNode;
// push the prettified html back into the tag.
if (!isRawContent(cs)) {
// just replace the old html with the new
cs.innerHTML = newContent;
} else {
// we need to change the tag to a <pre> since <xmp>s do not allow
// embedded tags such as the span tags used to attach styles to
// sections of source code.
var pre = document.createElement('PRE');
for ( var i = 0; i < cs.attributes.length; ++i) {
var a = cs.attributes[i];
if (a.specified) {
var aname = a.name.toLowerCase();
if (aname === 'class') {
pre.className = a.value; // For IE 6
} else {
pre.setAttribute(a.name, a.value);
}
}
}
pre.innerHTML = newContent;
// remove the old
cs.parentNode.replaceChild(pre, cs);
cs = pre;
}
// Replace <br>s with line-feeds so that copying and pasting works
// on IE 6.
// Doing this on other browsers breaks lots of stuff since \r\n is
// treated as two newlines on Firefox, and doing this also slows
// down rendering.
if (isIE678 && cs.tagName === 'PRE') {
var lineBreaks = cs.getElementsByTagName('br');
for ( var j = lineBreaks.length; --j >= 0;) {
var lineBreak = lineBreaks[j];
lineBreak.parentNode.replaceChild(document.createTextNode(ieNewline),
lineBreak);
}
}
}
doWork();
}
window['PR_normalizedHtml'] = normalizedHtml;
window['prettyPrintOne'] = prettyPrintOne;
window['prettyPrint'] = prettyPrint;
window['PR'] = {
'combinePrefixPatterns' : combinePrefixPatterns,
'createSimpleLexer' : createSimpleLexer,
'registerLangHandler' : registerLangHandler,
'sourceDecorator' : sourceDecorator,
'PR_ATTRIB_NAME' : PR_ATTRIB_NAME,
'PR_ATTRIB_VALUE' : PR_ATTRIB_VALUE,
'PR_COMMENT' : PR_COMMENT,
'PR_DECLARATION' : PR_DECLARATION,
'PR_KEYWORD' : PR_KEYWORD,
'PR_LITERAL' : PR_LITERAL,
'PR_NOCODE' : PR_NOCODE,
'PR_PLAIN' : PR_PLAIN,
'PR_PUNCTUATION' : PR_PUNCTUATION,
'PR_SOURCE' : PR_SOURCE,
'PR_STRING' : PR_STRING,
'PR_TAG' : PR_TAG,
'PR_TYPE' : PR_TYPE
};
})();
|
smgoller/geode
|
geode-pulse/src/main/webapp/scripts/multiselect/prettify.js
|
JavaScript
|
apache-2.0
| 57,146
|
// test AccessorNode
var assert = require('assert');
var approx = require('../../../tools/approx');
var math = require('../../../index');
var bigmath = require('../../../index').create({number: 'BigNumber'});
var Node = math.expression.node.Node;
var ConstantNode = math.expression.node.ConstantNode;
var OperatorNode = math.expression.node.OperatorNode;
var SymbolNode = math.expression.node.SymbolNode;
var AccessorNode = math.expression.node.AccessorNode;
var IndexNode = math.expression.node.IndexNode;
var RangeNode = math.expression.node.RangeNode;
describe('AccessorNode', function() {
it ('should create a AccessorNode', function () {
var n = new AccessorNode(new Node(), new IndexNode([]));
assert(n instanceof AccessorNode);
assert(n instanceof Node);
assert.equal(n.type, 'AccessorNode');
});
it ('should have isAccessorNode', function () {
var node = new AccessorNode(new Node(), new IndexNode([]));
assert(node.isAccessorNode);
});
it ('should throw an error when calling with wrong arguments', function () {
assert.throws(function () {new AccessorNode()}, TypeError);
assert.throws(function () {new AccessorNode('a', new IndexNode([]))}, TypeError);
assert.throws(function () {new AccessorNode(new Node, new IndexNode([2, 3]))}, TypeError);
assert.throws(function () {new AccessorNode(new Node, new IndexNode([new Node(), 3]))}, TypeError);
});
it ('should throw an error when calling without new operator', function () {
assert.throws(function () {AccessorNode(new Node(), new IndexNode([]))}, SyntaxError);
});
it ('should get the name of an AccessorNode', function () {
var n = new AccessorNode(new SymbolNode('a'), new IndexNode([new ConstantNode('toString')]));
assert.equal(n.name, 'toString');
var n = new AccessorNode(new SymbolNode('a'), new IndexNode([new ConstantNode(1)]));
assert.equal(n.name, '');
});
it ('should compile a AccessorNode', function () {
var a = new bigmath.expression.node.SymbolNode('a');
var index = new bigmath.expression.node.IndexNode([
new bigmath.expression.node.ConstantNode(2),
new bigmath.expression.node.ConstantNode(1)
]);
var n = new bigmath.expression.node.AccessorNode(a, index);
var expr = n.compile();
var scope = {
a: [[1, 2], [3, 4]]
};
assert.equal(expr.eval(scope), 3);
});
it ('should compile a AccessorNode with range and context parameters', function () {
var a = new SymbolNode('a');
var index = new IndexNode([
new ConstantNode(2),
new RangeNode(
new ConstantNode(1),
new SymbolNode('end')
)
]);
var n = new AccessorNode(a, index);
var expr = n.compile();
var scope = {
a: [[1, 2], [3, 4]]
};
assert.deepEqual(expr.eval(scope), [[3, 4]]);
});
it ('should compile a AccessorNode with a property', function () {
var a = new SymbolNode('a');
var index = new IndexNode([new ConstantNode('b')]);
var n = new AccessorNode(a, index);
var expr = n.compile();
var scope = {
a: { b: 42 }
};
assert.deepEqual(expr.eval(scope), 42);
});
it ('should throw a one-based index error when out of range (Array)', function () {
var a = new SymbolNode('a');
var index = new IndexNode([new ConstantNode(4)]);
var n = new AccessorNode(a, index);
var expr = n.compile();
var scope = {
a: [1,2,3]
};
assert.throws(function () { expr.eval(scope) }, /Index out of range \(4 > 3\)/);
});
it ('should throw a one-based index error when out of range (Matrix)', function () {
var a = new SymbolNode('a');
var index = new IndexNode([new ConstantNode(4)]);
var n = new AccessorNode(a, index);
var expr = n.compile();
var scope = {
a: math.matrix([1,2,3])
};
assert.throws(function () { expr.eval(scope) }, /Index out of range \(4 > 3\)/);
});
it ('should throw a one-based index error when out of range (string)', function () {
var a = new SymbolNode('a');
var index = new IndexNode([new ConstantNode(4)]);
var n = new AccessorNode(a, index);
var expr = n.compile();
var scope = {
a: 'hey'
};
assert.throws(function () { expr.eval(scope) }, /Index out of range \(4 > 3\)/);
});
it ('should throw an error when applying a matrix index onto an object', function () {
var a = new SymbolNode('a');
var index = new IndexNode([new ConstantNode(4)]);
var n = new AccessorNode(a, index);
var expr = n.compile();
var scope = {
a: {}
};
assert.throws(function () { expr.eval(scope) }, /Cannot apply a numeric index as object property/);
});
it ('should throw an error when applying an index onto a scalar', function () {
var a = new SymbolNode('a');
var index = new IndexNode([new ConstantNode(4)]);
var n = new AccessorNode(a, index);
var expr = n.compile();
var scope = {
a: 42
};
assert.throws(function () { expr.eval(scope) }, /Cannot apply index: unsupported type of object/);
});
it ('should compile a AccessorNode with negative step range and context parameters', function () {
var a = new SymbolNode('a');
var index = new IndexNode([
new ConstantNode(2),
new RangeNode(
new SymbolNode('end'),
new ConstantNode(1),
new ConstantNode(-1)
)
]);
var n = new AccessorNode(a, index);
var expr = n.compile();
var scope = {
a: [[1, 2], [3, 4]]
};
assert.deepEqual(expr.eval(scope), [[4, 3]]);
});
it ('should compile a AccessorNode with "end" both as value and in a range', function () {
var a = new SymbolNode('a');
var index = new IndexNode([
new SymbolNode('end'),
new RangeNode(
new ConstantNode(1),
new SymbolNode('end')
)
]);
var n = new AccessorNode(a, index);
var expr = n.compile();
var scope = {
a: [[1, 2], [3, 4]]
};
assert.deepEqual(expr.eval(scope), [[3, 4]]);
});
it ('should compile a AccessorNode with bignumber setting', function () {
var a = new bigmath.expression.node.SymbolNode('a');
var b = new bigmath.expression.node.ConstantNode(2);
var c = new bigmath.expression.node.ConstantNode(1);
var n = new bigmath.expression.node.AccessorNode(a,
new bigmath.expression.node.IndexNode([b, c]));
var expr = n.compile();
var scope = {
a: [[1, 2], [3, 4]]
};
assert.deepEqual(expr.eval(scope), 3);
});
it ('should filter an AccessorNode', function () {
var a = new SymbolNode('a');
var b = new ConstantNode(2);
var c = new ConstantNode(1);
var index = new IndexNode([b, c]);
var n = new AccessorNode(a, index);
assert.deepEqual(n.filter(function (node) {return node.isAccessorNode}), [n]);
assert.deepEqual(n.filter(function (node) {return node.isSymbolNode}), [a]);
assert.deepEqual(n.filter(function (node) {return node.isRangeNode}), []);
assert.deepEqual(n.filter(function (node) {return node.isConstantNode}), [b, c]);
assert.deepEqual(n.filter(function (node) {return node.isConstantNode && node.value == '2'}), [b]);
assert.deepEqual(n.filter(function (node) {return node.isConstantNode && node.value == '4'}), []);
});
it ('should filter an empty AccessorNode', function () {
var n = new AccessorNode(new SymbolNode('a'), new IndexNode([]));
assert.deepEqual(n.filter(function (node) {return node.isAccessorNode}), [n]);
assert.deepEqual(n.filter(function (node) {return node.isConstantNode}), []);
});
it ('should run forEach on an AccessorNode', function () {
var a = new SymbolNode('a');
var b = new ConstantNode(2);
var c = new ConstantNode(1);
var index = new IndexNode([b, c]);
var n = new AccessorNode(a, index);
var nodes = [];
var paths = [];
n.forEach(function (node, path, parent) {
nodes.push(node);
paths.push(path);
assert.strictEqual(parent, n);
});
assert.equal(nodes.length, 2);
assert.strictEqual(nodes[0], a);
assert.strictEqual(nodes[1], index);
assert.deepEqual(paths, ['object', 'index']);
});
it ('should map an AccessorNode', function () {
var a = new SymbolNode('a');
var b = new ConstantNode(2);
var c = new ConstantNode(1);
var index = new IndexNode([b, c]);
var n = new AccessorNode(a, index);
var nodes = [];
var paths = [];
var e = new SymbolNode('c');
var f = n.map(function (node, path, parent) {
nodes.push(node);
paths.push(path);
assert.strictEqual(parent, n);
return node instanceof SymbolNode ? e : node;
});
assert.equal(nodes.length, 2);
assert.strictEqual(nodes[0], a);
assert.strictEqual(nodes[1], index);
assert.deepEqual(paths, ['object', 'index']);
assert.notStrictEqual(f, n);
assert.deepEqual(f.object, e);
assert.deepEqual(f.index.dimensions[0], b);
assert.deepEqual(f.index.dimensions[1], c);
});
it ('should throw an error when the map callback does not return a node', function () {
var a = new SymbolNode('a');
var b = new ConstantNode(2);
var c = new ConstantNode(1);
var n = new AccessorNode(a, new IndexNode([b, c]));
assert.throws(function () {
n.map(function () {});
}, /Callback function must return a Node/)
});
it ('should transform an IndexNodes object', function () {
var a = new SymbolNode('a');
var b = new ConstantNode(2);
var c = new ConstantNode(1);
var n = new AccessorNode(a, new IndexNode([b, c]));
var e = new SymbolNode('c');
var f = n.transform(function (node) {
return node instanceof SymbolNode ? e : node;
});
assert.notStrictEqual(f, n);
assert.deepEqual(f.object, e);
assert.deepEqual(f.index.dimensions[0], b);
assert.deepEqual(f.index.dimensions[1], c);
});
it ('should transform an IndexNodes (nested) parameters', function () {
var a = new SymbolNode('a');
var b = new ConstantNode(2);
var c = new ConstantNode(1);
var n = new AccessorNode(a, new IndexNode([b, c]));
var e = new SymbolNode('c');
var f = n.transform(function (node) {
return node instanceof ConstantNode && node.value == '1' ? e : node;
});
assert.notStrictEqual(f, n);
assert.deepEqual(f.object, a);
assert.deepEqual(f.index.dimensions[0], b);
assert.deepEqual(f.index.dimensions[1], e);
});
it ('should transform an AccessorNode itself', function () {
var a = new SymbolNode('a');
var b = new ConstantNode(2);
var c = new ConstantNode(1);
var n = new AccessorNode(a, new IndexNode([b, c]));
var e = new ConstantNode(5);
var f = n.transform(function (node) {
return node instanceof AccessorNode ? e : node;
});
assert.notStrictEqual(f, n);
assert.deepEqual(f, e);
});
it ('should clone an AccessorNode', function () {
var a = new SymbolNode('a');
var b = new ConstantNode(2);
var c = new ConstantNode(1);
var n = new AccessorNode(a, new IndexNode([b, c]));
var d = n.clone();
assert(d instanceof AccessorNode);
assert.deepEqual(d, n);
assert.notStrictEqual(d, n);
assert.strictEqual(d.object, n.object);
assert.strictEqual(d.index, n.index);
assert.strictEqual(d.index.dimensions[0], n.index.dimensions[0]);
assert.strictEqual(d.index.dimensions[1], n.index.dimensions[1]);
});
it ('should test equality of an Node', function () {
var a = new SymbolNode('a');
var b = new ConstantNode(2);
var c = new ConstantNode(1);
var node1 = new AccessorNode(a, new IndexNode([b, c]));
var a = new SymbolNode('a');
var b = new SymbolNode('b');
var c = new ConstantNode(1);
var node2 = new AccessorNode(a, new IndexNode([b, c]));
var a = new SymbolNode('a');
var b = new ConstantNode(2);
var c = new ConstantNode(1);
var node3 = new AccessorNode(a, new IndexNode([b, c]));
assert.strictEqual(node1.equals(null), false);
assert.strictEqual(node1.equals(undefined), false);
assert.strictEqual(node1.equals(node2), false);
assert.strictEqual(node1.equals(node3), true);
});
it ('should stringify an AccessorNode', function () {
var a = new SymbolNode('a');
var index = new IndexNode([
new ConstantNode(2),
new ConstantNode(1)
]);
var n = new AccessorNode(a, index);
assert.equal(n.toString(), 'a[2, 1]');
var n2 = new AccessorNode(a, new IndexNode([]));
assert.equal(n2.toString(), 'a[]')
});
it ('should stringify an AccessorNode with parentheses', function () {
var a = new SymbolNode('a');
var b = new SymbolNode('b');
var add = new OperatorNode('+', 'add', [a, b]);
var bar = new AccessorNode(add, new IndexNode([new ConstantNode('bar')]));
assert.equal(bar.toString(), '(a + b)["bar"]');
});
it ('should stringify nested AccessorNode', function () {
var a = new SymbolNode('a');
var foo = new AccessorNode(a, new IndexNode([new ConstantNode('foo')]));
var bar = new AccessorNode(foo, new IndexNode([new ConstantNode('bar')]));
assert.equal(bar.toString(), 'a["foo"]["bar"]');
});
it ('should stringigy an AccessorNode with custom toString', function () {
//Also checks if the custom functions get passed on to the children
var customFunction = function (node, options) {
if (node.type === 'AccessorNode') {
var string = node.object.toString(options) + ' at ';
node.index.dimensions.forEach(function (range) {
string += range.toString(options) + ', ';
});
return string;
}
else if (node.type === 'ConstantNode') {
return 'const(' + node.value + ', ' + node.valueType + ')'
}
};
var a = new SymbolNode('a');
var b = new ConstantNode(1);
var c = new ConstantNode(2);
var n = new AccessorNode(a, new IndexNode([b, c]));
assert.equal(n.toString({handler: customFunction}), 'a at const(1, number), const(2, number), ');
});
it ('should LaTeX an AccessorNode', function () {
var a = new SymbolNode('a');
var index = new IndexNode([
new ConstantNode(2),
new ConstantNode(1)
]);
var n = new AccessorNode(a, index);
assert.equal(n.toTex(), ' a_{2,1}');
var n2 = new AccessorNode(a, new IndexNode([]));
assert.equal(n2.toTex(), ' a_{}')
});
it ('should LaTeX an AccessorNode with custom toTex', function () {
//Also checks if the custom functions get passed on to the children
var customFunction = function (node, options) {
if (node.type === 'AccessorNode') {
var latex = node.object.toTex(options) + ' at ';
node.index.dimensions.forEach(function (range) {
latex += range.toTex(options) + ', ';
});
return latex;
}
else if (node.type === 'ConstantNode') {
return 'const\\left(' + node.value + ', ' + node.valueType + '\\right)'
}
};
var a = new SymbolNode('a');
var b = new ConstantNode(1);
var c = new ConstantNode(2);
var n = new AccessorNode(a, new IndexNode([b, c]));
assert.equal(n.toTex({handler: customFunction}), ' a at const\\left(1, number\\right), const\\left(2, number\\right), ');
});
});
|
ChatterBoxGames/ChatterBot
|
node_modules/mathjs/test/expression/node/AccessorNode.test.js
|
JavaScript
|
gpl-2.0
| 15,328
|
var class_mix_e_r_p_1_1_net_1_1_schemas_1_1_policy_1_1_data_1_1_is_locked_out_till_procedure =
[
[ "IsLockedOutTillProcedure", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_policy_1_1_data_1_1_is_locked_out_till_procedure.html#aedbda9bd75c806e737c67228a18c1969", null ],
[ "IsLockedOutTillProcedure", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_policy_1_1_data_1_1_is_locked_out_till_procedure.html#abaa8d0635488b391d24724adb07e74ea", null ],
[ "Execute", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_policy_1_1_data_1_1_is_locked_out_till_procedure.html#aa5ee2d7b8052b5c6b2aaa96a6324e2cf", null ],
[ "ObjectName", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_policy_1_1_data_1_1_is_locked_out_till_procedure.html#a9b816b444c0c517ab6021d42b593a8f9", null ],
[ "ObjectNamespace", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_policy_1_1_data_1_1_is_locked_out_till_procedure.html#aa46c3cdc07e8c431f4b8f94339852ba9", null ],
[ "_LoginId", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_policy_1_1_data_1_1_is_locked_out_till_procedure.html#a00a022b2fc71ca2a55e9bcab9f090bd3", null ],
[ "_UserId", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_policy_1_1_data_1_1_is_locked_out_till_procedure.html#af3967d322eafb42a07a8bb571519bc89", null ],
[ "Catalog", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_policy_1_1_data_1_1_is_locked_out_till_procedure.html#a574706f452de44f6313533f252b7f903", null ],
[ "UserId", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_policy_1_1_data_1_1_is_locked_out_till_procedure.html#a0db729ec03b48bd56a14fb1ad3b39a92", null ]
];
|
mixerp/mixerp
|
docs/api/class_mix_e_r_p_1_1_net_1_1_schemas_1_1_policy_1_1_data_1_1_is_locked_out_till_procedure.js
|
JavaScript
|
gpl-3.0
| 1,547
|
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*
* @category Shopware
* @package MediaManager
* @subpackage Controller
* @version $Id$
* @author shopware AG
*/
/**
* Shopware UI - Media Manager Album Controller
*
* this file handles the album administration.
*/
//{namespace name=backend/media_manager/view/main}
//{block name="backend/media_manager/controller/album"}
Ext.define('Shopware.apps.MediaManager.controller.Album', {
/**
* Extend from the standard ExtJS 4 controller
* @string
*/
extend: 'Ext.app.Controller',
/**
* Define references for the different parts of our application. The
* references are parsed by ExtJS and Getter methods are automatically created.
*
* Example: { ref : 'grid', selector : 'grid' } transforms to this.getGrid();
* { ref : 'addBtn', selector : 'button[action=add]' } transforms to this.getAddBtn()
*
* @object
*/
refs: [
{ ref: 'albumTree', selector: 'mediamanager-album-tree' },
{ ref: 'mediaView', selector: 'mediamanager-media-view' }
],
/**
* Creates the necessary event listener for this
* specific controller and opens a new Ext.window.Window
* to display the subapplication
*
* @return void
*/
init: function () {
var me = this;
me.control({
// Open add window
'mediamanager-album-tree button[action=mediamanager-album-tree-add]': {
click: me.onOpenAddWindow
},
//remove selected album
'mediamanager-album-tree button[action=mediamanager-album-tree-delete]': {
click: me.onDeleteAlbumButton
},
'mediamanager-album-tree textfield[action=mediamanager-album-tree-search]': {
change: me.onSearchAlbum
},
// Save new album
'mediamanager-album-add button[action=mediamanager-album-add-add]': {
click: me.onAddAlbum
},
'mediamanager-album-tree': {
addAlbum: me.onOpenAddWindow,
addSubAlbum: me.onAddSubAlbum,
deleteAlbum: me.onDeleteAlbum,
reload: me.onReloadAlbums,
editSettings: me.onOpenSettingsWindow,
itemmove: me.onMoveAlbum
},
'mediamanager-media-view html5fileupload': {
uploadReady: me.onReload
},
// Save album settings
'mediamanager-album-setting button[action=mediamanager-album-setting-save]': {
click: me.onSaveSettings
},
'mediamanager-album-setting': {
generateThumbnails: me.onGenerateThumbnails
}
});
me.callParent(arguments);
},
/**
* Event listener method which fired when the user uploads files
* and the upload completed. Refreshs the tree and select the last
* selected node.
*/
onReload: function () {
var me = this,
tree = this.getAlbumTree(),
store = this.getStore('Album'),
selModel = tree.getSelectionModel(),
selected = tree.selModel.selected.items[0];
var rootNode = tree.getRootNode();
rootNode.removeAll(false);
tree.setLoading(true);
store.load({
callback: function () {
if (selected) {
var lastSelected = store.getNodeById(selected.data.id);
me.expandParent(lastSelected);
selModel.select(lastSelected);
}
tree.setLoading(false);
}
});
},
expandParent: function (node) {
var me = this;
if (!node) {
return;
}
node.expand();
if (!node.parentNode) {
return;
}
me.expandParent(node.parentNode);
},
/**
* Event listener method which fires when the user
* clicks on the "remove album"-button below the tree.
*
* @return void
*/
onDeleteAlbumButton: function () {
var me = this,
tree = me.getAlbumTree(),
store = tree.store,
selected = tree.selModel.selected.items[0];
if (!selected) {
return;
}
//delete only leaf albums
if (selected.data.leaf) {
selected.set('albumID', selected.get('id'));
tree.setLoading(true);
selected.destroy({
callback: function () {
var rootNode = tree.getRootNode();
rootNode.removeAll(false);
store.load();
tree.setLoading(false);
}
})
}
},
/**
* Filters the tree with the passed search value, which inserted in the
* search field on the left hand of the module.
*
* @param field
* @param value
*/
onSearchAlbum: function (field, value) {
var me = this,
tree = me.getAlbumTree(),
searchString = Ext.String.trim(value),
store = tree.store,
view = tree.viewConfig.plugins.cmp,
plugin = view.initialConfig.plugins.cmp.plugins[0];
//lock drag and drop if the tree is filtered.
if (searchString.length > 0) {
plugin.dropZone.lock();
plugin.dragZone.lock();
} else {
plugin.dropZone.unlock();
plugin.dragZone.unlock();
}
//search value changed?
if (store.getProxy().extraParams.filter === 'undefined' && searchString.length == 0) {
return;
}
if (store.getProxy().extraParams.filter === searchString) {
return;
}
tree.setLoading(true);
store.getProxy().extraParams = { albumFilter: searchString };
var rootNode = tree.getRootNode();
rootNode.removeAll(false);
//don't use store.clearFilter(), clearFilter() send an ajax request to reload the store.
store.load({
callback: function () {
tree.setLoading(false);
}
});
},
/**
* Event listener method which fires when the user
* clicks the "add album"-button in the toolbar of the
* album tree.
*
* Opens the "add album"-window.
*
* @event click
* @return void
*/
onOpenAddWindow: function () {
var me = this,
tree = me.getAlbumTree(),
selModel = tree.getSelectionModel(),
selection = selModel.getSelection(),
parentId;
if (selection && selection.length === 1) {
selection = selection[0];
parentId = selection.get('id');
me.getView('album.Add').create({ parentId: parentId });
} else {
me.getView('album.Add').create();
}
},
/**
* Event listener method which fires when the user
* clicks in the item context menu on the "edit settings" button.
*
* Opens the "album settings"-window
*
* @event editSettings
* @param [object] scope - Scope of the fired event
* @param [object] view - the Ext.tree.Panel
* @param [object] record - clicked Ext.data.Model
* @return void
*/
onOpenSettingsWindow: function (scope, view, record) {
this.getView('album.Setting').create({ settings: record });
},
/**
* Event listener method which fires when the user
* clicks the "save"-button in the "add"-window.
*
* The method adds a new album to the store
*
* @event click
* @param [object] btn - pressed Ext.button.Button
*/
onAddAlbum: function (btn) {
var win = btn.up('window'),
form = win.down('form'),
values = form.getForm().getValues(),
me = this,
model = me.getModel('Album').create(values),
store = me.getAlbumTree().store,
tree = me.getAlbumTree();
tree.setLoading(true);
model.save({
callback: function () {
var rootNode = tree.getRootNode();
rootNode.removeAll(false);
if (win.closeAction == 'destroy') {
win.destroy();
} else {
win.close()
}
store.load();
tree.setLoading(false);
}
})
},
/**
* Event listener method which fires when the user
* clicks the "add subalbum"-button in the item
* context menu.
*
* Opens the "add album"-window with the parent id
*
* @event addSubAlbum
* @param [object] scope - Scope of the fired event
* @param [object] view - Ext.tree.Panel which has fired the event
* @param [object] record - Associated Ext.data.Model
* @return void
*/
onAddSubAlbum: function (scope, view, record) {
var parentId = record.get('id');
this.getView('album.Add').create({ parentId: parentId });
},
/**
* Event listener method which fires when the user
* clicks the "delete album"-button in the item
* context menu.
*
* Deletes the associated album.
*
* @event deleteAlbum
* @param scope
* @param view
* @param record
*/
onDeleteAlbum: function (scope, view, record) {
var me = this,
tree = me.getAlbumTree(),
store = tree.store;
record.set('albumID', record.get('id'));
tree.setLoading(true);
record.destroy({
callback: function () {
var rootNode = tree.getRootNode();
rootNode.removeAll(false);
store.load();
tree.setLoading(false);
}
})
},
/**
* Event listener method which fires when the user
* clicks on the "reload albums"-button in the container
* context menu.
*
* Reloads the associated Ext.data.Tree.Store
*
* @event reload
* @return void
*/
onReloadAlbums: function () {
var me = this,
tree = me.getAlbumTree(),
store = tree.store;
var rootNode = tree.getRootNode();
rootNode.removeAll(false);
tree.setLoading(true);
store.load({
callback: function () {
tree.setLoading(false);
}
});
},
/**
* Event listener method which fires when the user
* moves an album to a different place.
*
* Moves an album to a different position.
*
* @event itemmove
* @param [object] node - actual Ext.data.Model
* @param [object] oldParent - old Ext.data.Model
* @param [object] newParent - updated Ext.data.Model
* @return void
*/
onMoveAlbum: function (node, oldParent, newParent) {
node.data.position = node.data.index + 1;
if (newParent.data.id !== 'root') {
node.data.parentId = newParent.data.id;
} else {
node.data.parentId = 0;
}
node.save();
},
/**
* Event listener method which will be fired when the user
* clicks the "save settings"-button.
*
* Changes the album settings
*
* @event click
* @param [object] btn - pressed Ext.button.Button
* @return void
*/
onSaveSettings: function (btn) {
var me = this,
win = btn.up('window'),
model = win.settings,
thumbItems = win.thumbnailStore.data.items,
thumbChanged = me.handleAlbumModelData(model, win);
me.setAlbumSizes(model, thumbItems);
model.save({
callback: function () {
if (thumbChanged) {
Ext.Msg.confirm('{s name=settings/newSizesTitle}Generate new thumbnails?{/s}', '{s name=settings/generateNewSizes}New thumbnail sizes have been defined. Would you like to generate them now?{/s}', function (btn) {
if (btn !== 'yes') {
return false;
}
win.fireEvent('createThumbnailWindow', model);
});
}
win.close();
me.getAlbumTree().fireEvent('reload');
}
});
},
/**
* Reads out the settings window form and sets its
* values to the album model.
*
* Returns boolean status whether thumbnail sizes
* were changed or not.
*
* @param model
* @param win
* @param setSizes
* @returns boolean
*/
handleAlbumModelData: function (model, win) {
var me = this,
form = win.down('form'),
values = form.getValues(),
thumbItems = win.thumbnailStore.data.items,
thumbChanged = me.checkThumbnailsChanged(thumbItems, model.get('thumbnailSize'));
model.set(values);
return thumbChanged;
},
setAlbumSizes: function(model, thumbItems){
var sizes = [];
Ext.each(thumbItems, function (item) {
sizes.push(item.data);
});
model.set('thumbnailSize', sizes);
},
/**
* This method first saves the album and generates the
* thumbnails afterwards with the defined sizes.
*
* @param window
*/
onGenerateThumbnails: function (window) {
var me = this,
model = window.settings,
thumbItems = window.thumbnailStore.data.items,
thumbChanged = me.handleAlbumModelData(model, window);
if (thumbChanged) {
Ext.Msg.confirm('{s name=settings/saveNowTitle}Save album?{/s}', '{s name=settings/saveBeforeGeneration}The album must first be saved. Save album now?{/s}', function (btn) {
if (btn !== 'yes') {
return false;
}
me.setAlbumSizes(model, thumbItems);
// save the album and generate the thumbnails on the callback
model.save({
callback: function () {
window.fireEvent('createThumbnailWindow', model);
}
});
});
} else {
window.fireEvent('createThumbnailWindow', model);
}
},
/**
* Determines if the thumbnails sizes have changed
*
* @param thumbnailItems
* @param oldSizes
* @returns bool
*/
checkThumbnailsChanged: function (thumbnailItems, oldSizes) {
var thumbnails = [];
// check if new thumbnails were created or changed
Ext.each(thumbnailItems, function (item) {
thumbnails.push(item.data);
});
return JSON.stringify(oldSizes) != JSON.stringify(thumbnails);
}
});
//{/block}
|
jenalgit/shopware
|
themes/Backend/ExtJs/backend/media_manager/controller/album.js
|
JavaScript
|
agpl-3.0
| 15,865
|
(function() {
'use strict';
angular
.module('shipyard.engines')
.controller('EngineDetailsController', EngineDetailsController);
EngineDetailsController.$inject = ['$scope', '$location', '$routeParams', 'flash', 'Containers', 'Engine'];
function EngineDetailsController($scope, $location, $routeParams, flash, Containers, Engine) {
$scope.showX = function(){
return function(d){
return d.key;
};
};
$scope.showY = function(){
return function(d){
return d.y;
};
};
$scope.showRemoveEngineDialog = function() {
$('.basic.modal')
.modal('show');
};
$scope.removeEngine = function() {
Engine.remove({id: $routeParams.id}).$promise.then(function() {
// we must remove the modal or it will come back
// the next time the modal is shown
$('.basic.modal').remove();
$location.path("/engines");
}, function(err) {
flash.error = 'error removing engine: ' + err.data;
});
};
Engine.query({id: $routeParams.id}, function(data){
$scope.engine = data;
// load container data
Containers.query(function(d){
var cpuData = [];
var memoryData = [];
$scope.chartOptions = {};
for (var i=0; i<d.length; i++) {
var c = d[i];
var color = getRandomColor();
if (c.engine.id == data.engine.id){
var x = {
label: c.image.hostname,
value: c.image.cpus || 0.0,
color: color
}
var y = {
label: c.image.hostname,
value: c.image.memory || 0.0,
color: color
}
cpuData.push(x);
memoryData.push(y);
}
}
$scope.engineCpuData = cpuData;
$scope.engineMemoryData = memoryData;
});
});
}
})()
|
Dumbear/shipyard
|
controller/static/app/engines/details.controller.js
|
JavaScript
|
apache-2.0
| 2,349
|
/******/ (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__) {
var __weex_template__ = __webpack_require__(1)
var __weex_style__ = __webpack_require__(2)
var __weex_script__ = __webpack_require__(3)
__weex_define__('@weex-component/08f3d99ae6a6056191aa37369285037a', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
__weex_bootstrap__('@weex-component/08f3d99ae6a6056191aa37369285037a',undefined,undefined)
/***/ },
/* 1 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"children": [
{
"type": "wxc-panel",
"attr": {
"title": "Transform",
"type": "primary"
},
"children": [
{
"type": "wxc-button",
"attr": {
"value": "Rotate",
"type": "primary",
"size": "middle"
},
"events": {
"click": "rotate"
}
},
{
"type": "wxc-button",
"attr": {
"value": "Scale",
"type": "primary",
"size": "middle"
},
"events": {
"click": "scale"
},
"style": {
"marginTop": 12
}
},
{
"type": "wxc-button",
"attr": {
"value": "Translate",
"type": "primary",
"size": "middle"
},
"events": {
"click": "translate"
},
"style": {
"marginTop": 12
}
},
{
"type": "wxc-button",
"attr": {
"value": "Transform",
"type": "success",
"size": "middle"
},
"events": {
"click": "transform"
},
"style": {
"marginTop": 12
}
}
]
},
{
"type": "wxc-panel",
"attr": {
"title": "Others",
"type": "primary"
},
"children": [
{
"type": "wxc-button",
"attr": {
"value": "BgColor",
"type": "primary",
"size": "middle"
},
"events": {
"click": "color"
}
},
{
"type": "wxc-button",
"attr": {
"value": "Opacity",
"type": "primary",
"size": "middle"
},
"events": {
"click": "opacity"
},
"style": {
"marginTop": 12
}
},
{
"type": "wxc-button",
"attr": {
"value": "All",
"type": "success",
"size": "middle"
},
"events": {
"click": "composite"
},
"style": {
"marginTop": 12
}
}
]
},
{
"type": "div",
"id": "block",
"classList": [
"block"
],
"style": {
"transformOrigin": function () {return this.transformOrigin}
},
"children": [
{
"type": "text",
"classList": [
"block-txt"
],
"attr": {
"value": "Anim"
}
}
]
}
]
}
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = {
"block": {
"position": "absolute",
"width": 250,
"height": 250,
"top": 300,
"left": 400,
"backgroundColor": "#F0AD4E",
"alignItems": "center",
"justifyContent": "center"
},
"block-txt": {
"color": "#FFFFFF",
"fontSize": 70
}
}
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
module.exports = function(module, exports, __weex_require__){'use strict';
__webpack_require__(4);
module.exports = {
data: function () {return {
transformOrigin: 'center center',
current_rotate: 0,
current_scale: 1,
current_color: '#FF0000',
current_opacity: 1,
current_translate: '',
current_transform: '',
isStop: true
}},
methods: {
anim: function anim(styles, timingFunction, duration, callback) {
this.$call('animation', 'transition', this._ids.block.el.ref, {
styles: styles,
timingFunction: timingFunction,
duration: duration
}, callback);
},
rotate: function rotate() {
var self = this;
self.current_rotate += 90;
self.anim({
transform: 'rotate(' + self.current_rotate + 'deg)'
}, 'ease-in-out', 500, function () {
if (self.current_rotate === 360) {
self.current_rotate = 0;
} else {
self.rotate();
}
});
},
translate: function translate() {
this.current_translate = this.current_translate ? '' : 'translate(50%, 50%)';
this.anim({
transform: this.current_translate
}, 'ease-in', 500, function () {});
},
scale: function scale() {
var self = this;
self.current_scale = self.current_scale === 2 ? .5 : 2;
self.anim({
transform: 'scale(' + self.current_scale + ')'
}, 'linear', 500, function () {});
},
transform: function transform() {
var self = this;
this.current_transform = this.current_transform ? '' : 'rotate(45deg) scale(1.5)';
this.anim({
transform: this.current_transform,
transformOrigin: 'left top'
}, 'ease-out', 500, function () {
if (self.current_transform !== '') {
self.anim({
transform: 'rotate(-90deg) scale(1.2)',
transformOrigin: 'left top'
}, 'ease-out', 500, function () {});
} else {}
});
},
composite: function composite() {
var self = this;
self.current_transform = self.current_transform ? '' : 'rotate(45deg) scale(1.5) translate(50%, 50%)';
self.current_color = self.current_color === '#F0AD4E' ? '#D9534F' : '#F0AD4E';
self.current_opacity = self.current_opacity === 1 ? 0.1 : 1;
this.anim({
transform: this.current_transform,
transformOrigin: 'left top',
backgroundColor: self.current_color,
opacity: self.current_opacity
}, 'ease-out', 1000, function () {});
},
color: function color() {
var self = this;
self.current_color = self.current_color === '#F0AD4E' ? '#D9534F' : '#F0AD4E';
self.anim({
backgroundColor: self.current_color
}, 'linear', 500, function () {});
},
opacity: function opacity() {
var self = this;
self.current_opacity = self.current_opacity === 1 ? 0.1 : 1;
self.anim({
opacity: self.current_opacity
}, 'linear', 500, function () {});
}
}
};}
/* generated by weex-loader */
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(5);
__webpack_require__(9);
__webpack_require__(13);
__webpack_require__(17);
__webpack_require__(21);
__webpack_require__(25);
__webpack_require__(66);
__webpack_require__(70);
__webpack_require__(74);
__webpack_require__(78);
__webpack_require__(79);
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(6)
var __weex_style__ = __webpack_require__(7)
var __weex_script__ = __webpack_require__(8)
__weex_define__('@weex-component/wxc-button', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 6 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": function () {return ['btn', 'btn-' + (this.type), 'btn-sz-' + (this.size)]},
"children": [
{
"type": "text",
"classList": function () {return ['btn-txt', 'btn-txt-' + (this.type), 'btn-txt-sz-' + (this.size)]},
"attr": {
"value": function () {return this.value}
}
}
]
}
/***/ },
/* 7 */
/***/ function(module, exports) {
module.exports = {
"btn": {
"marginBottom": 0,
"alignItems": "center",
"justifyContent": "center",
"borderWidth": 1,
"borderStyle": "solid",
"borderColor": "#333333"
},
"btn-default": {
"color": "rgb(51,51,51)"
},
"btn-primary": {
"backgroundColor": "rgb(40,96,144)",
"borderColor": "rgb(40,96,144)"
},
"btn-success": {
"backgroundColor": "rgb(92,184,92)",
"borderColor": "rgb(76,174,76)"
},
"btn-info": {
"backgroundColor": "rgb(91,192,222)",
"borderColor": "rgb(70,184,218)"
},
"btn-warning": {
"backgroundColor": "rgb(240,173,78)",
"borderColor": "rgb(238,162,54)"
},
"btn-danger": {
"backgroundColor": "rgb(217,83,79)",
"borderColor": "rgb(212,63,58)"
},
"btn-link": {
"borderColor": "rgba(0,0,0,0)",
"borderRadius": 0
},
"btn-txt-default": {
"color": "rgb(51,51,51)"
},
"btn-txt-primary": {
"color": "rgb(255,255,255)"
},
"btn-txt-success": {
"color": "rgb(255,255,255)"
},
"btn-txt-info": {
"color": "rgb(255,255,255)"
},
"btn-txt-warning": {
"color": "rgb(255,255,255)"
},
"btn-txt-danger": {
"color": "rgb(255,255,255)"
},
"btn-txt-link": {
"color": "rgb(51,122,183)"
},
"btn-sz-large": {
"width": 300,
"height": 100,
"paddingTop": 25,
"paddingBottom": 25,
"paddingLeft": 40,
"paddingRight": 40,
"borderRadius": 15
},
"btn-sz-middle": {
"width": 240,
"height": 80,
"paddingTop": 15,
"paddingBottom": 15,
"paddingLeft": 30,
"paddingRight": 30,
"borderRadius": 10
},
"btn-sz-small": {
"width": 170,
"height": 60,
"paddingTop": 12,
"paddingBottom": 12,
"paddingLeft": 25,
"paddingRight": 25,
"borderRadius": 7
},
"btn-txt-sz-large": {
"fontSize": 45
},
"btn-txt-sz-middle": {
"fontSize": 35
},
"btn-txt-sz-small": {
"fontSize": 30
}
}
/***/ },
/* 8 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
type: 'default',
size: 'large',
value: ''
}},
methods: {}
};}
/* generated by weex-loader */
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(10)
var __weex_style__ = __webpack_require__(11)
var __weex_script__ = __webpack_require__(12)
__weex_define__('@weex-component/wxc-hn', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 10 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": function () {return ['h' + (this.level)]},
"style": {
"justifyContent": "center"
},
"children": [
{
"type": "text",
"classList": function () {return ['txt-h' + (this.level)]},
"attr": {
"value": function () {return this.value}
}
}
]
}
/***/ },
/* 11 */
/***/ function(module, exports) {
module.exports = {
"h1": {
"height": 110,
"paddingTop": 20,
"paddingBottom": 20
},
"h2": {
"height": 110,
"paddingTop": 20,
"paddingBottom": 20
},
"h3": {
"height": 110,
"paddingTop": 20,
"paddingBottom": 20
},
"txt-h1": {
"fontSize": 70
},
"txt-h2": {
"fontSize": 52
},
"txt-h3": {
"fontSize": 42
}
}
/***/ },
/* 12 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
level: 1,
value: ''
}},
methods: {}
};}
/* generated by weex-loader */
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(14)
var __weex_style__ = __webpack_require__(15)
var __weex_script__ = __webpack_require__(16)
__weex_define__('@weex-component/wxc-list-item', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 14 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": [
"item"
],
"events": {
"touchstart": "touchstart",
"touchend": "touchend"
},
"style": {
"backgroundColor": function () {return this.bgColor}
},
"children": [
{
"type": "content"
}
]
}
/***/ },
/* 15 */
/***/ function(module, exports) {
module.exports = {
"item": {
"paddingTop": 25,
"paddingBottom": 25,
"paddingLeft": 35,
"paddingRight": 35,
"height": 160,
"justifyContent": "center",
"borderBottomWidth": 1,
"borderColor": "#dddddd"
}
}
/***/ },
/* 16 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
bgColor: '#ffffff'
}},
methods: {
touchstart: function touchstart() {},
touchend: function touchend() {}
}
};}
/* generated by weex-loader */
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(18)
var __weex_style__ = __webpack_require__(19)
var __weex_script__ = __webpack_require__(20)
__weex_define__('@weex-component/wxc-panel', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 18 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": function () {return ['panel', 'panel-' + (this.type)]},
"style": {
"borderWidth": function () {return this.border}
},
"children": [
{
"type": "text",
"classList": function () {return ['panel-header', 'panel-header-' + (this.type)]},
"style": {
"paddingTop": function () {return this.paddingHead},
"paddingBottom": function () {return this.paddingHead},
"paddingLeft": function () {return this.paddingHead*1.5},
"paddingRight": function () {return this.paddingHead*1.5}
},
"attr": {
"value": function () {return this.title}
}
},
{
"type": "div",
"classList": function () {return ['panel-body', 'panel-body-' + (this.type)]},
"style": {
"paddingTop": function () {return this.paddingBody},
"paddingBottom": function () {return this.paddingBody},
"paddingLeft": function () {return this.paddingBody*1.5},
"paddingRight": function () {return this.paddingBody*1.5}
},
"children": [
{
"type": "content"
}
]
}
]
}
/***/ },
/* 19 */
/***/ function(module, exports) {
module.exports = {
"panel": {
"marginBottom": 20,
"backgroundColor": "#ffffff",
"borderColor": "#dddddd",
"borderWidth": 1
},
"panel-primary": {
"borderColor": "rgb(40,96,144)"
},
"panel-success": {
"borderColor": "rgb(76,174,76)"
},
"panel-info": {
"borderColor": "rgb(70,184,218)"
},
"panel-warning": {
"borderColor": "rgb(238,162,54)"
},
"panel-danger": {
"borderColor": "rgb(212,63,58)"
},
"panel-header": {
"backgroundColor": "#f5f5f5",
"fontSize": 40,
"color": "#333333"
},
"panel-header-primary": {
"backgroundColor": "rgb(40,96,144)",
"color": "#ffffff"
},
"panel-header-success": {
"backgroundColor": "rgb(92,184,92)",
"color": "#ffffff"
},
"panel-header-info": {
"backgroundColor": "rgb(91,192,222)",
"color": "#ffffff"
},
"panel-header-warning": {
"backgroundColor": "rgb(240,173,78)",
"color": "#ffffff"
},
"panel-header-danger": {
"backgroundColor": "rgb(217,83,79)",
"color": "#ffffff"
}
}
/***/ },
/* 20 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
type: 'default',
title: '',
paddingBody: 20,
paddingHead: 20,
dataClass: '',
border: 0
}},
ready: function ready() {}
};}
/* generated by weex-loader */
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(22)
var __weex_style__ = __webpack_require__(23)
var __weex_script__ = __webpack_require__(24)
__weex_define__('@weex-component/wxc-tip', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 22 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": function () {return ['tip', 'tip-' + (this.type)]},
"children": [
{
"type": "text",
"classList": function () {return ['tip-txt', 'tip-txt-' + (this.type)]},
"attr": {
"value": function () {return this.value}
}
}
]
}
/***/ },
/* 23 */
/***/ function(module, exports) {
module.exports = {
"tip": {
"paddingLeft": 36,
"paddingRight": 36,
"paddingTop": 36,
"paddingBottom": 36,
"borderRadius": 10
},
"tip-txt": {
"fontSize": 28
},
"tip-success": {
"backgroundColor": "#dff0d8",
"borderColor": "#d6e9c6"
},
"tip-txt-success": {
"color": "#3c763d"
},
"tip-info": {
"backgroundColor": "#d9edf7",
"borderColor": "#bce8f1"
},
"tip-txt-info": {
"color": "#31708f"
},
"tip-warning": {
"backgroundColor": "#fcf8e3",
"borderColor": "#faebcc"
},
"tip-txt-warning": {
"color": "#8a6d3b"
},
"tip-danger": {
"backgroundColor": "#f2dede",
"borderColor": "#ebccd1"
},
"tip-txt-danger": {
"color": "#a94442"
}
}
/***/ },
/* 24 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
type: 'success',
value: ''
}}
};}
/* generated by weex-loader */
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(26)
var __weex_style__ = __webpack_require__(27)
var __weex_script__ = __webpack_require__(28)
__weex_define__('@weex-component/wxc-countdown', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 26 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"style": {
"overflow": "hidden",
"flexDirection": "row"
},
"events": {
"appear": "appeared",
"disappear": "disappeared"
},
"children": [
{
"type": "content"
}
]
}
/***/ },
/* 27 */
/***/ function(module, exports) {
module.exports = {
"wrap": {
"overflow": "hidden"
}
}
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
module.exports = function(module, exports, __weex_require__){'use strict';
var _assign = __webpack_require__(29);
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = {
data: function () {return {
now: 0,
remain: 0,
time: {
elapse: 0,
D: '0',
DD: '0',
h: '0',
hh: '00',
H: '0',
HH: '0',
m: '0',
mm: '00',
M: '0',
MM: '0',
s: '0',
ss: '00',
S: '0',
SS: '0'
},
outofview: false
}},
ready: function ready() {
if (this.remain <= 0) {
return;
}
this.now = Date.now();
this.nextTick();
},
methods: {
nextTick: function nextTick() {
if (this.outofview) {
setTimeout(this.nextTick.bind(this), 1000);
} else {
this.time.elapse = parseInt((Date.now() - this.now) / 1000);
if (this.calc()) {
this.$emit('tick', (0, _assign2.default)({}, this.time));
setTimeout(this.nextTick.bind(this), 1000);
} else {
this.$emit('alarm', (0, _assign2.default)({}, this.time));
}
this._app.updateActions();
}
},
format: function format(str) {
if (str.length >= 2) {
return str;
} else {
return '0' + str;
}
},
calc: function calc() {
var remain = this.remain - this.time.elapse;
if (remain < 0) {
remain = 0;
}
this.time.D = String(parseInt(remain / 86400));
this.time.DD = this.format(this.time.D);
this.time.h = String(parseInt((remain - parseInt(this.time.D) * 86400) / 3600));
this.time.hh = this.format(this.time.h);
this.time.H = String(parseInt(remain / 3600));
this.time.HH = this.format(this.time.H);
this.time.m = String(parseInt((remain - parseInt(this.time.H) * 3600) / 60));
this.time.mm = this.format(this.time.m);
this.time.M = String(parseInt(remain / 60));
this.time.MM = this.format(this.time.M);
this.time.s = String(remain - parseInt(this.time.M) * 60);
this.time.ss = this.format(this.time.s);
this.time.S = String(remain);
this.time.SS = this.format(this.time.S);
return remain > 0;
},
appeared: function appeared() {
this.outofview = false;
},
disappeared: function disappeared() {
this.outofview = true;
}
}
};}
/* generated by weex-loader */
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(30), __esModule: true };
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(31);
module.exports = __webpack_require__(34).Object.assign;
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__(32);
$export($export.S + $export.F, 'Object', {assign: __webpack_require__(47)});
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(33)
, core = __webpack_require__(34)
, ctx = __webpack_require__(35)
, hide = __webpack_require__(37)
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, IS_WRAP = type & $export.W
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE]
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
, key, own, out;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
if(own && key in exports)continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
// bind timers to global for call from export context
: IS_BIND && own ? ctx(out, global)
// wrap global constructors for prevent change them in library
: IS_WRAP && target[key] == out ? (function(C){
var F = function(a, b, c){
if(this instanceof C){
switch(arguments.length){
case 0: return new C;
case 1: return new C(a);
case 2: return new C(a, b);
} return new C(a, b, c);
} return C.apply(this, arguments);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
// make static versions for prototype methods
})(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
if(IS_PROTO){
(exports.virtual || (exports.virtual = {}))[key] = out;
// export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out);
}
}
};
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ },
/* 33 */
/***/ function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
/***/ },
/* 34 */
/***/ function(module, exports) {
var core = module.exports = {version: '2.4.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(36);
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
/***/ },
/* 36 */
/***/ function(module, exports) {
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
var dP = __webpack_require__(38)
, createDesc = __webpack_require__(46);
module.exports = __webpack_require__(42) ? function(object, key, value){
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(39)
, IE8_DOM_DEFINE = __webpack_require__(41)
, toPrimitive = __webpack_require__(45)
, dP = Object.defineProperty;
exports.f = __webpack_require__(42) ? Object.defineProperty : function defineProperty(O, P, Attributes){
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if(IE8_DOM_DEFINE)try {
return dP(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)O[P] = Attributes.value;
return O;
};
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(40);
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
/***/ },
/* 40 */
/***/ function(module, exports) {
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__(42) && !__webpack_require__(43)(function(){
return Object.defineProperty(__webpack_require__(44)('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(43)(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ },
/* 43 */
/***/ function(module, exports) {
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(40)
, document = __webpack_require__(33).document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(40);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ },
/* 46 */
/***/ function(module, exports) {
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = __webpack_require__(48)
, gOPS = __webpack_require__(63)
, pIE = __webpack_require__(64)
, toObject = __webpack_require__(65)
, IObject = __webpack_require__(52)
, $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __webpack_require__(43)(function(){
var A = {}
, B = {}
, S = Symbol()
, K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function(k){ B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
var T = toObject(target)
, aLen = arguments.length
, index = 1
, getSymbols = gOPS.f
, isEnum = pIE.f;
while(aLen > index){
var S = IObject(arguments[index++])
, keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key];
} return T;
} : $assign;
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(49)
, enumBugKeys = __webpack_require__(62);
module.exports = Object.keys || function keys(O){
return $keys(O, enumBugKeys);
};
/***/ },
/* 49 */
/***/ function(module, exports, __webpack_require__) {
var has = __webpack_require__(50)
, toIObject = __webpack_require__(51)
, arrayIndexOf = __webpack_require__(55)(false)
, IE_PROTO = __webpack_require__(59)('IE_PROTO');
module.exports = function(object, names){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(names.length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
/***/ },
/* 50 */
/***/ function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
/***/ },
/* 51 */
/***/ function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(52)
, defined = __webpack_require__(54);
module.exports = function(it){
return IObject(defined(it));
};
/***/ },
/* 52 */
/***/ function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(53);
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ },
/* 53 */
/***/ function(module, exports) {
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
/***/ },
/* 54 */
/***/ function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__(51)
, toLength = __webpack_require__(56)
, toIndex = __webpack_require__(58);
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__(57)
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ },
/* 57 */
/***/ function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(57)
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ },
/* 59 */
/***/ function(module, exports, __webpack_require__) {
var shared = __webpack_require__(60)('keys')
, uid = __webpack_require__(61);
module.exports = function(key){
return shared[key] || (shared[key] = uid(key));
};
/***/ },
/* 60 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(33)
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
/***/ },
/* 61 */
/***/ function(module, exports) {
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ },
/* 62 */
/***/ function(module, exports) {
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
/***/ },
/* 63 */
/***/ function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
/***/ },
/* 64 */
/***/ function(module, exports) {
exports.f = {}.propertyIsEnumerable;
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(54);
module.exports = function(it){
return Object(defined(it));
};
/***/ },
/* 66 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(67)
var __weex_style__ = __webpack_require__(68)
var __weex_script__ = __webpack_require__(69)
__weex_define__('@weex-component/wxc-marquee', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 67 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": [
"wrap"
],
"events": {
"appear": "appeared",
"disappear": "disappeared"
},
"children": [
{
"type": "div",
"id": "anim",
"classList": [
"anim"
],
"children": [
{
"type": "content"
}
]
}
]
}
/***/ },
/* 68 */
/***/ function(module, exports) {
module.exports = {
"wrap": {
"overflow": "hidden",
"position": "relative"
},
"anim": {
"flexDirection": "column",
"position": "absolute",
"transform": "translateY(0) translateZ(0)"
}
}
/***/ },
/* 69 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
step: 0,
count: 0,
index: 1,
duration: 0,
interval: 0,
outofview: false
}},
ready: function ready() {
if (this.interval > 0 && this.step > 0 && this.duration > 0) {
this.nextTick();
}
},
methods: {
nextTick: function nextTick() {
var self = this;
if (this.outofview) {
setTimeout(self.nextTick.bind(self), self.interval);
} else {
setTimeout(function () {
self.animation(self.nextTick.bind(self));
}, self.interval);
}
},
animation: function animation(cb) {
var self = this;
var offset = -self.step * self.index;
var $animation = __weex_require__('@weex-module/animation');
$animation.transition(this.$el('anim'), {
styles: {
transform: 'translateY(' + String(offset) + 'px) translateZ(0)'
},
timingFunction: 'ease',
duration: self.duration
}, function () {
self.index = (self.index + 1) % self.count;
self.$emit('change', {
index: self.index,
count: self.count
});
cb && cb();
});
},
appeared: function appeared() {
this.outofview = false;
},
disappeared: function disappeared() {
this.outofview = true;
}
}
};}
/* generated by weex-loader */
/***/ },
/* 70 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(71)
var __weex_style__ = __webpack_require__(72)
var __weex_script__ = __webpack_require__(73)
__weex_define__('@weex-component/wxc-navbar', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 71 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": [
"container"
],
"style": {
"height": function () {return this.height},
"backgroundColor": function () {return this.backgroundColor}
},
"attr": {
"dataRole": function () {return this.dataRole}
},
"children": [
{
"type": "text",
"classList": [
"right-text"
],
"style": {
"color": function () {return this.rightItemColor}
},
"attr": {
"naviItemPosition": "right",
"value": function () {return this.rightItemTitle}
},
"shown": function () {return !this.rightItemSrc},
"events": {
"click": "onclickrightitem"
}
},
{
"type": "image",
"classList": [
"right-image"
],
"attr": {
"naviItemPosition": "right",
"src": function () {return this.rightItemSrc}
},
"shown": function () {return this.rightItemSrc},
"events": {
"click": "onclickrightitem"
}
},
{
"type": "text",
"classList": [
"left-text"
],
"style": {
"color": function () {return this.leftItemColor}
},
"attr": {
"naviItemPosition": "left",
"value": function () {return this.leftItemTitle}
},
"shown": function () {return !this.leftItemSrc},
"events": {
"click": "onclickleftitem"
}
},
{
"type": "image",
"classList": [
"left-image"
],
"attr": {
"naviItemPosition": "left",
"src": function () {return this.leftItemSrc}
},
"shown": function () {return this.leftItemSrc},
"events": {
"click": "onclickleftitem"
}
},
{
"type": "text",
"classList": [
"center-text"
],
"style": {
"color": function () {return this.titleColor}
},
"attr": {
"naviItemPosition": "center",
"value": function () {return this.title}
}
}
]
}
/***/ },
/* 72 */
/***/ function(module, exports) {
module.exports = {
"container": {
"flexDirection": "row",
"position": "fixed",
"top": 0,
"left": 0,
"right": 0,
"width": 750
},
"right-text": {
"position": "absolute",
"bottom": 28,
"right": 32,
"textAlign": "right",
"fontSize": 32,
"fontFamily": "'Open Sans', sans-serif"
},
"left-text": {
"position": "absolute",
"bottom": 28,
"left": 32,
"textAlign": "left",
"fontSize": 32,
"fontFamily": "'Open Sans', sans-serif"
},
"center-text": {
"position": "absolute",
"bottom": 25,
"left": 172,
"right": 172,
"textAlign": "center",
"fontSize": 36,
"fontWeight": "bold"
},
"left-image": {
"position": "absolute",
"bottom": 20,
"left": 28,
"width": 50,
"height": 50
},
"right-image": {
"position": "absolute",
"bottom": 20,
"right": 28,
"width": 50,
"height": 50
}
}
/***/ },
/* 73 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
dataRole: 'navbar',
backgroundColor: 'black',
height: 88,
title: "",
titleColor: 'black',
rightItemSrc: '',
rightItemTitle: '',
rightItemColor: 'black',
leftItemSrc: '',
leftItemTitle: '',
leftItemColor: 'black'
}},
methods: {
onclickrightitem: function onclickrightitem(e) {
this.$dispatch('naviBar.rightItem.click', {});
},
onclickleftitem: function onclickleftitem(e) {
this.$dispatch('naviBar.leftItem.click', {});
}
}
};}
/* generated by weex-loader */
/***/ },
/* 74 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(70)
var __weex_template__ = __webpack_require__(75)
var __weex_style__ = __webpack_require__(76)
var __weex_script__ = __webpack_require__(77)
__weex_define__('@weex-component/wxc-navpage', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 75 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": [
"wrapper"
],
"children": [
{
"type": "wxc-navbar",
"attr": {
"dataRole": function () {return this.dataRole},
"height": function () {return this.height},
"backgroundColor": function () {return this.backgroundColor},
"title": function () {return this.title},
"titleColor": function () {return this.titleColor},
"leftItemSrc": function () {return this.leftItemSrc},
"leftItemTitle": function () {return this.leftItemTitle},
"leftItemColor": function () {return this.leftItemColor},
"rightItemSrc": function () {return this.rightItemSrc},
"rightItemTitle": function () {return this.rightItemTitle},
"rightItemColor": function () {return this.rightItemColor}
}
},
{
"type": "div",
"classList": [
"wrapper"
],
"style": {
"marginTop": function () {return this.height}
},
"children": [
{
"type": "content"
}
]
}
]
}
/***/ },
/* 76 */
/***/ function(module, exports) {
module.exports = {
"wrapper": {
"position": "absolute",
"top": 0,
"left": 0,
"right": 0,
"bottom": 0,
"width": 750
}
}
/***/ },
/* 77 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
dataRole: 'navbar',
backgroundColor: 'black',
height: 88,
title: "",
titleColor: 'black',
rightItemSrc: '',
rightItemTitle: '',
rightItemColor: 'black',
leftItemSrc: '',
leftItemTitle: '',
leftItemColor: 'black'
}}
};}
/* generated by weex-loader */
/***/ },
/* 78 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(79)
var __weex_template__ = __webpack_require__(83)
var __weex_style__ = __webpack_require__(84)
var __weex_script__ = __webpack_require__(85)
__weex_define__('@weex-component/wxc-tabbar', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 79 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(80)
var __weex_style__ = __webpack_require__(81)
var __weex_script__ = __webpack_require__(82)
__weex_define__('@weex-component/wxc-tabitem', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 80 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": [
"container"
],
"style": {
"backgroundColor": function () {return this.backgroundColor}
},
"events": {
"click": "onclickitem"
},
"children": [
{
"type": "image",
"classList": [
"top-line"
],
"attr": {
"src": "http://gtms03.alicdn.com/tps/i3/TB1mdsiMpXXXXXpXXXXNw4JIXXX-640-4.png"
}
},
{
"type": "image",
"classList": [
"tab-icon"
],
"attr": {
"src": function () {return this.icon}
}
},
{
"type": "text",
"classList": [
"tab-text"
],
"style": {
"color": function () {return this.titleColor}
},
"attr": {
"value": function () {return this.title}
}
}
]
}
/***/ },
/* 81 */
/***/ function(module, exports) {
module.exports = {
"container": {
"flex": 1,
"flexDirection": "column",
"alignItems": "center",
"justifyContent": "center",
"height": 88
},
"top-line": {
"position": "absolute",
"top": 0,
"left": 0,
"right": 0,
"height": 2
},
"tab-icon": {
"marginTop": 5,
"width": 40,
"height": 40
},
"tab-text": {
"marginTop": 5,
"textAlign": "center",
"fontSize": 20
}
}
/***/ },
/* 82 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
index: 0,
title: '',
titleColor: '#000000',
icon: '',
backgroundColor: '#ffffff'
}},
methods: {
onclickitem: function onclickitem(e) {
var vm = this;
var params = {
index: vm.index
};
vm.$dispatch('tabItem.onClick', params);
}
}
};}
/* generated by weex-loader */
/***/ },
/* 83 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": [
"wrapper"
],
"children": [
{
"type": "embed",
"classList": [
"content"
],
"style": {
"visibility": function () {return this.visibility}
},
"repeat": function () {return this.tabItems},
"attr": {
"src": function () {return this.src},
"type": "weex"
}
},
{
"type": "div",
"classList": [
"tabbar"
],
"append": "tree",
"children": [
{
"type": "wxc-tabitem",
"repeat": function () {return this.tabItems},
"attr": {
"index": function () {return this.index},
"icon": function () {return this.icon},
"title": function () {return this.title},
"titleColor": function () {return this.titleColor}
}
}
]
}
]
}
/***/ },
/* 84 */
/***/ function(module, exports) {
module.exports = {
"wrapper": {
"width": 750,
"position": "absolute",
"top": 0,
"left": 0,
"right": 0,
"bottom": 0
},
"content": {
"position": "absolute",
"top": 0,
"left": 0,
"right": 0,
"bottom": 0,
"marginTop": 0,
"marginBottom": 88
},
"tabbar": {
"flexDirection": "row",
"position": "fixed",
"bottom": 0,
"left": 0,
"right": 0,
"height": 88
}
}
/***/ },
/* 85 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
tabItems: [],
selectedIndex: 0,
selectedColor: '#ff0000',
unselectedColor: '#000000'
}},
created: function created() {
this.selected(this.selectedIndex);
this.$on('tabItem.onClick', function (e) {
var detail = e.detail;
this.selectedIndex = detail.index;
this.selected(detail.index);
var params = {
index: detail.index
};
this.$dispatch('tabBar.onClick', params);
});
},
methods: {
selected: function selected(index) {
for (var i = 0; i < this.tabItems.length; i++) {
var tabItem = this.tabItems[i];
if (i == index) {
tabItem.icon = tabItem.selectedImage;
tabItem.titleColor = this.selectedColor;
tabItem.visibility = 'visible';
} else {
tabItem.icon = tabItem.image;
tabItem.titleColor = this.unselectedColor;
tabItem.visibility = 'hidden';
}
}
}
}
};}
/* generated by weex-loader */
/***/ }
/******/ ]);
|
GHHX/AliWeexPluginWheelCalendar
|
playground/ios/bundlejs/animation.js
|
JavaScript
|
mit
| 56,309
|
/**
* Avatar cropping
*/
elgg.provide('elgg.avatarCropper');
/**
* Register the avatar cropper.
*
* If the hidden inputs have the coordinates from a previous cropping, begin
* the selection and preview with that displayed.
*/
elgg.avatarCropper.init = function() {
var params = {
selectionOpacity: 0,
aspectRatio: '1:1',
onSelectEnd: elgg.avatarCropper.selectChange,
onSelectChange: elgg.avatarCropper.preview
};
if ($('input[name=x2]').val()) {
params.x1 = $('input[name=x1]').val();
params.x2 = $('input[name=x2]').val();
params.y1 = $('input[name=y1]').val();
params.y2 = $('input[name=y2]').val();
}
$('#user-avatar-cropper').imgAreaSelect(params);
if ($('input[name=x2]').val()) {
// TODO figure out why this is necessary
$(window).on('load', function () {
var ias = $('#user-avatar-cropper').imgAreaSelect({instance: true});
var selection = ias.getSelection();
elgg.avatarCropper.preview($('#user-avatar-cropper'), selection);
});
}
};
/**
* Handler for changing select area.
*
* @param {Object} img reference to the image
* @param {Object} selection imgareaselect selection object
* @return void
*/
elgg.avatarCropper.preview = function(img, selection) {
// catch for the first click on the image
if (selection.width === 0 || selection.height === 0) {
return;
}
var origWidth = $("#user-avatar-cropper").width();
var origHeight = $("#user-avatar-cropper").height();
var scaleX = 100 / selection.width;
var scaleY = 100 / selection.height;
$('#user-avatar-preview > img').css({
width: Math.round(scaleX * origWidth) + 'px',
height: Math.round(scaleY * origHeight) + 'px',
marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
});
};
/**
* Handler for updating the form inputs after select ends
*
* @param {Object} img reference to the image
* @param {Object} selection imgareaselect selection object
* @return void
*/
elgg.avatarCropper.selectChange = function(img, selection) {
$('input[name=x1]').val(selection.x1);
$('input[name=x2]').val(selection.x2);
$('input[name=y1]').val(selection.y1);
$('input[name=y2]').val(selection.y2);
};
elgg.register_hook_handler('init', 'system', elgg.avatarCropper.init);
|
ibou77/elgg
|
js/lib/ui.avatar_cropper.js
|
JavaScript
|
gpl-2.0
| 2,280
|
'use strict';
var _ = require('lodash');
var moment = require('moment');
var times = require('../times');
function init(ctx) {
var translate = ctx.language.translate;
var levels = ctx.levels;
var sage = {
name: 'sage'
, label: 'Sensor Age'
, pluginType: 'pill-minor'
};
sage.getPrefs = function getPrefs(sbx) {
return {
info: sbx.extendedSettings.info || times.days(6).hours
, warn: sbx.extendedSettings.warn || (times.days(7).hours - 4)
, urgent: sbx.extendedSettings.urgent || (times.days(7).hours - 2)
, enableAlerts: sbx.extendedSettings.enableAlerts || false
};
};
sage.setProperties = function setProperties (sbx) {
sbx.offerProperty('sage', function setProp ( ) {
return sage.findLatestTimeChange(sbx);
});
};
sage.checkNotifications = function checkNotifications(sbx) {
var info = sbx.properties.sage;
var sensorInfo = info[info.min];
if (sensorInfo.notification) {
var notification = _.extend({}, sensorInfo.notification, {
plugin: sage
, debug: {
age: sensorInfo.age
}
});
sbx.notifications.requestNotify(notification);
}
};
function minButValid(record) {
var events = [ ];
var start = record['Sensor Start'];
if (start && start.found) {
events.push({eventType: 'Sensor Start', treatmentDate: start.treatmentDate});
}
var change = record['Sensor Change'];
if (change && change.found) {
events.push({eventType: 'Sensor Change', treatmentDate: change.treatmentDate});
}
var sorted = _.sortBy(events, 'treatmentDate');
var mostRecent = _.last(sorted);
return (mostRecent && mostRecent.eventType) || 'Sensor Start';
}
sage.findLatestTimeChange = function findLatestTimeChange(sbx) {
var returnValue = {
'Sensor Start': {
found: false
}
, 'Sensor Change': {
found: false
}
};
var prevDate = {
'Sensor Start': 0
, 'Sensor Change': 0
};
_.each(sbx.data.sensorTreatments, function eachTreatment (treatment) {
['Sensor Start', 'Sensor Change'].forEach( function eachEvent(event) {
var treatmentDate = treatment.mills;
if (treatment.eventType === event && treatmentDate > prevDate[event] && treatmentDate <= sbx.time) {
prevDate[event] = treatmentDate;
var a = moment(sbx.time);
var b = moment(treatmentDate);
var days = a.diff(b,'days');
var hours = a.diff(b,'hours') - days * 24;
var age = a.diff(b,'hours');
var eventValue = returnValue[event];
if (!eventValue.found || (age >= 0 && age < eventValue.age)) {
eventValue.found = true;
eventValue.treatmentDate = treatmentDate;
eventValue.age = age;
eventValue.days = days;
eventValue.hours = hours;
eventValue.notes = treatment.notes;
eventValue.minFractions = a.diff(b,'minutes') - age * 60;
eventValue.display = '';
if (eventValue.age >= 24) {
eventValue.display += eventValue.days + 'd';
}
eventValue.display += eventValue.hours + 'h';
eventValue.displayLong = '';
if (eventValue.age >= 24) {
eventValue.displayLong += eventValue.days + ' ' + translate('days');
}
if (eventValue.displayLong.length > 0) {
eventValue.displayLong += ' ';
}
eventValue.displayLong += eventValue.hours + ' ' + translate('hours');
}
}
});
});
if (returnValue['Sensor Change'].found && returnValue['Sensor Start'].found &&
returnValue['Sensor Change'].treatmentDate >= returnValue['Sensor Start'].treatmentDate) {
returnValue['Sensor Start'].found = false;
}
returnValue.min = minButValid(returnValue);
var sensorInfo = returnValue[returnValue.min];
var prefs = sage.getPrefs(sbx);
var sendNotification = false;
var sound = 'incoming';
var message;
sensorInfo.level = levels.NONE;
if (sensorInfo.age >= prefs.urgent) {
sendNotification = sensorInfo.age === prefs.urgent;
message = translate('Sensor change/restart overdue!');
sound = 'persistent';
sensorInfo.level = levels.URGENT;
} else if (sensorInfo.age >= prefs.warn) {
sendNotification = sensorInfo.age === prefs.warn;
message = translate('Time to change/restart sensor');
sensorInfo.level = levels.WARN;
} else if (sensorInfo.age >= prefs.info) {
sendNotification = sensorInfo.age === prefs.info;
message = translate('Change/restart sensor soon');
sensorInfo.level = levels.INFO;
}
//allow for 20 minute period after a full hour during which we'll alert the user
if (prefs.enableAlerts && sendNotification && sensorInfo.minFractions <= 20) {
sensorInfo.notification = {
title: translate('Sensor age %1 days %2 hours', { params: [sensorInfo.days, sensorInfo.hours] })
, message: message
, pushoverSound: sound
, level: sensorInfo.level
, group: 'SAGE'
};
}
return returnValue;
};
sage.updateVisualisation = function updateVisualisation (sbx) {
var latest = sbx.properties.sage;
var sensorInfo = latest[latest.min];
var info = [];
['Sensor Change', 'Sensor Start'].forEach( function eachEvent(event) {
if (latest[event].found) {
var label = event === 'Sensor Change' ? 'Sensor Insert' : event;
info.push( { label: translate(label), value: new Date(latest[event].treatmentDate).toLocaleString() } );
info.push( { label: translate('Duration'), value: latest[event].displayLong } );
if (!_.isEmpty(latest[event].notes)) {
info.push({label: translate('Notes'), value: latest[event].notes});
}
}
});
var statusClass = null;
if (sensorInfo.level === levels.URGENT) {
statusClass = 'urgent';
} else if (sensorInfo.level === levels.WARN) {
statusClass = 'warn';
}
sbx.pluginBase.updatePillText(sage, {
value: sensorInfo.display
, label: translate('SAGE')
, info: info
, pillClass: statusClass
});
};
return sage;
}
module.exports = init;
|
vittetoe/cgm-remote-monitor
|
lib/plugins/sensorage.js
|
JavaScript
|
agpl-3.0
| 6,353
|
/**
* searx is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* searx is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with searx. If not, see < http://www.gnu.org/licenses/ >.
*
* (C) 2014 by Thomas Pointhuber, <thomas.pointhuber@gmx.at>
*/
$(document).ready(function(){
/**
* focus element if class="autofocus" and id="q"
*/
$('#q.autofocus').focus();
/**
* select full content on click if class="select-all-on-click"
*/
$(".select-all-on-click").click(function () {
$(this).select();
});
/**
* change text during btn-collapse click if possible
*/
$('.btn-collapse').click(function() {
var btnTextCollapsed = $(this).data('btn-text-collapsed');
var btnTextNotCollapsed = $(this).data('btn-text-not-collapsed');
if(btnTextCollapsed !== '' && btnTextNotCollapsed !== '') {
if($(this).hasClass('collapsed')) {
new_html = $(this).html().replace(btnTextCollapsed, btnTextNotCollapsed);
} else {
new_html = $(this).html().replace(btnTextNotCollapsed, btnTextCollapsed);
}
$(this).html(new_html);
}
});
/**
* change text during btn-toggle click if possible
*/
$('.btn-toggle .btn').click(function() {
var btnClass = 'btn-' + $(this).data('btn-class');
var btnLabelDefault = $(this).data('btn-label-default');
var btnLabelToggled = $(this).data('btn-label-toggled');
if(btnLabelToggled !== '') {
if($(this).hasClass('btn-default')) {
new_html = $(this).html().replace(btnLabelDefault, btnLabelToggled);
} else {
new_html = $(this).html().replace(btnLabelToggled, btnLabelDefault);
}
$(this).html(new_html);
}
$(this).toggleClass(btnClass);
$(this).toggleClass('btn-default');
});
/**
* change text during btn-toggle click if possible
*/
$('.media-loader').click(function() {
var target = $(this).data('target');
var iframe_load = $(target + ' > iframe');
var srctest = iframe_load.attr('src');
if(srctest === undefined || srctest === false){
iframe_load.attr('src', iframe_load.data('src'));
}
});
/**
* Select or deselect every categories on double clic
*/
$(".btn-sm").dblclick(function() {
var btnClass = 'btn-' + $(this).data('btn-class'); // primary
if($(this).hasClass('btn-default')) {
$(".btn-sm > input").attr('checked', 'checked');
$(".btn-sm > input").prop("checked", true);
$(".btn-sm").addClass(btnClass);
$(".btn-sm").addClass('active');
$(".btn-sm").removeClass('btn-default');
} else {
$(".btn-sm > input").attr('checked', '');
$(".btn-sm > input").removeAttr('checked');
$(".btn-sm > input").checked = false;
$(".btn-sm").removeClass(btnClass);
$(".btn-sm").removeClass('active');
$(".btn-sm").addClass('btn-default');
}
});
});
|
PwnArt1st/searx
|
searx/static/themes/sandyseventiesspeedboat/js/searx_src/element_modifiers.js
|
JavaScript
|
agpl-3.0
| 3,733
|
"use strict";
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var A = (function () {
function A() { }
return A;
})();
var B = (function (_super) {
__extends(B, _super);
function B() {
_super.apply(this, arguments);
}
return B;
})(A);
|
bolinfest/typescript
|
tests/baselines/reference/strictMode1.commonjs.js
|
JavaScript
|
apache-2.0
| 377
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* Operator x & y returns ToNumber(x) & ToNumber(y)
*
* @path ch11/11.10/11.10.1/S11.10.1_A3_T1.2.js
* @description Type(x) and Type(y) are primitive number and Number object
*/
//CHECK#1
if ((1 & 1) !== 1) {
$ERROR('#1: (1 & 1) === 1. Actual: ' + ((1 & 1)));
}
//CHECK#2
if ((new Number(1) & 1) !== 1) {
$ERROR('#2: (new Number(1) & 1) === 1. Actual: ' + ((new Number(1) & 1)));
}
//CHECK#3
if ((1 & new Number(1)) !== 1) {
$ERROR('#3: (1 & new Number(1)) === 1. Actual: ' + ((1 & new Number(1))));
}
//CHECK#4
if ((new Number(1) & new Number(1)) !== 1) {
$ERROR('#4: (new Number(1) & new Number(1)) === 1. Actual: ' + ((new Number(1) & new Number(1))));
}
|
popravich/typescript
|
tests/Fidelity/test262/suite/ch11/11.10/11.10.1/S11.10.1_A3_T1.2.js
|
JavaScript
|
apache-2.0
| 813
|
/*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
*/
/**
* Gets URI that identifies the test.
* @return uri identifier of test
*/
function getTargetURI() {
return "http://www.w3.org/2001/DOM-Test-Suite/level1/core/hc_namednodemapgetnameditem";
}
var docsLoaded = -1000000;
var builder = null;
//
// This function is called by the testing framework before
// running the test suite.
//
// If there are no configuration exceptions, asynchronous
// document loading is started. Otherwise, the status
// is set to complete and the exception is immediately
// raised when entering the body of the test.
//
function setUpPage() {
setUpPageStatus = 'running';
try {
//
// creates test document builder, may throw exception
//
builder = createConfiguredBuilder();
docsLoaded = 0;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
docsLoaded += preload(docRef, "doc", "hc_staff");
if (docsLoaded == 1) {
setUpPageStatus = 'complete';
}
} catch(ex) {
catchInitializationError(builder, ex);
setUpPageStatus = 'complete';
}
}
//
// This method is called on the completion of
// each asychronous load started in setUpTests.
//
// When every synchronous loaded document has completed,
// the page status is changed which allows the
// body of the test to be executed.
function loadComplete() {
if (++docsLoaded == 1) {
setUpPageStatus = 'complete';
}
}
/**
*
Retrieve the second "p" element and create a NamedNodeMap
listing of the attributes of the last child. Once the
list is created an invocation of the "getNamedItem(name)"
method is done with name="title". This should result
in the title Attr node being returned.
* @author Curt Arnold
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-1074577549
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-349467F9
* @see http://www.w3.org/Bugs/Public/show_bug.cgi?id=236
* @see http://lists.w3.org/Archives/Public/www-dom-ts/2003Jun/0011.html
*/
function hc_namednodemapgetnameditem() {
var success;
if(checkInitialization(builder, "hc_namednodemapgetnameditem") != null) return;
var doc;
var elementList;
var testEmployee;
var attributes;
var domesticAttr;
var attrName;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
doc = load(docRef, "doc", "hc_staff");
elementList = doc.getElementsByTagName("acronym");
testEmployee = elementList.item(1);
attributes = testEmployee.attributes;
domesticAttr = attributes.getNamedItem("title");
attrName = domesticAttr.name;
assertEqualsAutoCase("attribute", "nodeName","title",attrName);
}
function runTest() {
hc_namednodemapgetnameditem();
}
|
modulexcite/domino
|
test/w3c/level1/core/obsolete/hc_namednodemapgetnameditem.js
|
JavaScript
|
bsd-2-clause
| 3,456
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
File Name: 15.9.5.10.js
ECMA Section: 15.9.5.10
Description: Date.prototype.getDate
1.Let t be this time value.
2.If t is NaN, return NaN.
3.Return DateFromTime(LocalTime(t)).
Author: christine@netscape.com
Date: 12 november 1997
*/
var SECTION = "15.9.5.10";
var VERSION = "ECMA_1";
startTest();
var TITLE = "Date.prototype.getDate()";
writeHeaderToLog( SECTION + " "+ TITLE);
// some daylight savings time cases
var DST_START_1998 = GetDSTStart(TimeFromYear(1998));
addTestCase( DST_START_1998 );
new TestCase( SECTION,
"(new Date(NaN)).getDate()",
NaN,
(new Date(NaN)).getDate() );
new TestCase( SECTION,
"Date.prototype.getDate.length",
0,
Date.prototype.getDate.length );
test();
function addTestCase( t ) {
var start = TimeFromYear(YearFromTime(t));
var stop = TimeFromYear(YearFromTime(t) + 1);
for (var d = start; d < stop; d += msPerDay)
{
new TestCase( SECTION,
"(new Date("+d+")).getDate()",
DateFromTime(LocalTime(d)),
(new Date(d)).getDate() );
}
}
|
daejunpark/jsaf
|
tests/parser_tests/js/src/tests/ecma/Date/15.9.5.10-8.js
|
JavaScript
|
bsd-3-clause
| 3,029
|
var rewire = require("rewire");
var Connection = rewire("../lib/connection");
var events = require("events");
var sinon = require("sinon");
var lolex = require("lolex");
var Q = require("q");
describe("Connection", function() {
describe("constructor", function () {
var originalEnv;
before(function() {
originalEnv = process.env.NODE_ENV;
});
after(function() {
process.env.NODE_ENV = originalEnv;
});
beforeEach(function() {
process.env.NODE_ENV = "";
});
// Issue #50
it("should use gateway.sandbox.push.apple.com as the default connection address", function () {
expect(Connection().options.address).to.equal("gateway.sandbox.push.apple.com");
});
it("should use gateway.push.apple.com when NODE_ENV=production", function () {
process.env.NODE_ENV = "production";
expect(Connection().options.address).to.equal("gateway.push.apple.com");
});
it("should give precedence to production flag over NODE_ENV=production", function () {
process.env.NODE_ENV = "production";
expect(Connection({ production: false }).options.address).to.equal("gateway.sandbox.push.apple.com");
});
it("should use gateway.push.apple.com when production:true", function () {
expect(Connection({production:true}).options.address).to.equal("gateway.push.apple.com");
});
it("should use a custom address when passed", function () {
expect(Connection({address: "testaddress"}).options.address).to.equal("testaddress");
});
describe("gateway option", function() {
it("uses the legacy gateway option when supplied", function() {
expect(Connection({gateway: "testaddress"}).options.address).to.equal("testaddress");
});
});
describe("address is passed", function() {
it("sets production to true when using production address", function() {
expect(Connection({address: "gateway.push.apple.com"}).options.production).to.be.true;
});
it("sets production to false when using sandbox address", function() {
process.env.NODE_ENV = "production";
expect(Connection({address: "gateway.sandbox.push.apple.com"}).options.production).to.be.false;
});
});
});
describe("#loadCredentials", function () {
var loadStub, parseStub, validateStub, removeStubs;
beforeEach(function() {
loadStub = sinon.stub();
loadStub.displayName = "loadCredentials";
parseStub = sinon.stub();
parseStub.displayName = "parseCredentials";
validateStub = sinon.stub();
validateStub.displayName = "validateCredentials";
removeStubs = Connection.__set__({
"loadCredentials": loadStub,
"parseCredentials": parseStub,
"validateCredentials": validateStub,
});
});
afterEach(function() {
removeStubs();
});
it("only loads credentials once", function() {
loadStub.returns(Q({}));
var connection = Connection();
connection.loadCredentials();
connection.loadCredentials();
expect(loadStub).to.be.calledOnce;
});
describe("with valid credentials", function() {
var credentials;
var testOptions = {
pfx: "myCredentials.pfx", cert: "myCert.pem", key: "myKey.pem", ca: "myCa.pem",
passphrase: "apntest", production: true
};
beforeEach(function() {
loadStub.withArgs(sinon.match(function(v) {
return v.pfx === "myCredentials.pfx" && v.cert === "myCert.pem" && v.key === "myKey.pem" &&
v.ca === "myCa.pem" && v.passphrase === "apntest";
})).returns(Q({ pfx: "myPfxData", cert: "myCertData", key: "myKeyData", ca: ["myCaData"], passphrase: "apntest" }));
parseStub.returnsArg(0);
credentials = Connection(testOptions).loadCredentials();
});
it("should be fulfilled", function () {
return expect(credentials).to.be.fulfilled;
});
describe("the validation stage", function() {
it("is called once", function() {
return credentials.finally(function() {
expect(validateStub).to.be.calledOnce;
});
});
it("is passed the production flag", function() {
return credentials.finally(function() {
expect(validateStub.getCall(0).args[0]).to.have.property("production", true);
});
});
describe("passed credentials", function() {
it("contains the PFX data", function() {
return credentials.finally(function() {
expect(validateStub.getCall(0).args[0]).to.have.property("pfx", "myPfxData");
});
});
it("contains the key data", function() {
return credentials.finally(function() {
expect(validateStub.getCall(0).args[0]).to.have.property("key", "myKeyData");
});
});
it("contains the certificate data", function() {
return credentials.finally(function() {
expect(validateStub.getCall(0).args[0]).to.have.property("cert", "myCertData");
});
});
it("includes passphrase", function() {
return credentials.finally(function() {
expect(validateStub.getCall(0).args[0]).to.have.property("passphrase", "apntest");
});
});
});
});
describe("resolution value", function() {
it("contains the PFX data", function() {
return expect(credentials).to.eventually.have.property("pfx", "myPfxData");
});
it("contains the key data", function() {
return expect(credentials).to.eventually.have.property("key", "myKeyData");
});
it("contains the certificate data", function() {
return expect(credentials).to.eventually.have.property("cert", "myCertData");
});
it("contains the CA data", function() {
return expect(credentials).to.eventually.have.deep.property("ca[0]", "myCaData");
});
it("includes passphrase", function() {
return expect(credentials).to.eventually.have.property("passphrase", "apntest");
});
});
});
describe("credential file cannot be parsed", function() {
beforeEach(function() {
loadStub.returns(Q({ cert: "myCertData", key: "myKeyData" }));
parseStub.throws(new Error("unable to parse key"));
});
it("should resolve with the credentials", function() {
var credentials = Connection({ cert: "myUnparseableCert.pem", key: "myUnparseableKey.pem" }).loadCredentials();
return expect(credentials).to.become({ cert: "myCertData", key: "myKeyData" });
});
it("should log an error", function() {
var debug = sinon.spy();
var reset = Connection.__set__("debug", debug);
var credentials = Connection({ cert: "myUnparseableCert.pem", key: "myUnparseableKey.pem" }).loadCredentials();
return credentials.finally(function() {
reset();
expect(debug).to.be.calledWith(sinon.match(function(err) {
return err.message ? err.message.match(/unable to parse key/) : false;
}, "\"unable to parse key\""));
});
});
it("should not attempt to validate", function() {
var credentials = Connection({ cert: "myUnparseableCert.pem", key: "myUnparseableKey.pem" }).loadCredentials();
return credentials.finally(function() {
expect(validateStub).to.not.be.called;
});
});
});
describe("credential validation fails", function() {
it("should be rejected", function() {
loadStub.returns(Q({ cert: "myCertData", key: "myMismatchedKeyData" }));
parseStub.returnsArg(0);
validateStub.throws(new Error("certificate and key do not match"));
var credentials = Connection({ cert: "myCert.pem", key: "myMistmatchedKey.pem" }).loadCredentials();
return expect(credentials).to.eventually.be.rejectedWith(/certificate and key do not match/);
});
});
describe("credential file cannot be loaded", function() {
it("should be rejected", function() {
loadStub.returns(Q.reject(new Error("ENOENT, no such file or directory")));
var credentials = Connection({ cert: "noSuchFile.pem", key: "myKey.pem" }).loadCredentials();
return expect(credentials).to.eventually.be.rejectedWith("ENOENT, no such file or directory");
});
});
});
describe("createSocket", function() {
var socketDouble, socketStub, removeSocketStub;
before(function() {
var loadCredentialsStub = sinon.stub(Connection.prototype, "loadCredentials");
loadCredentialsStub.returns(Q({
pfx: "pfxData",
key: "keyData",
cert: "certData",
ca: ["caData1", "caData2"],
passphrase: "apntest" }));
});
after(function() {
Connection.prototype.loadCredentials.restore();
});
beforeEach(function() {
socketDouble = new events.EventEmitter();
socketDouble.end = sinon.spy();
socketStub = sinon.stub();
socketStub.callsArg(2);
socketStub.returns(socketDouble);
removeSocketStub = Connection.__set__("createSocket", socketStub);
});
afterEach(function() {
socketDouble.removeAllListeners();
removeSocketStub();
});
it("loadCredentialss the module", function(done) {
var connection = Connection({ pfx: "myCredentials.pfx" });
return connection.createSocket().finally(function() {
expect(connection.loadCredentials).to.have.been.calledOnce;
done();
});
});
describe("with valid credentials", function() {
it("resolves", function() {
var connection = Connection({
cert: "myCert.pem",
key: "myKey.pem"
});
return expect(connection.createSocket()).to.be.fulfilled;
});
describe("the call to create socket", function() {
var connect;
it("passes PFX data", function() {
connect = Connection({
pfx: "myCredentials.pfx",
passphrase: "apntest"
}).createSocket();
return connect.then(function() {
var socketOptions = socketStub.args[0][1];
expect(socketOptions.pfx).to.equal("pfxData");
});
});
it("passes the passphrase", function() {
connect = Connection({
passphrase: "apntest",
cert: "myCert.pem",
key: "myKey.pem"
}).createSocket();
return connect.then(function() {
var socketOptions = socketStub.args[0][1];
expect(socketOptions.passphrase).to.equal("apntest");
});
});
it("passes the cert", function() {
connect = Connection({
cert: "myCert.pem",
key: "myKey.pem"
}).createSocket();
return connect.then(function() {
var socketOptions = socketStub.args[0][1];
expect(socketOptions.cert).to.equal("certData");
});
});
it("passes the key", function() {
connect = Connection({
cert: "test/credentials/support/cert.pem",
key: "test/credentials/support/key.pem"
}).createSocket();
return connect.then(function() {
var socketOptions = socketStub.args[0][1];
expect(socketOptions.key).to.equal("keyData");
});
});
it("passes the ca certificates", function() {
connect = Connection({
cert: "test/credentials/support/cert.pem",
key: "test/credentials/support/key.pem",
ca: [ "test/credentials/support/issuerCert.pem" ]
}).createSocket();
return connect.then(function() {
var socketOptions = socketStub.args[0][1];
expect(socketOptions.ca[0]).to.equal("caData1");
});
});
});
});
describe("intialization failure", function() {
it("is rejected", function() {
var connection = Connection({ pfx: "a-non-existant-file-which-really-shouldnt-exist.pfx" });
connection.on("error", function() {});
connection.loadCredentials = sinon.stub();
connection.loadCredentials.returns(Q.reject(new Error("loadCredentials failed")));
return expect(connection.createSocket()).to.be.rejectedWith("loadCredentials failed");
});
});
describe("timeout option", function() {
var clock, timeoutRestore;
beforeEach(function() {
clock = lolex.createClock();
timeoutRestore = Connection.__set__({
"setTimeout": clock.setTimeout,
"clearTimeout": clock.clearTimeout
});
});
afterEach(function() {
timeoutRestore();
});
it("ends the socket when connection takes too long", function() {
var connection = Connection({connectTimeout: 3000}).createSocket();
socketStub.onCall(0).returns(socketDouble);
process.nextTick(function(){
clock.tick(5000);
});
return connection.then(function() {
throw "connection did not time out";
}, function() {
expect(socketDouble.end).to.have.been.called;
});
});
it("does not end the socket when the connnection succeeds", function() {
var connection = Connection({connectTimeout: 3000}).createSocket();
return connection.then(function() {
clock.tick(5000);
expect(socketDouble.end).to.not.have.been.called;
});
});
it("does not end the socket when the connection fails", function() {
var connection = Connection({connectTimeout: 3000}).createSocket();
socketStub.onCall(0).returns(socketDouble);
process.nextTick(function() {
socketDouble.emit("close");
});
return connection.then(function() {
throw "connection should have failed";
}, function() {
clock.tick(5000);
expect(socketDouble.end).to.not.have.been.called;
});
});
it("does not fire when disabled", function() {
var connection = Connection({connectTimeout: 0}).createSocket();
socketStub.onCall(0).returns(socketDouble);
process.nextTick(function() {
clock.tick(100000);
socketDouble.emit("close");
});
return connection.then(function() {
throw "connection should have failed";
}, function() {
expect(socketDouble.end).to.not.have.been.called;
});
});
context("timeout fires before socket is created", function() {
it("does not throw", function() {
var connection = Connection({connectTimeout: 100});
connection.credentialsPromise = Q.defer();
connection.createSocket();
expect(function() { clock.tick(500); }).to.not.throw(TypeError);
});
});
context("after timeout fires", function() {
it("does not throw if socket connects", function() {
var connection = Connection({connectTimeout: 100});
socketStub.onCall(0).returns(socketDouble);
connection.loadCredentials().then(function() {
clock.tick(500);
});
return connection.createSocket().then(null, function() {
connection.deferredConnection = null;
expect(socketStub.getCall(0).args[2]).to.not.throw(TypeError);
});
});
});
});
});
describe("validNotification", function() {
describe("notification is shorter than max allowed", function() {
it("returns true", function() {
var connection = Connection();
var notification = { length: function() { return 128; }};
expect(connection.validNotification(notification)).to.equal(true);
});
});
describe("notification is the maximum length", function() {
it("returns true", function() {
var connection = Connection();
var notification = { length: function() { return 2048; }};
expect(connection.validNotification(notification)).to.equal(true);
});
});
describe("notification too long", function() {
it("returns false", function() {
var connection = Connection();
var notification = { length: function() { return 2176; }};
expect(connection.validNotification(notification)).to.equal(false);
});
});
describe("VoIP flag set", function() {
it("allows longer payload", function() {
var connection = Connection({"voip": true});
var notification = { length: function() { return 4096; }};
expect(connection.validNotification(notification)).to.equal(true);
});
});
});
});
|
lopper/node-apn
|
test/connection.js
|
JavaScript
|
mit
| 15,395
|
module.exports = { prefix: 'fab', iconName: 'r-project', icon: [581, 512, [], "f4f7", "M581 226.6C581 119.1 450.9 32 290.5 32S0 119.1 0 226.6C0 322.4 103.3 402 239.4 418.1V480h99.1v-61.5c24.3-2.7 47.6-7.4 69.4-13.9L448 480h112l-67.4-113.7c54.5-35.4 88.4-84.9 88.4-139.7zm-466.8 14.5c0-73.5 98.9-133 220.8-133s211.9 40.7 211.9 133c0 50.1-26.5 85-70.3 106.4-2.4-1.6-4.7-2.9-6.4-3.7-10.2-5.2-27.8-10.5-27.8-10.5s86.6-6.4 86.6-92.7-90.6-87.9-90.6-87.9h-199V361c-74.1-21.5-125.2-67.1-125.2-119.9zm225.1 38.3v-55.6c57.8 0 87.8-6.8 87.8 27.3 0 36.5-38.2 28.3-87.8 28.3zm-.9 72.5H365c10.8 0 18.9 11.7 24 19.2-16.1 1.9-33 2.8-50.6 2.9v-22.1z"] };
|
persy/appunti_persycchiotto
|
static/fonts/fontawesome/advanced-options/use-with-node-js/fontawesome-free-brands/faRProject.js
|
JavaScript
|
mit
| 637
|
(function( $ ) {
module( "autocomplete: core" );
test( "prevent form submit on enter when menu is active", function() {
expect( 2 );
var event,
element = $( "#autocomplete" )
.autocomplete({
source: [ "java", "javascript" ]
})
.val( "ja" )
.autocomplete( "search" ),
menu = element.autocomplete( "widget" );
event = $.Event( "keydown" );
event.keyCode = $.ui.keyCode.DOWN;
element.trigger( event );
deepEqual( menu.find( ".ui-menu-item:has(.ui-state-focus)" ).length, 1, "menu item is active" );
event = $.Event( "keydown" );
event.keyCode = $.ui.keyCode.ENTER;
element.trigger( event );
ok( event.isDefaultPrevented(), "default action is prevented" );
});
test( "allow form submit on enter when menu is not active", function() {
expect( 1 );
var event,
element = $( "#autocomplete" )
.autocomplete({
autoFocus: false,
source: [ "java", "javascript" ]
})
.val( "ja" )
.autocomplete( "search" );
event = $.Event( "keydown" );
event.keyCode = $.ui.keyCode.ENTER;
element.trigger( event );
ok( !event.isDefaultPrevented(), "default action is prevented" );
});
(function() {
test( "up arrow invokes search - input", function() {
arrowsInvokeSearch( "#autocomplete", true, true );
});
test( "down arrow invokes search - input", function() {
arrowsInvokeSearch( "#autocomplete", false, true );
});
test( "up arrow invokes search - textarea", function() {
arrowsInvokeSearch( "#autocomplete-textarea", true, false );
});
test( "down arrow invokes search - textarea", function() {
arrowsInvokeSearch( "#autocomplete-textarea", false, false );
});
test( "up arrow invokes search - contenteditable", function() {
arrowsInvokeSearch( "#autocomplete-contenteditable", true, false );
});
test( "down arrow invokes search - contenteditable", function() {
arrowsInvokeSearch( "#autocomplete-contenteditable", false, false );
});
test( "up arrow moves focus - input", function() {
arrowsMoveFocus( "#autocomplete", true );
});
test( "down arrow moves focus - input", function() {
arrowsMoveFocus( "#autocomplete", false );
});
test( "up arrow moves focus - textarea", function() {
arrowsMoveFocus( "#autocomplete-textarea", true );
});
test( "down arrow moves focus - textarea", function() {
arrowsMoveFocus( "#autocomplete-textarea", false );
});
test( "up arrow moves focus - contenteditable", function() {
arrowsMoveFocus( "#autocomplete-contenteditable", true );
});
test( "down arrow moves focus - contenteditable", function() {
arrowsMoveFocus( "#autocomplete-contenteditable", false );
});
function arrowsInvokeSearch( id, isKeyUp, shouldMove ) {
expect( 1 );
var didMove = false,
element = $( id ).autocomplete({
source: [ "a" ],
delay: 0,
minLength: 0
});
element.autocomplete( "instance" )._move = function() {
didMove = true;
};
element.simulate( "keydown", { keyCode: ( isKeyUp ? $.ui.keyCode.UP : $.ui.keyCode.DOWN ) } );
equal( didMove, shouldMove, "respond to arrow" );
}
function arrowsMoveFocus( id, isKeyUp ) {
expect( 1 );
var element = $( id ).autocomplete({
source: [ "a" ],
delay: 0,
minLength: 0
});
element.autocomplete( "instance" )._move = function() {
ok( true, "repsond to arrow" );
};
element.autocomplete( "search" );
element.simulate( "keydown", { keyCode: ( isKeyUp ? $.ui.keyCode.UP : $.ui.keyCode.DOWN ) } );
}
})();
asyncTest( "handle race condition", function() {
expect( 3 );
var count = 0,
element = $( "#autocomplete" ).autocomplete({
source: function( request, response ) {
count++;
if ( request.term.length === 1 ) {
equal( count, 1, "request with 1 character is first" );
setTimeout(function() {
response([ "one" ]);
setTimeout( checkResults, 1 );
}, 1 );
return;
}
equal( count, 2, "request with 2 characters is second" );
response([ "two" ]);
}
});
element.autocomplete( "search", "a" );
element.autocomplete( "search", "ab" );
function checkResults() {
equal( element.autocomplete( "widget" ).find( ".ui-menu-item" ).text(), "two",
"correct results displayed" );
start();
}
});
test( "ARIA", function() {
expect( 7 );
var element = $( "#autocomplete" ).autocomplete({
source: [ "java", "javascript" ]
}),
liveRegion = element.autocomplete( "instance" ).liveRegion;
equal( liveRegion.text(), "", "Empty live region on create" );
element.autocomplete( "search", "j" );
equal( liveRegion.text(), "2 results are available, use up and down arrow keys to navigate.",
"Live region for multiple values" );
element.simulate( "keydown", { keyCode: $.ui.keyCode.DOWN } );
equal( liveRegion.text(), "2 results are available, use up and down arrow keys to navigate.",
"Live region not changed on focus" );
element.one( "autocompletefocus", function( event ) {
event.preventDefault();
});
element.simulate( "keydown", { keyCode: $.ui.keyCode.DOWN } );
equal( liveRegion.text(), "javascript",
"Live region updated when default focus is prevented" );
element.autocomplete( "search", "javas" );
equal( liveRegion.text(), "1 result is available, use up and down arrow keys to navigate.",
"Live region for one value" );
element.autocomplete( "search", "z" );
equal( liveRegion.text(), "No search results.",
"Live region for no values" );
element.autocomplete( "search", "j" );
equal( liveRegion.text(), "2 results are available, use up and down arrow keys to navigate.",
"Live region for multiple values" );
});
test( ".replaceWith() (#9172)", function() {
expect( 1 );
var element = $( "#autocomplete" ).autocomplete(),
replacement = "<div>test</div>",
parent = element.parent();
element.replaceWith( replacement );
equal( parent.html().toLowerCase(), replacement );
});
}( jQuery ) );
|
yuyang545262477/Resume
|
项目三jQueryMobile/bower_components/jquery-ui-tabs/tests/unit/autocomplete/autocomplete_core.js
|
JavaScript
|
mit
| 5,813
|
import _extends from"@babel/runtime/helpers/extends";import _objectWithoutProperties from"@babel/runtime/helpers/objectWithoutProperties";var _excluded=["children","closing","toggleRef","popupDirection"];import{createScopedElement}from"../../lib/jsxRuntime";import{getClassName}from"../../helpers/getClassName";import{classNames}from"../../lib/classNames";import{usePlatform}from"../../hooks/usePlatform";import{FocusTrap}from"../FocusTrap/FocusTrap";import"./ActionSheet.css";var stopPropagation=function(e){return e.stopPropagation()},ActionSheetDropdown=function(e){var o=e.children,t=e.closing,r=(e.toggleRef,e.popupDirection,_objectWithoutProperties(e,_excluded)),e=usePlatform(),e=getClassName("ActionSheet",e);return createScopedElement(FocusTrap,_extends({},r,{onClick:stopPropagation,vkuiClass:classNames(e,{"ActionSheet--closing":t})}),o)};export{ActionSheetDropdown};
|
cdnjs/cdnjs
|
ajax/libs/vkui/4.27.2/cssm/components/ActionSheet/ActionSheetDropdown.min.js
|
JavaScript
|
mit
| 878
|
'use strict';
var path = require('path');
var fs = require('fs');
var rimraf = require('rimraf');
var mkdirp = require('mkdirp');
var _ = require('lodash');
var helpers = module.exports;
helpers.directory = function directory(dir) {
return function directory(done) {
process.chdir(__dirname);
rimraf(dir, function (err) {
if (err) {
return done(err);
}
mkdirp(dir, function (err) {
if (err) {
return done(err);
}
process.chdir(dir);
done();
});
});
};
};
helpers.blocks = function () {
return [{
type: 'js',
dest: 'scripts/site.js',
searchPath: [],
indent: ' ',
src: [
'foo.js',
'bar.js',
'baz.js'
],
raw: [
' <!-- build:js scripts/site.js -->',
' <script src="foo.js"></script>',
' <script src="bar.js"></script>',
' <script src="baz.js"></script>',
' <!-- endbuild -->'
]
}];
};
helpers.cssBlock = function () {
return {
type: 'css',
dest: '/styles/main.min.js',
searchPath: [],
indent: ' ',
src: [
'foo.js',
'bar.js',
'baz.js'
],
raw: [
' <!-- build:css sstyles/main.min.css -->',
' <link rel="stylesheet" href="styles/main.css">',
' <!-- endbuild -->'
]
};
};
helpers.createFile = function (name, dir, blocks) {
return {
name: name,
blocks: blocks,
dir: dir,
searchPath: [dir]
};
};
helpers.file = {
mkdir: function (path, mode) {
fs.mkdirSync(path, mode);
},
write: function (path, content) {
return fs.writeFileSync(path, content);
},
copy: function (srcFile, destFile, encoding) {
var content = fs.readFileSync(srcFile, encoding);
fs.writeFileSync(destFile, content, encoding);
}
};
helpers.makeFinder = function (mapping) {
return {
find: function (s, b) {
var output;
if (_.isString(b)) {
b = [b];
}
var dir = _.find(b, function (d) {
return mapping[path.join(d, s).replace(/\\/g, '/')];
});
var file = typeof dir !== 'undefined' ? mapping[path.join(dir, s).replace(/\\/g, '/')] : s;
if (_.isArray(file)) {
output = file[0];
} else {
output = file;
}
return output;
}
};
};
helpers.normalize = function (object) {
// turns {'foo/bar': ['app/bar.js', 'app/baz.js']}
// into {'foo\\bar': ['app\\bar.js', 'app\\baz.js']} on Windows
if (process.platform !== 'win32') {
return object;
}
if (object) {
if (_.isString(object)) {
object = path.normalize(object);
} else if (_.isArray(object)) {
for (var i = 0; i < object.length; i++) {
object[i] = helpers.normalize(object[i]);
}
} else {
for (var prop in object) {
if (object.hasOwnProperty(prop)) {
if (prop.indexOf('/') !== -1) {
object[path.normalize(prop)] = helpers.normalize(object[prop]);
delete object[prop];
} else {
object[prop] = helpers.normalize(object[prop]);
}
}
}
}
}
return object;
};
|
alippai/grunt-usemin
|
test/helpers.js
|
JavaScript
|
bsd-2-clause
| 3,148
|
var Twig = Twig || require("../twig"),
twig = twig || Twig.twig;
describe("Twig.js Expressions ->", function() {
var numeric_test_data = [
{a: 10, b: 15},
{a: 0, b: 0},
{a: 1, b: 11},
{a: 10444, b: 0.5},
{a: 1034, b: -53},
{a: -56, b: -1.7},
{a: 34, b: 0},
{a: 14, b: 14}
];
describe("Basic Operators ->", function() {
var string_data = [
{a: 'test', b: 'string'},
{a: 'test', b: ''},
{a: '', b: 'string'},
{a: '', b: ''},
];
it("should parse parenthesis", function() {
var test_template = twig({data: '{{ a - (b + c) }}'}),
d = {a: 10, b: 4, c: 2},
output = test_template.render(d);
output.should.equal( (d.a - (d.b + d.c)).toString() );
});
it("should parse nested parenthesis", function() {
var test_template = twig({data: '{{ a - ((b) + (1 + c)) }}'}),
d = {a: 10, b: 4, c: 2},
output = test_template.render(d);
output.should.equal( (d.a - (d.b + 1 + d.c)).toString() );
});
it("should add numbers", function() {
var test_template = twig({data: '{{ a + b }}'});
numeric_test_data.forEach(function(pair) {
var output = test_template.render(pair);
output.should.equal( (pair.a + pair.b).toString() );
});
});
it("should subtract numbers", function() {
var test_template = twig({data: '{{ a - b }}'});
numeric_test_data.forEach(function(pair) {
var output = test_template.render(pair);
output.should.equal( (pair.a - pair.b).toString() );
});
});
it("should multiply numbers", function() {
var test_template = twig({data: '{{ a * b }}'});
numeric_test_data.forEach(function(pair) {
var output = test_template.render(pair);
output.should.equal((pair.a * pair.b).toString() );
});
});
it("should divide numbers", function() {
var test_template = twig({data: '{{ a / b }}'});
numeric_test_data.forEach(function(pair) {
var output = test_template.render(pair);
output.should.equal((pair.a / pair.b).toString() );
});
});
it("should divide numbers and return an int result", function() {
var test_template = twig({data: '{{ a // b }}'});
numeric_test_data.forEach(function(pair) {
var output = test_template.render(pair);
// Get expected truncated result
var c = parseInt(pair.a/pair.b);
output.should.equal(c.toString() );
});
});
it("should raise numbers to a power", function() {
var test_template = twig({data: '{{ a ** b }}'});
var pow_test_data = [
{a: 2, b:3, c: 8}
, {a: 4, b:.5, c: 2}
, {a: 5, b: 1, c: 5}
];
pow_test_data.forEach(function(pair) {
var output = test_template.render(pair);
output.should.equal(pair.c.toString() );
});
});
it("should concatanate values", function() {
twig({data: '{{ "test" ~ a }}'}).render({a:1234}).should.equal("test1234");
twig({data: '{{ a ~ "test" ~ a }}'}).render({a:1234}).should.equal("1234test1234");
twig({data: '{{ "this" ~ "test" }}'}).render({a:1234}).should.equal("thistest");
// Test numbers
var test_template = twig({data: '{{ a ~ b }}'});
numeric_test_data.forEach(function(pair) {
var output = test_template.render(pair);
output.should.equal(pair.a.toString() + pair.b.toString());
});
// Test strings
test_template = twig({data: '{{ a ~ b }}'});
string_data.forEach(function(pair) {
var output = test_template.render(pair);
output.should.equal(pair.a.toString() + pair.b.toString());
});
});
it("should concatenate null and undefined values and not throw an exception", function() {
twig({data: '{{ a ~ b }}'}).render().should.equal("");
twig({data: '{{ a ~ b }}'}).render({
a: null,
b: null
}).should.equal("");
});
it("should handle multiple chained operations", function() {
var data = {a: 4.5, b: 10, c: 12, d: -0.25, e:0, f: 65, g: 21, h: -0.0002};
var test_template = twig({data: '{{a/b+c*d-e+f/g*h}}'});
var output = test_template.render(data);
var expected = data.a / data.b + data.c * data.d - data.e + data.f / data.g * data.h;
output.should.equal(expected.toString());
});
it("should handle parenthesis in chained operations", function() {
var data = {a: 4.5, b: 10, c: 12, d: -0.25, e:0, f: 65, g: 21, h: -0.0002};
var test_template = twig({data: '{{a /(b+c )*d-(e+f)/(g*h)}}'});
var output = test_template.render(data);
var expected = data.a / (data.b + data.c) * data.d - (data.e + data.f) / (data.g * data.h);
output.should.equal(expected.toString());
});
});
describe("Comparison Operators ->", function() {
var equality_data = [
{a: true, b: "true"},
{a: 1, b: "1"},
{a: 1, b: 1},
{a: 1, b: 1.0},
{a: "str", b: "str"},
{a: false, b: "false"}
];
var boolean_data = [
{a: true, b: true},
{a: true, b: false},
{a: false, b: true},
{a: false, b: false}
];
it("should support less then", function() {
var test_template = twig({data: '{{ a < b }}'});
numeric_test_data.forEach(function(pair) {
var output = test_template.render(pair);
output.should.equal((pair.a < pair.b).toString() );
});
});
it("should support less then or equal", function() {
var test_template = twig({data: '{{ a <= b }}'});
numeric_test_data.forEach(function(pair) {
var output = test_template.render(pair);
output.should.equal((pair.a <= pair.b).toString() );
});
});
it("should support greater then", function() {
var test_template = twig({data: '{{ a > b }}'});
numeric_test_data.forEach(function(pair) {
var output = test_template.render(pair);
output.should.equal((pair.a > pair.b).toString() );
});
});
it("should support greater then or equal", function() {
var test_template = twig({data: '{{ a >= b }}'});
numeric_test_data.forEach(function(pair) {
var output = test_template.render(pair);
output.should.equal((pair.a >= pair.b).toString() );
});
});
it("should support equals", function() {
var test_template = twig({data: '{{ a == b }}'});
boolean_data.forEach(function(pair) {
var output = test_template.render(pair);
output.should.equal((pair.a == pair.b).toString() );
});
equality_data.forEach(function(pair) {
var output = test_template.render(pair);
output.should.equal((pair.a == pair.b).toString() );
});
});
it("should support not equals", function() {
var test_template = twig({data: '{{ a != b }}'});
boolean_data.forEach(function(pair) {
var output = test_template.render(pair);
output.should.equal((pair.a != pair.b).toString() );
});
equality_data.forEach(function(pair) {
var output = test_template.render(pair);
output.should.equal((pair.a != pair.b).toString() );
});
});
it("should support boolean or", function() {
var test_template = twig({data: '{{ a or b }}'});
boolean_data.forEach(function(pair) {
var output = test_template.render(pair);
output.should.equal((pair.a || pair.b).toString() );
});
});
it("should support boolean and", function() {
var test_template = twig({data: '{{ a and b }}'});
boolean_data.forEach(function(pair) {
var output = test_template.render(pair);
output.should.equal((pair.a && pair.b).toString() );
});
});
it("should support boolean not", function() {
var test_template = twig({data: '{{ not a }}'});
test_template.render({a:false}).should.equal(true.toString());
test_template.render({a:true}).should.equal(false.toString());
});
});
describe("Other Operators ->", function() {
it("should support the ternary operator", function() {
var test_template = twig({data: '{{ a ? b:c }}'})
, output_t = test_template.render({a: true, b: "one", c: "two"})
, output_f = test_template.render({a: false, b: "one", c: "two"});
output_t.should.equal( "one" );
output_f.should.equal( "two" );
});
it("should support the ternary operator with objects in it", function() {
var test_template2 = twig({data: '{{ (a ? {"a":e+f}:{"a":1}).a }}'})
, output2 = test_template2.render({a: true, b: false, e: 1, f: 2});
output2.should.equal( "3" );
});
it("should support the ternary operator inside objects", function() {
var test_template2 = twig({data: '{{ {"b" : a or b ? {"a":e+f}:{"a":1} }.b.a }}'})
, output2 = test_template2.render({a: false, b: false, e: 1, f: 2});
output2.should.equal( "1" );
});
it("should support in/containment functionality for arrays", function() {
var test_template = twig({data: '{{ "a" in ["a", "b", "c"] }}'});
test_template.render().should.equal(true.toString());
var test_template = twig({data: '{{ "d" in ["a", "b", "c"] }}'});
test_template.render().should.equal(false.toString());
});
it("should support not in/containment functionality for arrays", function() {
var test_template = twig({data: '{{ "a" not in ["a", "b", "c"] }}'});
test_template.render().should.equal(false.toString());
var test_template = twig({data: '{{ "d" not in ["a", "b", "c"] }}'});
test_template.render().should.equal(true.toString());
});
it("should support in/containment functionality for strings", function() {
var test_template = twig({data: '{{ "at" in "hat" }}'});
test_template.render().should.equal(true.toString());
var test_template = twig({data: '{{ "d" in "not" }}'});
test_template.render().should.equal(false.toString());
});
it("should support not in/containment functionality for strings", function() {
var test_template = twig({data: '{{ "at" not in "hat" }}'});
test_template.render().should.equal(false.toString());
var test_template = twig({data: '{{ "d" not in "not" }}'});
test_template.render().should.equal(true.toString());
});
it("should support in/containment functionality for objects", function() {
var test_template = twig({data: '{{ "value" in {"key" : "value", "2": "other"} }}'});
test_template.render().should.equal(true.toString());
var test_template = twig({data: '{{ "d" in {"key_a" : "no"} }}'});
test_template.render().should.equal(false.toString());
});
it("should support not in/containment functionality for objects", function() {
var test_template = twig({data: '{{ "value" not in {"key" : "value", "2": "other"} }}'});
test_template.render().should.equal(false.toString());
var test_template = twig({data: '{{ "d" not in {"key_a" : "no"} }}'});
test_template.render().should.equal(true.toString());
});
});
});
|
moodtraffic/twig.js
|
test/test.expressions.js
|
JavaScript
|
bsd-2-clause
| 12,627
|
// @flow strict
import React from 'react';
import renderer from 'react-test-renderer';
import Icon from './Icon';
describe('Icon', () => {
const props = {
name: 'test',
icon: {
viewBox: '0 0 0 0',
path: '',
}
};
it('renders correctly', () => {
const tree = renderer.create(<Icon {...props} />).toJSON();
expect(tree).toMatchSnapshot();
});
});
|
alxshelepenok/gatsby-starter-lumen
|
src/components/Icon/Icon.test.js
|
JavaScript
|
mit
| 386
|
(function ($) {
// register namespace
$.extend(true, window, {
"Slick": {
"RowMoveManager": RowMoveManager
}
});
function RowMoveManager(options) {
var _grid;
var _canvas;
var _dragging;
var _self = this;
var _handler = new Slick.EventHandler();
var _defaults = {
cancelEditOnDrag: false
};
function init(grid) {
options = $.extend(true, {}, _defaults, options);
_grid = grid;
_canvas = _grid.getCanvasNode();
_handler
.subscribe(_grid.onDragInit, handleDragInit)
.subscribe(_grid.onDragStart, handleDragStart)
.subscribe(_grid.onDrag, handleDrag)
.subscribe(_grid.onDragEnd, handleDragEnd);
}
function destroy() {
_handler.unsubscribeAll();
}
function handleDragInit(e, dd) {
// prevent the grid from cancelling drag'n'drop by default
e.stopImmediatePropagation();
}
function handleDragStart(e, dd) {
var cell = _grid.getCellFromEvent(e);
if (options.cancelEditOnDrag && _grid.getEditorLock().isActive()) {
_grid.getEditorLock().cancelCurrentEdit();
}
if (_grid.getEditorLock().isActive() || !/move|selectAndMove/.test(_grid.getColumns()[cell.cell].behavior)) {
return false;
}
_dragging = true;
e.stopImmediatePropagation();
var selectedRows = _grid.getSelectedRows();
if (selectedRows.length === 0 || $.inArray(cell.row, selectedRows) == -1) {
selectedRows = [cell.row];
_grid.setSelectedRows(selectedRows);
}
var rowHeight = _grid.getOptions().rowHeight;
dd.selectedRows = selectedRows;
dd.selectionProxy = $("<div class='slick-reorder-proxy'/>")
.css("position", "absolute")
.css("zIndex", "99999")
.css("width", $(_canvas).innerWidth())
.css("height", rowHeight * selectedRows.length)
.appendTo(_canvas);
dd.guide = $("<div class='slick-reorder-guide'/>")
.css("position", "absolute")
.css("zIndex", "99998")
.css("width", $(_canvas).innerWidth())
.css("top", -1000)
.appendTo(_canvas);
dd.insertBefore = -1;
}
function handleDrag(e, dd) {
if (!_dragging) {
return;
}
e.stopImmediatePropagation();
var top = e.pageY - $(_canvas).offset().top;
dd.selectionProxy.css("top", top - 5);
var insertBefore = Math.max(0, Math.min(Math.round(top / _grid.getOptions().rowHeight), _grid.getDataLength()));
if (insertBefore !== dd.insertBefore) {
var eventData = {
"rows": dd.selectedRows,
"insertBefore": insertBefore
};
if (_self.onBeforeMoveRows.notify(eventData) === false) {
dd.guide.css("top", -1000);
dd.canMove = false;
} else {
dd.guide.css("top", insertBefore * _grid.getOptions().rowHeight);
dd.canMove = true;
}
dd.insertBefore = insertBefore;
}
}
function handleDragEnd(e, dd) {
if (!_dragging) {
return;
}
_dragging = false;
e.stopImmediatePropagation();
dd.guide.remove();
dd.selectionProxy.remove();
if (dd.canMove) {
var eventData = {
"rows": dd.selectedRows,
"insertBefore": dd.insertBefore
};
// TODO: _grid.remapCellCssClasses ?
_self.onMoveRows.notify(eventData);
}
}
$.extend(this, {
"onBeforeMoveRows": new Slick.Event(),
"onMoveRows": new Slick.Event(),
"init": init,
"destroy": destroy,
"pluginName": "RowMoveManager"
});
}
})(jQuery);
|
cdnjs/cdnjs
|
ajax/libs/6pac-slickgrid/2.4.19/plugins/slick.rowmovemanager.js
|
JavaScript
|
mit
| 3,693
|
/**
* Intercepts the standard WordPress gallery insert and edit.
*
* @copyright Greg Priday 2013
* @license GPL 2.0 http://www.gnu.org/licenses/gpl-2.0.html
*/
jQuery(function($){
var originalInsert = wp.media.editor.insert;
wp.media.editor.insert = function(h){
// Check that panels tab is active and that no dialogs are open.
if( !$('#wp-content-wrap').hasClass('panels-active') ) return originalInsert(h);
if( $('.panel-dialog:visible').length > 0 ) return originalInsert(h);
if(h.indexOf('[gallery') !== -1) {
// Get the IDs of the gallery
var attachments = wp.media.gallery.attachments( wp.shortcode.next( 'gallery', h ).shortcode );
var ids = attachments.models.map(function(e){ return e.id });
// Create a new gallery panel
// TODO support random and column arguments
var panel = $('#panels-dialog').panelsCreatePanel('SiteOrigin_Panels_Widgets_Gallery', {
'ids' : ids.join(',')
});
// The panel couldn't be created. Possible the widgets gallery isn't being used.
if(panel == null) originalInsert(h);
else panels.addPanel(panel, null, null, true);
return;
}
else if(h.indexOf('<a ') !== -1 || h.indexOf('<img ') !== -1) {
// Figure out how we can add this to panels
var $el = $(h);
var panel;
if($el.prop("tagName") == 'A' && $el.children().eq(0 ).prop('tagName') == 'IMG'){
// This is an image with a link
panel = $('#panels-dialog').panelsCreatePanel('SiteOrigin_Panels_Widgets_Image', {
'href' : $el.attr('href'),
'src' : $el.children().eq(0 ).attr('src')
});
}
else if($el.prop("tagName") == 'IMG'){
// This is just an image tag
panel = $('#panels-dialog').panelsCreatePanel('SiteOrigin_Panels_Widgets_Image', {
'src' : $el.attr('src')
});
}
else if($el.prop('tagName') == 'A' && ($el.attr('href' ).indexOf('.mp4') !== -1 || $el.attr('href' ).indexOf('.avi') !== -1)){
panel = $('#panels-dialog').panelsCreatePanel('SiteOrigin_Panels_Widgets_Video', {
'url' : $el.attr('href' )
});
}
// The panel couldn't be created. Possible the widgets gallery isn't being used.
if(panel == null) originalInsert(h);
else panels.addPanel(panel, null, null, true);
return;
}
else {
// Create a new gallery panel
var panel = $('#panels-dialog').panelsCreatePanel('WP_Widget_Text', {
'text' : h
});
// The panel couldn't be created. Possible the widgets gallery isn't being used.
if(panel == null) originalInsert(h);
else panels.addPanel(panel, null, null, true);
}
// Incase we've added any new panels
originalInsert(h);
}
// When the user clicks on the select button, we need to display the gallery editing
$('body').on({
click: function(event){
// Make sure the media gallery API exists
if ( typeof wp === 'undefined' || ! wp.media || ! wp.media.gallery ) return;
event.preventDefault();
// Activate the media editor
var $$ = $(this);
var dialog = $('.panels-admin-dialog:visible' );
var val = dialog.find('*[name$="[ids]"]').val();
if(val.indexOf('{demo') === 0 || val.indexOf('{default') === 0) val = '-'; // This removes the demo or default content
if(val == '' && $('#post_ID' ).val() == null) val = '-';
// Close the gallery dialog so it doesn't interfere with wp.media.gallery
dialog.find('.ui-dialog-content' ).dialog('close');
var frame = wp.media.gallery.edit('[gallery ids="' + val + '"]');
// When the gallery-edit state is updated, copy the attachment ids across
frame.state('gallery-edit').on( 'update', function( selection ) {
dialog.find('.ui-dialog-content' ).dialog('open');
var ids = selection.models.map(function(e){ return e.id });
dialog.find('input[name$="[ids]"]' ).val(ids.join(','));
});
frame.on('escape', function(){
// Reopen the dialog
dialog.find('.ui-dialog-content' ).dialog('open');
});
return false;
}
}, '.so-gallery-widget-select-attachments');
});
|
bryanerayner/bryanerayner-old
|
wp-content/plugins/siteorigin-panels/js/panels.admin.media.js
|
JavaScript
|
gpl-2.0
| 4,782
|
var searchData=
[
['ldir_5ft',['ldir_t',['../_fat_structs_8h.html#aa1b540ee1eedd1aa9b267d11cba0d9e2',1,'FatStructs.h']]]
];
|
lyusupov/SoftRF
|
software/firmware/source/libraries/SdFat/extras/html/search/typedefs_4.js
|
JavaScript
|
gpl-3.0
| 126
|
// |reftest| skip-if(!xulRuntime.shell)
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/licenses/publicdomain/
a = evalcx('');
a.__proto__ = ''.__proto__;
a.length = 3; // don't assert
reportCompare(0, 0, 'ok');
|
JasonGross/mozjs
|
js/src/tests/js1_8_5/extensions/regress-636818.js
|
JavaScript
|
mpl-2.0
| 249
|
/*
* bootstrap-table - v1.8.0 - 2015-05-22
* https://github.com/wenzhixin/bootstrap-table
* Copyright (c) 2015 zhixin wen
* Licensed MIT License
*/
!function(a){"use strict";a.fn.bootstrapTable.locales["pl-PL"]={formatLoadingMessage:function(){return"Ładowanie, proszę czekać..."},formatRecordsPerPage:function(a){return a+" rekordów na stronę"},formatShowingRows:function(a,b,c){return"Wyświetlanie rekordów od "+a+" do "+b+" z "+c},formatSearch:function(){return"Szukaj"},formatNoMatches:function(){return"Niestety, nic nie znaleziono"},formatRefresh:function(){return"Odśwież"},formatToggle:function(){return"Przełącz"},formatColumns:function(){return"Kolumny"}},a.extend(a.fn.bootstrapTable.defaults,a.fn.bootstrapTable.locales["pl-PL"])}(jQuery);
|
garrypolley/jsdelivr
|
files/bootstrap.table/1.8.0/locale/bootstrap-table-pl-PL.min.js
|
JavaScript
|
mit
| 762
|
#!/usr/bin/env node
var RSVP = require('rsvp');
var spawn = require('child_process').spawn;
var fs = require('fs');
var chalk = require('chalk');
var packages = require('../packages');
var testrunner = require("qunit");
testrunner.setup({log:{errors:true}});
function runBrowserTests(command, args) {
return new RSVP.Promise(function(resolve, reject) {
console.log('Running: ' + command + ' ' + args.join(' '));
var child = spawn(command, args);
var result = {output: [], errors: [], code: null};
child.stdout.on('data', function (data) {
var string = data.toString();
var lines = string.split('\n');
lines.forEach(function(line) {
if (line.indexOf('0 failed.') > -1) {
console.log(chalk.green(line));
} else {
console.log(line);
}
});
result.output.push(string);
});
child.stderr.on('data', function (data) {
var string = data.toString();
result.errors.push(string);
console.error(chalk.red(string));
});
child.on('close', function (code) {
result.code = code;
if (code === 0) {
resolve(result);
} else {
reject(result);
}
});
});
}
function runNodeTests(testDir) {
var nodeTests = fs.readdirSync(testDir),
testPaths = [];
for (var i=0;i<nodeTests.length;i++){
if (nodeTests[i].match(/.*node-test\.js$/)) {
testPaths.push(testDir+nodeTests[i]);
}
}
return new RSVP.Promise(function(resolve, reject){
if (testPaths.length === 0) {
resolve();
return;
}
console.log('----');
console.log("Running: Node test runner against "+testPaths.join(", "));
testrunner.run({
code: "tests/node-context.js",
tests: testPaths
}, function(e, summary){
if (e) {
console.log(chalk.red("Error running node tests"));
return reject(e);
}
var summaryText = "Took "+summary.runtime+"ms to run "+
summary.assertions+" assertions ("+summary.tests+" tests) in node. "+
summary.passed+" passed, "+summary.failed+" failed.";
if (summary.failed > 0) {
console.log(chalk.red(summaryText));
return reject(e);
}
console.log(chalk.green(summaryText));
resolve(e);
});
});
}
// Run tests
var testRuns = RSVP.resolve();
if (process.env.CI && process.env.TEST_BROWSERS) {
testRuns = testRuns.then(function() {
return runBrowserTests('./node_modules/.bin/ember', ['test', '--port', '7000', '--config-file', './testem-sauce.json']);
});
}
if (!process.env.CI) {
testRuns = testRuns.then(function() {
return runBrowserTests('./node_modules/.bin/ember', ['test']);
});
}
if (false /*!process.env.CI || (process.env.CI && process.env.TEST_NODE)*/) {
Object.keys(packages.dependencies).forEach(function(packageName){
if (packages.dependencies[packageName].node) {
var testDir = 'dist/cjs/'+packageName+'-tests/';
testRuns = testRuns.then(function(){
return runNodeTests(testDir);
});
}
});
}
testRuns
.then(function() {
console.log(chalk.green('Passed!'));
process.exit(0);
})
.catch(function(e) {
console.error(chalk.red('Failed!'), e);
process.exit(1);
});
|
simudream/htmlbars
|
bin/run-tests.js
|
JavaScript
|
mit
| 3,256
|
module.exports =
/******/ (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] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.l = 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;
/******/ // identity function for calling harmory imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/ // define getter function for harmory exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ };
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 217);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ function(module, exports) {
module.exports = require("mint-ui/lib/cell");
/***/ },
/***/ 1:
/***/ function(module, exports) {
module.exports = require("mint-ui/lib/cell/style.css");
/***/ },
/***/ 119:
/***/ function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ },
/***/ 134:
/***/ function(module, exports, __webpack_require__) {
var __vue_exports__, __vue_options__
/* styles */
__webpack_require__(119)
/* script */
__vue_exports__ = __webpack_require__(56)
/* template */
var __vue_template__ = __webpack_require__(190)
__vue_options__ = __vue_exports__ = __vue_exports__ || {}
if (
typeof __vue_exports__.default === "object" ||
typeof __vue_exports__.default === "function"
) {
__vue_options__ = __vue_exports__ = __vue_exports__.default
}
if (typeof __vue_options__ === "function") {
__vue_options__ = __vue_options__.options
}
__vue_options__.render = __vue_template__.render
__vue_options__.staticRenderFns = __vue_template__.staticRenderFns
module.exports = __vue_exports__
/***/ },
/***/ 190:
/***/ function(module, exports) {
module.exports={render:function (){with(this) {
return _h('x-cell', {
directives: [{
name: "clickoutside",
rawName: "v-clickoutside",
value: (doCloseActive),
expression: "doCloseActive"
}],
staticClass: "mint-field",
class: [{
'is-textarea': type === 'textarea',
'is-nolabel': !label
}],
attrs: {
"title": label
}
}, [(type === 'textarea') ? _h('textarea', {
directives: [{
name: "model",
rawName: "v-model",
value: (currentValue),
expression: "currentValue"
}],
ref: "textarea",
staticClass: "mint-field-core",
attrs: {
"placeholder": placeholder,
"rows": rows,
"disabled": disabled,
"readonly": readonly
},
domProps: {
"value": _s(currentValue)
},
on: {
"input": function($event) {
if ($event.target.composing) return;
currentValue = $event.target.value
}
}
}) : _h('input', {
ref: "input",
staticClass: "mint-field-core",
attrs: {
"placeholder": placeholder,
"number": type === 'number',
"type": type,
"disabled": disabled,
"readonly": readonly
},
domProps: {
"value": currentValue
},
on: {
"focus": function($event) {
active = true
},
"input": handleInput
}
}), " ", " ", (!disableClear) ? _h('div', {
directives: [{
name: "show",
rawName: "v-show",
value: (currentValue && type !== 'textarea' && active),
expression: "currentValue && type !== 'textarea' && active"
}],
staticClass: "mint-field-clear",
on: {
"click": handleClear
}
}, [_m(0)]) : _e(), " ", (state) ? _h('span', {
staticClass: "mint-field-state",
class: ['is-' + state]
}, [_h('i', {
staticClass: "mintui",
class: ['mintui-field-' + state]
})]) : _e(), " ", _h('div', {
staticClass: "mint-field-other"
}, [_t("default")])])
}},staticRenderFns: [function (){with(this) {
return _h('i', {
staticClass: "mintui mintui-field-error"
})
}}]}
/***/ },
/***/ 217:
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(22);
/***/ },
/***/ 22:
/***/ function(module, exports, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_field_vue__ = __webpack_require__(134);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_field_vue___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__src_field_vue__);
module.exports = __WEBPACK_IMPORTED_MODULE_0__src_field_vue___default.a;
/***/ },
/***/ 56:
/***/ function(module, exports, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_mint_ui_packages_cell_index_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_mint_ui_packages_cell_index_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_mint_ui_packages_cell_index_js__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_mint_ui_src_utils_clickoutside__ = __webpack_require__(8);
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
if (true) {
__webpack_require__(1);
}
/**
* mt-field
* @desc 编辑器,依赖 cell
* @module components/field
*
* @param {string} [type=text] - field 类型,接受 text, textarea 等
* @param {string} [label] - 标签
* @param {string} [rows] - textarea 的 rows
* @param {string} [placeholder] - placeholder
* @param {string} [disabled] - disabled
* @param {string} [readonly] - readonly
* @param {string} [state] - 表单校验状态样式,接受 error, warning, success
*
* @example
* <mt-field v-model="value" label="用户名"></mt-field>
* <mt-field v-model="value" label="密码" placeholder="请输入密码"></mt-field>
* <mt-field v-model="value" label="自我介绍" placeholder="自我介绍" type="textarea" rows="4"></mt-field>
* <mt-field v-model="value" label="邮箱" placeholder="成功状态" state="success"></mt-field>
*/
/* harmony default export */ exports["default"] = {
name: 'mt-field',
data: function data() {
return {
active: false,
currentValue: this.value
};
},
directives: {
Clickoutside: __WEBPACK_IMPORTED_MODULE_1_mint_ui_src_utils_clickoutside__["a" /* default */]
},
props: {
type: {
type: String,
default: 'text'
},
rows: String,
label: String,
placeholder: String,
readonly: Boolean,
disabled: Boolean,
disableClear: Boolean,
state: {
type: String,
default: 'default'
},
value: {},
attr: Object
},
components: { XCell: __WEBPACK_IMPORTED_MODULE_0_mint_ui_packages_cell_index_js___default.a },
methods: {
doCloseActive: function doCloseActive() {
this.active = false;
},
handleInput: function handleInput(evt) {
this.currentValue = evt.target.value;
},
handleClear: function handleClear() {
if (this.disabled || this.readonly) return;
this.currentValue = '';
}
},
watch: {
value: function value(val) {
this.currentValue = val;
},
currentValue: function currentValue(val) {
this.$emit('input', val);
},
attr: {
immediate: true,
handler: function handler(attrs) {
var this$1 = this;
this.$nextTick(function () {
var target = [this$1.$refs.input, this$1.$refs.textarea];
target.forEach(function (el) {
if (!el || !attrs) return;
Object.keys(attrs).map(function (name) { return el.setAttribute(name, attrs[name]); });
});
});
}
}
}
};
/***/ },
/***/ 8:
/***/ function(module, exports, __webpack_require__) {
"use strict";
/**
* v-clickoutside
* @desc 点击元素外面才会触发的事件
* @example
* ```vue
* <div v-element-clickoutside="handleClose">
* ```
*/
var clickoutsideContext = '@@clickoutsideContext';
/* harmony default export */ exports["a"] = {
bind: function bind(el, binding, vnode) {
var documentHandler = function(e) {
if (vnode.context && !el.contains(e.target)) {
vnode.context[el[clickoutsideContext].methodName]();
}
};
el[clickoutsideContext] = {
documentHandler: documentHandler,
methodName: binding.expression,
arg: binding.arg || 'click'
};
document.addEventListener(el[clickoutsideContext].arg, documentHandler);
},
update: function update(el, binding) {
el[clickoutsideContext].methodName = binding.expression;
},
unbind: function unbind(el) {
document.removeEventListener(
el[clickoutsideContext].arg,
el[clickoutsideContext].documentHandler);
},
install: function install(Vue) {
Vue.directive('clickoutside', {
bind: this.bind,
unbind: this.unbind
});
}
};
/***/ }
/******/ });
|
sufuf3/cdnjs
|
ajax/libs/mint-ui/2.0.3/field/index.js
|
JavaScript
|
mit
| 10,462
|
/**
* @class Ext.chart.series.CandleStick
* @extends Ext.chart.series.Cartesian
*
* Creates a candlestick or OHLC Chart.
*
* @example preview
* var chart = new Ext.chart.CartesianChart({
* animation: true,
* store: {
* fields: ['time', 'open', 'high', 'low', 'close'],
* data: [
* {'time':new Date('Jan 1 2010').getTime(), 'open':600, 'high':614, 'low':578, 'close':590},
* {'time':new Date('Jan 2 2010').getTime(), 'open':590, 'high':609, 'low':580, 'close':580},
* {'time':new Date('Jan 3 2010').getTime(), 'open':580, 'high':602, 'low':578, 'close':602},
* {'time':new Date('Jan 4 2010').getTime(), 'open':602, 'high':614, 'low':586, 'close':586},
* {'time':new Date('Jan 5 2010').getTime(), 'open':586, 'high':602, 'low':565, 'close':565}
* ]
* },
* axes: [{
* type: 'numeric',
* position: 'left',
* fields: ['open', 'high', 'low', 'close'],
* title: {
* text: 'Sample Values',
* fontSize: 15
* },
* grid: true,
* minimum: 560,
* maximum: 640
* }, {
* type: 'time',
* position: 'bottom',
* fields: ['time'],
* fromDate: new Date('Dec 31 2009'),
* toDate: new Date('Jan 6 2010'),
* title: {
* text: 'Sample Values',
* fontSize: 15
* },
* style: {
* axisLine: false
* }
* }],
* series: [{
* type: 'candlestick',
* xField: 'time',
* openField: 'open',
* highField: 'high',
* lowField: 'low',
* closeField: 'close',
* style: {
* dropStyle: {
* fill: 'rgb(237, 123, 43)',
* stroke: 'rgb(237, 123, 43)'
* },
* raiseStyle: {
* fill: 'rgb(55, 153, 19)',
* stroke: 'rgb(55, 153, 19)'
* }
* },
* aggregator: {
* strategy: 'time'
* }
* }]
* });
* Ext.Viewport.setLayout('fit');
* Ext.Viewport.add(chart);
*/
Ext.define('Ext.chart.series.CandleStick', {
extend: 'Ext.chart.series.Cartesian',
requires: ['Ext.chart.series.sprite.CandleStick'],
alias: 'series.candlestick',
type: 'candlestick',
seriesType: 'candlestickSeries',
config: {
/**
* @cfg {String} openField
* The store record field name that represents the opening value of the given period.
*/
openField: null,
/**
* @cfg {String} highField
* The store record field name that represents the highest value of the time interval represented.
*/
highField: null,
/**
* @cfg {String} lowField
* The store record field name that represents the lowest value of the time interval represented.
*/
lowField: null,
/**
* @cfg {String} closeField
* The store record field name that represents the closing value of the given period.
*/
closeField: null
},
fieldCategoryY: ['Open', 'High', 'Low', 'Close'],
themeColorCount: function() {
return 2;
}
});
|
applifireAlgo/ZenClubApp
|
zenws/src/main/webapp/ext/packages/sencha-charts/src/chart/series/CandleStick.js
|
JavaScript
|
gpl-3.0
| 3,493
|
loadIonicon('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M213.573 256h84.846l-42.427-89.356z"/><path d="M255.981 32L32 112l46.12 272L256 480l177.75-96L480 112 255.981 32zM344 352l-26.589-56H194.584L168 352h-40L256 72l128 280h-40z"/></svg>','logo-angular');
|
matteobortolazzo/matteobortolazzo.github.io
|
build/app/svg/logo-angular.js
|
JavaScript
|
mit
| 283
|
describe('webKitDataTransfer', function () {
/**
* @type {Flow}
*/
var flow;
beforeEach(function () {
flow = new Flow();
});
var getWebKitFile = function (filename) {
return {
isFile: true,
isDirectory: false,
fullPath: '/home/user/foo/' + filename,
file: function (callback) {
callback({
relativePath: '/foo/' + filename
});
}
};
};
it('should return empty array', function() {
var event = {
dataTransfer: {
items: [
{
webkitGetAsEntry: function () {
return false;
}
}
]
}
};
spyOn(flow, 'addFiles');
flow.webkitReadDataTransfer(event);
expect(flow.addFiles).toHaveBeenCalledWith([], event);
});
it('should return one file', function() {
var event = {
dataTransfer: {
items: [
{
webkitGetAsEntry: function () {
return getWebKitFile('111.txt');
},
getAsFile: function () {
return {
relativePath: '/foo/111.txt'
};
}
}
]
}
};
spyOn(flow, 'addFiles');
flow.webkitReadDataTransfer(event);
expect(flow.addFiles).toHaveBeenCalledWith(
[{relativePath: 'home/user/foo/111.txt'}],
event
);
});
it('should return one file from subdirectory', function() {
var event = {
dataTransfer: {
items: [
{
webkitGetAsEntry: function () {
return {
isFile: false,
isDirectory: true,
fullPath: '/home/user/foo/',
createReader: function () {
var entries = [
getWebKitFile('111.txt')
];
return {
readEntries: function (success, error) {
var entry = entries.shift();
if (entry) {
return success([entry]);
} else {
return success([]);
}
}
};
}
};
}
}
]
}
};
spyOn(flow, 'addFiles');
flow.webkitReadDataTransfer(event);
expect(flow.addFiles).toHaveBeenCalledWith(
[{relativePath: 'home/user/foo/111.txt'}],
event
);
});
it('should return two files from subdirectory', function() {
var event = {
dataTransfer: {
items: [
{
webkitGetAsEntry: function () {
return {
isFile: false,
isDirectory: true,
fullPath: '/home/user/foo/',
createReader: function () {
var entries = [
getWebKitFile('111.txt'),
getWebKitFile('222.txt')
];
return {
readEntries: function (success, error) {
var entry = entries.shift();
if (entry) {
return success([entry]);
} else {
return success([]);
}
}
};
}
};
}
}
]
}
};
spyOn(flow, 'addFiles');
flow.webkitReadDataTransfer(event);
expect(flow.addFiles).toHaveBeenCalledWith(
[
{relativePath: 'home/user/foo/111.txt'},
{relativePath: 'home/user/foo/222.txt'}
],
event
);
});
});
|
SuberFu/flow.js
|
test/webKitDataTransferSpec.js
|
JavaScript
|
mit
| 3,687
|
import {q} from './dep.js';
export var p = 'module';
|
bjlxj2008/traceur-compiler
|
test/unit/node/resources/compile-dir/file.js
|
JavaScript
|
apache-2.0
| 53
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @nolint
* @format
*/
declare class Position {
coords: Coordinates;
timestamp: number;
mocked: boolean;
}
|
pandiaraj44/react-native
|
flow/Position.js
|
JavaScript
|
bsd-3-clause
| 321
|
/**
* Test dependencies
*/
const test = require("tape")
const utils = require("./utils")
const cssnext = require("..")
const cssnextStandalone = require("../cssnext")
/**
* Features tests
*/
const toSlug = require("to-slug-case")
const testFeature = function(
t,
feature,
cssnextInstance,
version,
source,
input,
expected
) {
const options = {from: source, sourcemap: false, features: {}}
// disable all features
Object.keys(cssnextInstance.features).forEach(function(key) {
options.features[key] = false
})
const css = cssnextInstance(input, options)
t.notEqual(
css,
expected,
version + ": should not add " + feature + " support if disabled"
)
t.equal(
css,
input,
version + ": should not modify input if " + feature + " is disabled"
)
// enable only the one we want to test...
options.features[feature] = true
// ...except "url" because we want to validate its behaviour when integrated
// with "import"
if (feature === "url") {
options.features.import = true
}
t.equal(
cssnextInstance(input, options).trim(),
expected.trim(),
version + ": should add " + feature + " support"
)
}
Object.keys(cssnext.features).forEach(function(name) {
const slug = toSlug(name)
const source = utils.fixturePath("features/" + slug)
const input = utils.readFixture("features/" + slug)
const expected = utils.readFixture("features/" + slug + ".expected")
test(slug, function(t) {
testFeature(t, name, cssnext, "node.js", source, input, expected)
// we do not support @import or url rewriting in the browser
if (name === "import" || name === "url") {
t.end()
return
}
testFeature(t, name, cssnextStandalone, "browser", source, input, expected)
t.end()
})
})
|
jedmao/cssnext
|
src/__tests__/option.features.js
|
JavaScript
|
mit
| 1,798
|
module.exports = function (config) {
config.set({
basePath: '../',
files: [
'node_modules/angular/angular.js',
'node_modules/angular-animate/angular-animate.js',
'node_modules/angular-aria/angular-aria.js',
'node_modules/angular-mocks/angular-mocks.js',
'node_modules/angular-material/angular-material.js',
'app/src/users/Users.js',
'app/src/users/UserService.js',
'app/src/users/UserController.js',
'test/unit/**/*.js'
],
logLevel: config.LOG_ERROR,
port: 9876,
reporters: ['progress'],
colors: true,
autoWatch : false,
singleRun : true,
// For TDD mode
//autoWatch : true,
//singleRun : false,
frameworks: ['jasmine'],
browsers: ['Chrome'],
plugins: [
'karma-chrome-launcher',
'karma-jasmine'
]
});
};
|
pbourdu/qrea-compta-app
|
test/karma.conf.js
|
JavaScript
|
mit
| 848
|
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
jQuery(function($) {
//console.log("Ready Loaded");
// Remove Preload so that transitions work after page loads
$("body").removeClass("preload");
Mousetrap.bind('?', function() {
//console.log("Question Mark Pressed");
$('#keyboard-shortcuts').modal("show");
});
// Table Column Highlgihting
// --------------------------------------------------------
$(".table-highlighting").delegate('td','mouseover mouseleave', function(e) {
var whichCol = $(this).index();
if (e.type == 'mouseover') {
$(this).parent().addClass("is-active");
$(this).parent().parent().siblings("colgroup").eq(whichCol).addClass("is-active");
}
else {
$(this).parent().removeClass("is-active");
$(this).parent().parent().siblings("colgroup").eq(whichCol).removeClass("is-active");
}
});
// Open Lists
// --------------------------------------------------------
$(".collapse-list").delegate('li','click', function(e) {
//console.log("Clicked");
$(this).toggleClass("is-open");
});
// Handler for .ready() called.
});
|
opengovfoundation/marylandcode
|
htdocs/themes/StateDecoded2013/static/js/ready.js
|
JavaScript
|
gpl-3.0
| 1,778
|
if(!window.calendar_languages) {
window.calendar_languages = {};
}
window.calendar_languages['de'] = {
error_noview: 'Kalender: Ansicht {0} nicht gefunden',
error_dateformat: 'Kalender: Falsches Datumsformat {0}. Sollte entweder "now" oder "yyyy-mm-dd" sein',
error_loadurl: 'Kalender: Event-URL nicht gesetzt.',
error_where: 'Kalender: Falsche Navigationsrichtung {0}. Nur "next", "prev" oder "today" sind erlaubt',
error_timedevide: 'Kalender: Parameter für die Zeiteinteilung muss ein Teiler von 60 sein. Beispielsweise 10, 15, 30',
no_events_in_day: 'Keine Ereignisse an diesem Tag.',
title_year: '{0}',
title_month: '{0} {1}',
title_week: '{0}. Kalenderwoche {1}',
title_day: '{0}, der {1}. {2} {3}',
week: 'KW {0}',
all_day: 'Ganztägig',
time: 'Zeit',
events: 'Ereignisse',
before_time: 'Endet vor Zeitspanne',
after_time: 'Beginnt nach Zeitspanne',
m0: 'Januar',
m1: 'Februar',
m2: 'März',
m3: 'April',
m4: 'Mai',
m5: 'Juni',
m6: 'Juli',
m7: 'August',
m8: 'September',
m9: 'Oktober',
m10: 'November',
m11: 'Dezember',
ms0: 'Jan',
ms1: 'Feb',
ms2: 'Mär',
ms3: 'Apr',
ms4: 'Mai',
ms5: 'Jun',
ms6: 'Jul',
ms7: 'Aug',
ms8: 'Sep',
ms9: 'Okt',
ms10: 'Nov',
ms11: 'Dez',
d0: 'Sonntag',
d1: 'Montag',
d2: 'Dienstag',
d3: 'Mittwoch',
d4: 'Donnerstag',
d5: 'Freitag',
d6: 'Samstag',
first_day: 1,
holidays: {
'01-01': 'Neujahr',
'easter-2': 'Karfreitag',
'easter+1': 'Ostermontag',
'01-05': 'Erster Mai',
'easter+39': 'Himmelfahrt',
'easter+49': 'Pfingstsonntag',
'easter+50': 'Pfingstmontag',
'03-10': 'Tag der Deutschen Einheit',
'25-12': 'Erster Weihnachtsfeiertag',
'26-12': 'Zweiter Weihnachtsfeiertag',
}
};
|
alexhuang888/xibo-cms
|
web/theme/default/libraries/calendar/js/language/de.js
|
JavaScript
|
agpl-3.0
| 1,776
|
tinyMCE.addI18n('no.emotions_dlg',{cry:"Griner",cool:"Cool",desc:"Hum\u00f8rfjes",title:"Sett inn hum\u00f8rfjes",yell:"Skrik",wink:"Blunke",undecided:"Skeptisk","tongue_out":"Rekke tunge",surprised:"Overrasket",smile:"Smil",sealed:"Lukket","money_mouth":"Penger i munnen",laughing:"Ler",kiss:"Kyss",innocent:"Uskyldig",frown:"Skummer","foot_in_mouth":"Fot i munnen",embarassed:"Flau",usage:"Use left and right arrows to navigate."});
|
codepython/CollectorCity-Market-Place
|
stores/media_out_s3/js/tiny_mce/plugins/emotions/langs/no_dlg.js
|
JavaScript
|
apache-2.0
| 434
|
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-50.js
* @description Object.getOwnPropertyDescriptor returns data desc for functions on built-ins (Array.prototype.splice)
*/
function testcase() {
var desc = Object.getOwnPropertyDescriptor(Array.prototype, "splice");
if (desc.value === Array.prototype.splice &&
desc.writable === true &&
desc.enumerable === false &&
desc.configurable === true) {
return true;
}
}
runTestCase(testcase);
|
Oceanswave/NiL.JS
|
Tests/tests/sputnik/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-50.js
|
JavaScript
|
bsd-3-clause
| 538
|
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-5-21.js
* @description Array.prototype.some - the global object can be used as thisArg
*/
function testcase() {
function callbackfn(val, idx, obj) {
return this === fnGlobalObject();
}
return [11].some(callbackfn, fnGlobalObject());
}
runTestCase(testcase);
|
Oceanswave/NiL.JS
|
Tests/tests/sputnik/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-5-21.js
|
JavaScript
|
bsd-3-clause
| 421
|
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.9/15.9.1/15.9.1.15/15.9.1.15-1.js
* @description Date Time String Format - specified default values will be set for all optional fields(MM, DD, mm, ss and time zone) when they are absent
*/
function testcase() {
var result = false;
var expectedDateTimeStr = "1970-01-01T00:00:00.000Z";
var dateObj = new Date("1970");
var dateStr = dateObj.toISOString();
result = dateStr === expectedDateTimeStr;
return result;
}
runTestCase(testcase);
|
Oceanswave/NiL.JS
|
Tests/tests/sputnik/ch15/15.9/15.9.1/15.9.1.15/15.9.1.15-1.js
|
JavaScript
|
bsd-3-clause
| 580
|
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['quill'], factory)
} else if (typeof exports === 'object') {
module.exports = factory(require('quill'))
} else {
root.Requester = factory(root.Quill)
}
}(this, function (Quill) {
'use strict'
var app
// declare ngQuill module
app = angular.module('ngQuill', [])
app.provider('ngQuillConfig', function () {
var config = {
modules: {
toolbar: [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
[{ 'header': 1 }, { 'header': 2 }], // custom button values
[{ 'list': 'ordered' }, { 'list': 'bullet' }],
[{ 'script': 'sub' }, { 'script': 'super' }], // superscript/subscript
[{ 'indent': '-1' }, { 'indent': '+1' }], // outdent/indent
[{ 'direction': 'rtl' }], // text direction
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'font': [] }],
[{ 'align': [] }],
['clean'], // remove formatting button
['link', 'image', 'video'] // link and image, video
]
},
theme: 'snow',
placeholder: 'Insert text here ...',
readOnly: false,
bounds: document.body
}
this.set = function (customConf) {
customConf = customConf || {}
if (customConf.modules) {
config.modules = customConf.modules
}
if (customConf.theme) {
config.theme = customConf.theme
}
if (customConf.placeholder) {
config.placeholder = customConf.placeholder
}
if (customConf.bounds) {
config.bounds = customConf.bounds
}
if (customConf.readOnly) {
config.readOnly = customConf.readOnly
}
if (customConf.formats) {
config.formats = customConf.formats
}
}
this.$get = function () {
return config
}
})
app.component('ngQuillEditor', {
bindings: {
'modules': '<modules',
'theme': '@?',
'readOnly': '<?',
'formats': '<?',
'placeholder': '@?',
'bounds': '<?',
'onEditorCreated': '&?',
'onContentChanged': '&?',
'onSelectionChanged': '&?',
'ngModel': '<',
'maxLength': '<',
'minLength': '<'
},
require: {
ngModelCtrl: 'ngModel'
},
transclude: {
'toolbar': '?ngQuillToolbar'
},
template: '<div class="ng-hide" ng-show="$ctrl.ready"><ng-transclude ng-transclude-slot="toolbar"></ng-transclude></div>',
controller: ['$scope', '$element', '$timeout', '$transclude', 'ngQuillConfig', function ($scope, $element, $timeout, $transclude, ngQuillConfig) {
var config = {}
var content
var editorElem
var modelChanged = false
var editorChanged = false
var editor
this.validate = function (text) {
if (this.maxLength) {
if (text.length > this.maxLength + 1) {
this.ngModelCtrl.$setValidity('maxlength', false)
} else {
this.ngModelCtrl.$setValidity('maxlength', true)
}
}
if (this.minLength > 1) {
// validate only if text.length > 1
if (text.length <= this.minLength && text.length > 1) {
this.ngModelCtrl.$setValidity('minlength', false)
} else {
this.ngModelCtrl.$setValidity('minlength', true)
}
}
}
this.$onChanges = function (changes) {
if (changes.ngModel && changes.ngModel.currentValue !== changes.ngModel.previousValue) {
content = changes.ngModel.currentValue
if (editor && !editorChanged) {
modelChanged = true
if (content) {
editor.pasteHTML(content)
} else {
editor.setText('')
}
}
editorChanged = false
}
if (editor && changes.readOnly) {
editor.enable(!changes.readOnly.currentValue)
}
}
this.$onInit = function () {
config = {
theme: this.theme || ngQuillConfig.theme,
readOnly: this.readOnly || ngQuillConfig.readOnly,
modules: this.modules || ngQuillConfig.modules,
formats: this.formats || ngQuillConfig.formats,
placeholder: this.placeholder || ngQuillConfig.placeholder,
bounds: this.bounds || ngQuillConfig.bounds
}
}
this.$postLink = function () {
// create quill instance after dom is rendered
$timeout(function () {
this._initEditor(editorElem)
}.bind(this), 0)
}
this._initEditor = function (editorElem) {
var $editorElem = angular.element('<div></div>')
var container = $element.children()
editorElem = $editorElem[0]
// set toolbar to custom one
if ($transclude.isSlotFilled('toolbar')) {
config.modules.toolbar = container.find('ng-quill-toolbar').children()[0]
}
container.append($editorElem)
editor = new Quill(editorElem, config)
this.ready = true
// mark model as touched if editor lost focus
editor.on('selection-change', function (range, oldRange, source) {
if (this.onSelectionChanged) {
this.onSelectionChanged({
editor: editor,
oldRange: oldRange,
range: range,
source: source
})
}
if (range) {
return
}
$scope.$applyAsync(function () {
this.ngModelCtrl.$setTouched()
}.bind(this))
}.bind(this))
// update model if text changes
editor.on('text-change', function (delta, oldDelta, source) {
var html = editorElem.children[0].innerHTML
var text = editor.getText()
if (html === '<p><br></p>') {
html = null
}
this.validate(text)
if (!modelChanged) {
$scope.$applyAsync(function () {
editorChanged = true
this.ngModelCtrl.$setViewValue(html)
if (this.onContentChanged) {
this.onContentChanged({
editor: editor,
html: html,
text: text,
delta: delta,
oldDelta: oldDelta,
source: source
})
}
}.bind(this))
}
modelChanged = false
}.bind(this))
// set initial content
if (content) {
modelChanged = true
var contents = editor.clipboard.convert(content)
editor.setContents(contents)
editor.history.clear()
}
// provide event to get informed when editor is created -> pass editor object.
if (this.onEditorCreated) {
this.onEditorCreated({editor: editor})
}
}
}]
})
}))
|
dakshshah96/cdnjs
|
ajax/libs/ng-quill/3.2.1/ng-quill.js
|
JavaScript
|
mit
| 7,532
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Injectable } from '@angular/core';
import { createCheckBindingField, createCheckBindingStmt } from './compiler_util/binding_util';
import { convertPropertyBinding } from './compiler_util/expression_converter';
import { writeToRenderer } from './compiler_util/render_util';
import { CompilerConfig } from './config';
import { Parser } from './expression_parser/parser';
import { Identifiers, resolveIdentifier } from './identifiers';
import { DEFAULT_INTERPOLATION_CONFIG } from './ml_parser/interpolation_config';
import { createClassStmt } from './output/class_builder';
import * as o from './output/output_ast';
import { ParseErrorLevel, ParseLocation, ParseSourceFile, ParseSourceSpan } from './parse_util';
import { Console, LifecycleHooks } from './private_import_core';
import { ElementSchemaRegistry } from './schema/element_schema_registry';
import { BindingParser } from './template_parser/binding_parser';
export var DirectiveWrapperCompileResult = (function () {
function DirectiveWrapperCompileResult(statements, dirWrapperClassVar) {
this.statements = statements;
this.dirWrapperClassVar = dirWrapperClassVar;
}
return DirectiveWrapperCompileResult;
}());
var CONTEXT_FIELD_NAME = 'context';
var CHANGES_FIELD_NAME = 'changes';
var CHANGED_FIELD_NAME = 'changed';
var CURR_VALUE_VAR = o.variable('currValue');
var THROW_ON_CHANGE_VAR = o.variable('throwOnChange');
var FORCE_UPDATE_VAR = o.variable('forceUpdate');
var VIEW_VAR = o.variable('view');
var RENDER_EL_VAR = o.variable('el');
var RESET_CHANGES_STMT = o.THIS_EXPR.prop(CHANGES_FIELD_NAME).set(o.literalMap([])).toStmt();
/**
* We generate directive wrappers to prevent code bloat when a directive is used.
* A directive wrapper encapsulates
* the dirty checking for `@Input`, the handling of `@HostListener` / `@HostBinding`
* and calling the lifecyclehooks `ngOnInit`, `ngOnChanges`, `ngDoCheck`.
*
* So far, only `@Input` and the lifecycle hooks have been implemented.
*/
export var DirectiveWrapperCompiler = (function () {
function DirectiveWrapperCompiler(compilerConfig, _exprParser, _schemaRegistry, _console) {
this.compilerConfig = compilerConfig;
this._exprParser = _exprParser;
this._schemaRegistry = _schemaRegistry;
this._console = _console;
}
DirectiveWrapperCompiler.dirWrapperClassName = function (id) { return "Wrapper_" + id.name; };
DirectiveWrapperCompiler.prototype.compile = function (dirMeta) {
var builder = new DirectiveWrapperBuilder(this.compilerConfig, dirMeta);
Object.keys(dirMeta.inputs).forEach(function (inputFieldName) {
addCheckInputMethod(inputFieldName, builder);
});
addDetectChangesInInputPropsMethod(builder);
var hostParseResult = parseHostBindings(dirMeta, this._exprParser, this._schemaRegistry);
reportParseErrors(hostParseResult.errors, this._console);
// host properties are change detected by the DirectiveWrappers,
// except for the animation properties as they need close integration with animation events
// and DirectiveWrappers don't support
// event listeners right now.
addDetectChangesInHostPropsMethod(hostParseResult.hostProps.filter(function (hostProp) { return !hostProp.isAnimation; }), builder);
// TODO(tbosch): implement hostListeners via DirectiveWrapper as well!
var classStmt = builder.build();
return new DirectiveWrapperCompileResult([classStmt], classStmt.name);
};
DirectiveWrapperCompiler.decorators = [
{ type: Injectable },
];
/** @nocollapse */
DirectiveWrapperCompiler.ctorParameters = [
{ type: CompilerConfig, },
{ type: Parser, },
{ type: ElementSchemaRegistry, },
{ type: Console, },
];
return DirectiveWrapperCompiler;
}());
var DirectiveWrapperBuilder = (function () {
function DirectiveWrapperBuilder(compilerConfig, dirMeta) {
this.compilerConfig = compilerConfig;
this.dirMeta = dirMeta;
this.fields = [];
this.getters = [];
this.methods = [];
this.ctorStmts = [];
var dirLifecycleHooks = dirMeta.type.lifecycleHooks;
this.genChanges = dirLifecycleHooks.indexOf(LifecycleHooks.OnChanges) !== -1 ||
this.compilerConfig.logBindingUpdate;
this.ngOnChanges = dirLifecycleHooks.indexOf(LifecycleHooks.OnChanges) !== -1;
this.ngOnInit = dirLifecycleHooks.indexOf(LifecycleHooks.OnInit) !== -1;
this.ngDoCheck = dirLifecycleHooks.indexOf(LifecycleHooks.DoCheck) !== -1;
}
DirectiveWrapperBuilder.prototype.build = function () {
var dirDepParamNames = [];
for (var i = 0; i < this.dirMeta.type.diDeps.length; i++) {
dirDepParamNames.push("p" + i);
}
var fields = [
new o.ClassField(CONTEXT_FIELD_NAME, o.importType(this.dirMeta.type)),
new o.ClassField(CHANGED_FIELD_NAME, o.BOOL_TYPE),
];
var ctorStmts = [o.THIS_EXPR.prop(CHANGED_FIELD_NAME).set(o.literal(false)).toStmt()];
if (this.genChanges) {
fields.push(new o.ClassField(CHANGES_FIELD_NAME, new o.MapType(o.DYNAMIC_TYPE)));
ctorStmts.push(RESET_CHANGES_STMT);
}
ctorStmts.push(o.THIS_EXPR.prop(CONTEXT_FIELD_NAME)
.set(o.importExpr(this.dirMeta.type)
.instantiate(dirDepParamNames.map(function (paramName) { return o.variable(paramName); })))
.toStmt());
return createClassStmt({
name: DirectiveWrapperCompiler.dirWrapperClassName(this.dirMeta.type),
ctorParams: dirDepParamNames.map(function (paramName) { return new o.FnParam(paramName, o.DYNAMIC_TYPE); }),
builders: [{ fields: fields, ctorStmts: ctorStmts }, this]
});
};
return DirectiveWrapperBuilder;
}());
function addDetectChangesInInputPropsMethod(builder) {
var changedVar = o.variable('changed');
var stmts = [
changedVar.set(o.THIS_EXPR.prop(CHANGED_FIELD_NAME)).toDeclStmt(),
o.THIS_EXPR.prop(CHANGED_FIELD_NAME).set(o.literal(false)).toStmt(),
];
var lifecycleStmts = [];
if (builder.genChanges) {
var onChangesStmts = [];
if (builder.ngOnChanges) {
onChangesStmts.push(o.THIS_EXPR.prop(CONTEXT_FIELD_NAME)
.callMethod('ngOnChanges', [o.THIS_EXPR.prop(CHANGES_FIELD_NAME)])
.toStmt());
}
if (builder.compilerConfig.logBindingUpdate) {
onChangesStmts.push(o.importExpr(resolveIdentifier(Identifiers.setBindingDebugInfoForChanges))
.callFn([VIEW_VAR.prop('renderer'), RENDER_EL_VAR, o.THIS_EXPR.prop(CHANGES_FIELD_NAME)])
.toStmt());
}
onChangesStmts.push(RESET_CHANGES_STMT);
lifecycleStmts.push(new o.IfStmt(changedVar, onChangesStmts));
}
if (builder.ngOnInit) {
lifecycleStmts.push(new o.IfStmt(VIEW_VAR.prop('numberOfChecks').identical(new o.LiteralExpr(0)), [o.THIS_EXPR.prop(CONTEXT_FIELD_NAME).callMethod('ngOnInit', []).toStmt()]));
}
if (builder.ngDoCheck) {
lifecycleStmts.push(o.THIS_EXPR.prop(CONTEXT_FIELD_NAME).callMethod('ngDoCheck', []).toStmt());
}
if (lifecycleStmts.length > 0) {
stmts.push(new o.IfStmt(o.not(THROW_ON_CHANGE_VAR), lifecycleStmts));
}
stmts.push(new o.ReturnStatement(changedVar));
builder.methods.push(new o.ClassMethod('detectChangesInInputProps', [
new o.FnParam(VIEW_VAR.name, o.importType(resolveIdentifier(Identifiers.AppView), [o.DYNAMIC_TYPE])),
new o.FnParam(RENDER_EL_VAR.name, o.DYNAMIC_TYPE),
new o.FnParam(THROW_ON_CHANGE_VAR.name, o.BOOL_TYPE),
], stmts, o.BOOL_TYPE));
}
function addCheckInputMethod(input, builder) {
var field = createCheckBindingField(builder);
var onChangeStatements = [
o.THIS_EXPR.prop(CHANGED_FIELD_NAME).set(o.literal(true)).toStmt(),
o.THIS_EXPR.prop(CONTEXT_FIELD_NAME).prop(input).set(CURR_VALUE_VAR).toStmt(),
];
if (builder.genChanges) {
onChangeStatements.push(o.THIS_EXPR.prop(CHANGES_FIELD_NAME)
.key(o.literal(input))
.set(o.importExpr(resolveIdentifier(Identifiers.SimpleChange))
.instantiate([field.expression, CURR_VALUE_VAR]))
.toStmt());
}
var methodBody = createCheckBindingStmt({ currValExpr: CURR_VALUE_VAR, forceUpdate: FORCE_UPDATE_VAR, stmts: [] }, field.expression, THROW_ON_CHANGE_VAR, onChangeStatements);
builder.methods.push(new o.ClassMethod("check_" + input, [
new o.FnParam(CURR_VALUE_VAR.name, o.DYNAMIC_TYPE),
new o.FnParam(THROW_ON_CHANGE_VAR.name, o.BOOL_TYPE),
new o.FnParam(FORCE_UPDATE_VAR.name, o.BOOL_TYPE),
], methodBody));
}
function addDetectChangesInHostPropsMethod(hostProps, builder) {
var stmts = [];
var methodParams = [
new o.FnParam(VIEW_VAR.name, o.importType(resolveIdentifier(Identifiers.AppView), [o.DYNAMIC_TYPE])),
new o.FnParam(RENDER_EL_VAR.name, o.DYNAMIC_TYPE),
new o.FnParam(THROW_ON_CHANGE_VAR.name, o.BOOL_TYPE),
];
hostProps.forEach(function (hostProp) {
var field = createCheckBindingField(builder);
var evalResult = convertPropertyBinding(builder, null, o.THIS_EXPR.prop(CONTEXT_FIELD_NAME), hostProp.value, field.bindingId);
if (!evalResult) {
return;
}
var securityContextExpr;
if (hostProp.needsRuntimeSecurityContext) {
securityContextExpr = o.variable("secCtx_" + methodParams.length);
methodParams.push(new o.FnParam(securityContextExpr.name, o.importType(resolveIdentifier(Identifiers.SecurityContext))));
}
stmts.push.apply(stmts, createCheckBindingStmt(evalResult, field.expression, THROW_ON_CHANGE_VAR, writeToRenderer(VIEW_VAR, hostProp, RENDER_EL_VAR, evalResult.currValExpr, builder.compilerConfig.logBindingUpdate, securityContextExpr)));
});
builder.methods.push(new o.ClassMethod('detectChangesInHostProps', methodParams, stmts));
}
var ParseResult = (function () {
function ParseResult(hostProps, hostListeners, errors) {
this.hostProps = hostProps;
this.hostListeners = hostListeners;
this.errors = errors;
}
return ParseResult;
}());
function parseHostBindings(dirMeta, exprParser, schemaRegistry) {
var errors = [];
var parser = new BindingParser(exprParser, DEFAULT_INTERPOLATION_CONFIG, schemaRegistry, [], errors);
var sourceFileName = dirMeta.type.moduleUrl ?
"in Directive " + dirMeta.type.name + " in " + dirMeta.type.moduleUrl :
"in Directive " + dirMeta.type.name;
var sourceFile = new ParseSourceFile('', sourceFileName);
var sourceSpan = new ParseSourceSpan(new ParseLocation(sourceFile, null, null, null), new ParseLocation(sourceFile, null, null, null));
var parsedHostProps = parser.createDirectiveHostPropertyAsts(dirMeta, sourceSpan);
var parsedHostListeners = parser.createDirectiveHostEventAsts(dirMeta, sourceSpan);
return new ParseResult(parsedHostProps, parsedHostListeners, errors);
}
function reportParseErrors(parseErrors, console) {
var warnings = parseErrors.filter(function (error) { return error.level === ParseErrorLevel.WARNING; });
var errors = parseErrors.filter(function (error) { return error.level === ParseErrorLevel.FATAL; });
if (warnings.length > 0) {
this._console.warn("Directive parse warnings:\n" + warnings.join('\n'));
}
if (errors.length > 0) {
throw new Error("Directive parse errors:\n" + errors.join('\n'));
}
}
//# sourceMappingURL=directive_wrapper_compiler.js.map
|
ice3x2/Clreball
|
web/lib/@angular/compiler/src/directive_wrapper_compiler.js
|
JavaScript
|
gpl-3.0
| 11,939
|
/**
* @fileoverview Rule to flag non-camelcased identifiers
* @author Nicholas C. Zakas
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "enforce camelcase naming convention",
category: "Stylistic Issues",
recommended: false
},
schema: [
{
type: "object",
properties: {
properties: {
enum: ["always", "never"]
}
},
additionalProperties: false
}
]
},
create(context) {
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
// contains reported nodes to avoid reporting twice on destructuring with shorthand notation
const reported = [];
const ALLOWED_PARENT_TYPES = new Set(["CallExpression", "NewExpression"]);
/**
* Checks if a string contains an underscore and isn't all upper-case
* @param {string} name The string to check.
* @returns {boolean} if the string is underscored
* @private
*/
function isUnderscored(name) {
// if there's an underscore, it might be A_CONSTANT, which is okay
return name.indexOf("_") > -1 && name !== name.toUpperCase();
}
/**
* Reports an AST node as a rule violation.
* @param {ASTNode} node The node to report.
* @returns {void}
* @private
*/
function report(node) {
if (reported.indexOf(node) < 0) {
reported.push(node);
context.report({ node, message: "Identifier '{{name}}' is not in camel case.", data: { name: node.name } });
}
}
const options = context.options[0] || {};
let properties = options.properties || "";
if (properties !== "always" && properties !== "never") {
properties = "always";
}
return {
Identifier(node) {
/*
* Leading and trailing underscores are commonly used to flag
* private/protected identifiers, strip them
*/
const name = node.name.replace(/^_+|_+$/g, ""),
effectiveParent = (node.parent.type === "MemberExpression") ? node.parent.parent : node.parent;
// MemberExpressions get special rules
if (node.parent.type === "MemberExpression") {
// "never" check properties
if (properties === "never") {
return;
}
// Always report underscored object names
if (node.parent.object.type === "Identifier" &&
node.parent.object.name === node.name &&
isUnderscored(name)) {
report(node);
// Report AssignmentExpressions only if they are the left side of the assignment
} else if (effectiveParent.type === "AssignmentExpression" &&
isUnderscored(name) &&
(effectiveParent.right.type !== "MemberExpression" ||
effectiveParent.left.type === "MemberExpression" &&
effectiveParent.left.property.name === node.name)) {
report(node);
}
// Properties have their own rules
} else if (node.parent.type === "Property") {
// "never" check properties
if (properties === "never") {
return;
}
if (node.parent.parent && node.parent.parent.type === "ObjectPattern" &&
node.parent.key === node && node.parent.value !== node) {
return;
}
if (isUnderscored(name) && !ALLOWED_PARENT_TYPES.has(effectiveParent.type)) {
report(node);
}
// Check if it's an import specifier
} else if (["ImportSpecifier", "ImportNamespaceSpecifier", "ImportDefaultSpecifier"].indexOf(node.parent.type) >= 0) {
// Report only if the local imported identifier is underscored
if (node.parent.local && node.parent.local.name === node.name && isUnderscored(name)) {
report(node);
}
// Report anything that is underscored that isn't a CallExpression
} else if (isUnderscored(name) && !ALLOWED_PARENT_TYPES.has(effectiveParent.type)) {
report(node);
}
}
};
}
};
|
hellokidder/js-studying
|
微信小程序/wxtest/node_modules/eslint/lib/rules/camelcase.js
|
JavaScript
|
mit
| 5,183
|
// DATA_TEMPLATE: empty_table
oTest.fnStart( "oSearch" );
$(document).ready( function () {
/* Check the default */
var oTable = $('#example').dataTable( {
"sAjaxSource": "../../../examples/examples_support/json_source.txt"
} );
var oSettings = oTable.fnSettings();
oTest.fnWaitTest(
"Default values should be blank",
null,
function () {
var bReturn = oSettings.oPreviousSearch.sSearch == "" &&
oSettings.oPreviousSearch.bEscapeRegex;
return bReturn;
}
);
/* This test might be considered iffy since the full object isn't given, but it's reasonable to
* expect DataTables to cope with this. It should just assumine regex false
*/
oTest.fnWaitTest(
"Search term only in object",
function () {
oSession.fnRestore();
oTable = $('#example').dataTable( {
"sAjaxSource": "../../../examples/examples_support/json_source.txt",
"oSearch": {
"sSearch": "Mozilla"
}
} );
},
function () { return $('#example tbody tr:eq(0) td:eq(0)').html() == "Gecko"; }
);
oTest.fnWaitTest(
"New search will kill old one",
function () {
oTable.fnFilter("Opera");
},
function () { return $('#example tbody tr:eq(0) td:eq(0)').html() == "Presto"; }
);
oTest.fnWaitTest(
"Search plain text term and escape regex true",
function () {
oSession.fnRestore();
$('#example').dataTable( {
"sAjaxSource": "../../../examples/examples_support/json_source.txt",
"oSearch": {
"sSearch": "DS",
"bEscapeRegex": true
}
} );
},
function () { return $('#example tbody tr:eq(0) td:eq(1)').html() == "Nintendo DS browser"; }
);
oTest.fnWaitTest(
"Search plain text term and escape regex false",
function () {
oSession.fnRestore();
$('#example').dataTable( {
"sAjaxSource": "../../../examples/examples_support/json_source.txt",
"oSearch": {
"sSearch": "Opera",
"bEscapeRegex": false
}
} );
},
function () { return $('#example tbody tr:eq(0) td:eq(0)').html() == "Presto"; }
);
oTest.fnWaitTest(
"Search regex text term and escape regex true",
function () {
oSession.fnRestore();
$('#example').dataTable( {
"sAjaxSource": "../../../examples/examples_support/json_source.txt",
"oSearch": {
"sSearch": "1.*",
"bEscapeRegex": true
}
} );
},
function () { return $('#example tbody tr:eq(0) td:eq(0)').html() == "No matching records found"; }
);
oTest.fnWaitTest(
"Search regex text term and escape regex false",
function () {
oSession.fnRestore();
$('#example').dataTable( {
"sAjaxSource": "../../../examples/examples_support/json_source.txt",
"oSearch": {
"sSearch": "1.*",
"bEscapeRegex": false
}
} );
},
function () { return $('#example tbody tr:eq(0) td:eq(0)').html() == "Gecko"; }
);
oTest.fnComplete();
} );
|
yesudeep/chickoojs
|
src/jquery/dataTables/1.6/media/unit_testing/tests_onhold/3_ajax/oSearch.js
|
JavaScript
|
mit
| 2,843
|
/**
* Autoload
*/
(function ($) {
// Autoload namespace: private properties and methods
var Autoload = {
/**
* Include necessary CSS file
*/
css: function (file, options) {
var collection = $("link[rel=stylesheet]"),
path = options.basePath + options.cssPath + file,
element,
i;
for (i = 0; i < collection.length; i += 1) {
if (path === this.href) {
// is loaded
return true;
}
}
if ($.browser.msie) {
/*
<style> element
var styleSheet = document.createElement('STYLE');
document.documentElement.firstChild.appendChild(styleSheet);
*/
element = window.document.createStyleSheet(path);
$(element).attr({
"media": "all"
});
} else {
element = $("<link/>").attr({
"href": path,
"media": "all",
"rel": "stylesheet",
"type": "text/css"
}).appendTo("head");
}
return true;
},
/**
* Search path to js file
*/
findPath: function (baseFile) {
baseFile = baseFile.replace(/\./g, "\\.");
var collection = $("script"),
reg = eval("/^(.*)" + baseFile + "$/"),
i,
p;
for (i = 0; i < collection.length; i += 1) {
p = reg.exec(collection[i].src);
if (null !== p) {
return p[1];
}
}
return null;
},
/**
* Include necessary JavaScript file
*/
js: function (file, options) {
var collection = $("script"),
path = options.basePath + options.jsPath + file,
i;
for (i = 0; i < collection.length; i += 1) {
if (path === collection[i].src) {
// is loaded
return true;
}
}
// When local used in Firefox got [Exception... "Access to restricted URI denied" code: "1012"]
$.ajax({
url: path,
dataType: "script",
success: function (data, textStatus, XMLHttpRequest) {
if (options.successCallback) {
options.successCallback();
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (console) {
console.log(XMLHttpRequest, textStatus, errorThrown);
}
}
});
return true;
}
};
/*
* Autoload namespace: public properties and methods
*/
$.autoload = {
css: function (names, options) {
var basePath = Autoload.findPath(options.baseFile),
cssPath = (undefined === options.cssPath) ? "css/" : options.cssPath,
i;
options = {"basePath": basePath, "cssPath": cssPath};
if ("string" === typeof names) {
names = [names];
}
for (i = 0; i < names.length; i += 1) {
Autoload.css(names[i], options);
}
},
js: function (names, options) {
var i;
options.basePath = Autoload.findPath(options.baseFile);
options.jsPath = (undefined === options.jsPath) ? "plugins/" : options.jsPath;
if ("string" === typeof names) {
names = [names];
}
for (i = 0; i < names.length; i += 1) {
Autoload.js(names[i], options);
}
}
};
//$.wysiwyg.autoload.init();
})(jQuery);
|
allengaller/zenx-tmall
|
web/public_html/protected/modules/translate/widgets/assets/jwysiwyg/help/lib/plugins/autoload/jquery.autoload.js
|
JavaScript
|
mit
| 2,926
|
var _curry1 = require('./internal/_curry1');
var _makeFlat = require('./internal/_makeFlat');
/**
* Returns a new list by pulling every item out of it (and all its sub-arrays) and putting
* them in a new array, depth-first.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> [b]
* @param {Array} list The array to consider.
* @return {Array} The flattened list.
* @see R.unnest
* @example
*
* R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]);
* //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
*/
module.exports = _curry1(_makeFlat(true));
|
concertcoder/leaky-ionic-app
|
www/lib/ramda/src/flatten.js
|
JavaScript
|
mit
| 579
|
/*!
* # Fomantic-UI - Visibility
* http://github.com/fomantic/Fomantic-UI/
*
*
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ($, window, document, undefined) {
'use strict';
$.isFunction = $.isFunction || function(obj) {
return typeof obj === "function" && typeof obj.nodeType !== "number";
};
window = (typeof window != 'undefined' && window.Math == Math)
? window
: (typeof self != 'undefined' && self.Math == Math)
? self
: Function('return this')()
;
$.fn.visibility = function(parameters) {
var
$allModules = $(this),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue,
moduleCount = $allModules.length,
loadedCount = 0
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.visibility.settings, parameters)
: $.extend({}, $.fn.visibility.settings),
className = settings.className,
namespace = settings.namespace,
error = settings.error,
metadata = settings.metadata,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
$window = $(window),
$module = $(this),
$context = $(settings.context),
$placeholder,
instance = $module.data(moduleNamespace),
requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { setTimeout(callback, 0); },
element = this,
disabled = false,
contextObserver,
observer,
module
;
module = {
initialize: function() {
module.debug('Initializing', settings);
module.setup.cache();
if( module.should.trackChanges() ) {
if(settings.type == 'image') {
module.setup.image();
}
if(settings.type == 'fixed') {
module.setup.fixed();
}
if(settings.observeChanges) {
module.observeChanges();
}
module.bind.events();
}
module.save.position();
if( !module.is.visible() ) {
module.error(error.visible, $module);
}
if(settings.initialCheck) {
module.checkVisibility();
}
module.instantiate();
},
instantiate: function() {
module.debug('Storing instance', module);
$module
.data(moduleNamespace, module)
;
instance = module;
},
destroy: function() {
module.verbose('Destroying previous module');
if(observer) {
observer.disconnect();
}
if(contextObserver) {
contextObserver.disconnect();
}
$window
.off('load' + eventNamespace, module.event.load)
.off('resize' + eventNamespace, module.event.resize)
;
$context
.off('scroll' + eventNamespace, module.event.scroll)
.off('scrollchange' + eventNamespace, module.event.scrollchange)
;
if(settings.type == 'fixed') {
module.resetFixed();
module.remove.placeholder();
}
$module
.off(eventNamespace)
.removeData(moduleNamespace)
;
},
observeChanges: function() {
if('MutationObserver' in window) {
contextObserver = new MutationObserver(module.event.contextChanged);
observer = new MutationObserver(module.event.changed);
contextObserver.observe(document, {
childList : true,
subtree : true
});
observer.observe(element, {
childList : true,
subtree : true
});
module.debug('Setting up mutation observer', observer);
}
},
bind: {
events: function() {
module.verbose('Binding visibility events to scroll and resize');
if(settings.refreshOnLoad) {
$window
.on('load' + eventNamespace, module.event.load)
;
}
$window
.on('resize' + eventNamespace, module.event.resize)
;
// pub/sub pattern
$context
.off('scroll' + eventNamespace)
.on('scroll' + eventNamespace, module.event.scroll)
.on('scrollchange' + eventNamespace, module.event.scrollchange)
;
}
},
event: {
changed: function(mutations) {
module.verbose('DOM tree modified, updating visibility calculations');
module.timer = setTimeout(function() {
module.verbose('DOM tree modified, updating sticky menu');
module.refresh();
}, 100);
},
contextChanged: function(mutations) {
[].forEach.call(mutations, function(mutation) {
if(mutation.removedNodes) {
[].forEach.call(mutation.removedNodes, function(node) {
if(node == element || $(node).find(element).length > 0) {
module.debug('Element removed from DOM, tearing down events');
module.destroy();
}
});
}
});
},
resize: function() {
module.debug('Window resized');
if(settings.refreshOnResize) {
requestAnimationFrame(module.refresh);
}
},
load: function() {
module.debug('Page finished loading');
requestAnimationFrame(module.refresh);
},
// publishes scrollchange event on one scroll
scroll: function() {
if(settings.throttle) {
clearTimeout(module.timer);
module.timer = setTimeout(function() {
$context.triggerHandler('scrollchange' + eventNamespace, [ $context.scrollTop() ]);
}, settings.throttle);
}
else {
requestAnimationFrame(function() {
$context.triggerHandler('scrollchange' + eventNamespace, [ $context.scrollTop() ]);
});
}
},
// subscribes to scrollchange
scrollchange: function(event, scrollPosition) {
module.checkVisibility(scrollPosition);
},
},
precache: function(images, callback) {
if (!(images instanceof Array)) {
images = [images];
}
var
imagesLength = images.length,
loadedCounter = 0,
cache = [],
cacheImage = document.createElement('img'),
handleLoad = function() {
loadedCounter++;
if (loadedCounter >= images.length) {
if ($.isFunction(callback)) {
callback();
}
}
}
;
while (imagesLength--) {
cacheImage = document.createElement('img');
cacheImage.onload = handleLoad;
cacheImage.onerror = handleLoad;
cacheImage.src = images[imagesLength];
cache.push(cacheImage);
}
},
enableCallbacks: function() {
module.debug('Allowing callbacks to occur');
disabled = false;
},
disableCallbacks: function() {
module.debug('Disabling all callbacks temporarily');
disabled = true;
},
should: {
trackChanges: function() {
if(methodInvoked) {
module.debug('One time query, no need to bind events');
return false;
}
module.debug('Callbacks being attached');
return true;
}
},
setup: {
cache: function() {
module.cache = {
occurred : {},
screen : {},
element : {},
};
},
image: function() {
var
src = $module.data(metadata.src)
;
if(src) {
module.verbose('Lazy loading image', src);
settings.once = true;
settings.observeChanges = false;
// show when top visible
settings.onOnScreen = function() {
module.debug('Image on screen', element);
module.precache(src, function() {
module.set.image(src, function() {
loadedCount++;
if(loadedCount == moduleCount) {
settings.onAllLoaded.call(this);
}
settings.onLoad.call(this);
});
});
};
}
},
fixed: function() {
module.debug('Setting up fixed');
settings.once = false;
settings.observeChanges = false;
settings.initialCheck = true;
settings.refreshOnLoad = true;
if(!parameters.transition) {
settings.transition = false;
}
module.create.placeholder();
module.debug('Added placeholder', $placeholder);
settings.onTopPassed = function() {
module.debug('Element passed, adding fixed position', $module);
module.show.placeholder();
module.set.fixed();
if(settings.transition) {
if($.fn.transition !== undefined) {
$module.transition(settings.transition, settings.duration);
}
}
};
settings.onTopPassedReverse = function() {
module.debug('Element returned to position, removing fixed', $module);
module.hide.placeholder();
module.remove.fixed();
};
}
},
create: {
placeholder: function() {
module.verbose('Creating fixed position placeholder');
$placeholder = $module
.clone(false)
.css('display', 'none')
.addClass(className.placeholder)
.insertAfter($module)
;
}
},
show: {
placeholder: function() {
module.verbose('Showing placeholder');
$placeholder
.css('display', 'block')
.css('visibility', 'hidden')
;
}
},
hide: {
placeholder: function() {
module.verbose('Hiding placeholder');
$placeholder
.css('display', 'none')
.css('visibility', '')
;
}
},
set: {
fixed: function() {
module.verbose('Setting element to fixed position');
$module
.addClass(className.fixed)
.css({
position : 'fixed',
top : settings.offset + 'px',
left : 'auto',
zIndex : settings.zIndex
})
;
settings.onFixed.call(element);
},
image: function(src, callback) {
$module
.attr('src', src)
;
if(settings.transition) {
if( $.fn.transition !== undefined) {
if($module.hasClass(className.visible)) {
module.debug('Transition already occurred on this image, skipping animation');
return;
}
$module.transition(settings.transition, settings.duration, callback);
}
else {
$module.fadeIn(settings.duration, callback);
}
}
else {
$module.show();
}
}
},
is: {
onScreen: function() {
var
calculations = module.get.elementCalculations()
;
return calculations.onScreen;
},
offScreen: function() {
var
calculations = module.get.elementCalculations()
;
return calculations.offScreen;
},
visible: function() {
if(module.cache && module.cache.element) {
return !(module.cache.element.width === 0 && module.cache.element.offset.top === 0);
}
return false;
},
verticallyScrollableContext: function() {
var
overflowY = ($context.get(0) !== window)
? $context.css('overflow-y')
: false
;
return (overflowY == 'auto' || overflowY == 'scroll');
},
horizontallyScrollableContext: function() {
var
overflowX = ($context.get(0) !== window)
? $context.css('overflow-x')
: false
;
return (overflowX == 'auto' || overflowX == 'scroll');
}
},
refresh: function() {
module.debug('Refreshing constants (width/height)');
if(settings.type == 'fixed') {
module.resetFixed();
}
module.reset();
module.save.position();
if(settings.checkOnRefresh) {
module.checkVisibility();
}
settings.onRefresh.call(element);
},
resetFixed: function () {
module.remove.fixed();
module.remove.occurred();
},
reset: function() {
module.verbose('Resetting all cached values');
if( $.isPlainObject(module.cache) ) {
module.cache.screen = {};
module.cache.element = {};
}
},
checkVisibility: function(scroll) {
module.verbose('Checking visibility of element', module.cache.element);
if( !disabled && module.is.visible() ) {
// save scroll position
module.save.scroll(scroll);
// update calculations derived from scroll
module.save.calculations();
// percentage
module.passed();
// reverse (must be first)
module.passingReverse();
module.topVisibleReverse();
module.bottomVisibleReverse();
module.topPassedReverse();
module.bottomPassedReverse();
// one time
module.onScreen();
module.offScreen();
module.passing();
module.topVisible();
module.bottomVisible();
module.topPassed();
module.bottomPassed();
// on update callback
if(settings.onUpdate) {
settings.onUpdate.call(element, module.get.elementCalculations());
}
}
},
passed: function(amount, newCallback) {
var
calculations = module.get.elementCalculations()
;
// assign callback
if(amount && newCallback) {
settings.onPassed[amount] = newCallback;
}
else if(amount !== undefined) {
return (module.get.pixelsPassed(amount) > calculations.pixelsPassed);
}
else if(calculations.passing) {
$.each(settings.onPassed, function(amount, callback) {
if(calculations.bottomVisible || calculations.pixelsPassed > module.get.pixelsPassed(amount)) {
module.execute(callback, amount);
}
else if(!settings.once) {
module.remove.occurred(callback);
}
});
}
},
onScreen: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onOnScreen,
callbackName = 'onScreen'
;
if(newCallback) {
module.debug('Adding callback for onScreen', newCallback);
settings.onOnScreen = newCallback;
}
if(calculations.onScreen) {
module.execute(callback, callbackName);
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback !== undefined) {
return calculations.onOnScreen;
}
},
offScreen: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onOffScreen,
callbackName = 'offScreen'
;
if(newCallback) {
module.debug('Adding callback for offScreen', newCallback);
settings.onOffScreen = newCallback;
}
if(calculations.offScreen) {
module.execute(callback, callbackName);
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback !== undefined) {
return calculations.onOffScreen;
}
},
passing: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onPassing,
callbackName = 'passing'
;
if(newCallback) {
module.debug('Adding callback for passing', newCallback);
settings.onPassing = newCallback;
}
if(calculations.passing) {
module.execute(callback, callbackName);
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback !== undefined) {
return calculations.passing;
}
},
topVisible: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onTopVisible,
callbackName = 'topVisible'
;
if(newCallback) {
module.debug('Adding callback for top visible', newCallback);
settings.onTopVisible = newCallback;
}
if(calculations.topVisible) {
module.execute(callback, callbackName);
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback === undefined) {
return calculations.topVisible;
}
},
bottomVisible: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onBottomVisible,
callbackName = 'bottomVisible'
;
if(newCallback) {
module.debug('Adding callback for bottom visible', newCallback);
settings.onBottomVisible = newCallback;
}
if(calculations.bottomVisible) {
module.execute(callback, callbackName);
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback === undefined) {
return calculations.bottomVisible;
}
},
topPassed: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onTopPassed,
callbackName = 'topPassed'
;
if(newCallback) {
module.debug('Adding callback for top passed', newCallback);
settings.onTopPassed = newCallback;
}
if(calculations.topPassed) {
module.execute(callback, callbackName);
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback === undefined) {
return calculations.topPassed;
}
},
bottomPassed: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onBottomPassed,
callbackName = 'bottomPassed'
;
if(newCallback) {
module.debug('Adding callback for bottom passed', newCallback);
settings.onBottomPassed = newCallback;
}
if(calculations.bottomPassed) {
module.execute(callback, callbackName);
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback === undefined) {
return calculations.bottomPassed;
}
},
passingReverse: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onPassingReverse,
callbackName = 'passingReverse'
;
if(newCallback) {
module.debug('Adding callback for passing reverse', newCallback);
settings.onPassingReverse = newCallback;
}
if(!calculations.passing) {
if(module.get.occurred('passing')) {
module.execute(callback, callbackName);
}
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback !== undefined) {
return !calculations.passing;
}
},
topVisibleReverse: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onTopVisibleReverse,
callbackName = 'topVisibleReverse'
;
if(newCallback) {
module.debug('Adding callback for top visible reverse', newCallback);
settings.onTopVisibleReverse = newCallback;
}
if(!calculations.topVisible) {
if(module.get.occurred('topVisible')) {
module.execute(callback, callbackName);
}
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback === undefined) {
return !calculations.topVisible;
}
},
bottomVisibleReverse: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onBottomVisibleReverse,
callbackName = 'bottomVisibleReverse'
;
if(newCallback) {
module.debug('Adding callback for bottom visible reverse', newCallback);
settings.onBottomVisibleReverse = newCallback;
}
if(!calculations.bottomVisible) {
if(module.get.occurred('bottomVisible')) {
module.execute(callback, callbackName);
}
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback === undefined) {
return !calculations.bottomVisible;
}
},
topPassedReverse: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onTopPassedReverse,
callbackName = 'topPassedReverse'
;
if(newCallback) {
module.debug('Adding callback for top passed reverse', newCallback);
settings.onTopPassedReverse = newCallback;
}
if(!calculations.topPassed) {
if(module.get.occurred('topPassed')) {
module.execute(callback, callbackName);
}
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback === undefined) {
return !calculations.onTopPassed;
}
},
bottomPassedReverse: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onBottomPassedReverse,
callbackName = 'bottomPassedReverse'
;
if(newCallback) {
module.debug('Adding callback for bottom passed reverse', newCallback);
settings.onBottomPassedReverse = newCallback;
}
if(!calculations.bottomPassed) {
if(module.get.occurred('bottomPassed')) {
module.execute(callback, callbackName);
}
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback === undefined) {
return !calculations.bottomPassed;
}
},
execute: function(callback, callbackName) {
var
calculations = module.get.elementCalculations(),
screen = module.get.screenCalculations()
;
callback = callback || false;
if(callback) {
if(settings.continuous) {
module.debug('Callback being called continuously', callbackName, calculations);
callback.call(element, calculations, screen);
}
else if(!module.get.occurred(callbackName)) {
module.debug('Conditions met', callbackName, calculations);
callback.call(element, calculations, screen);
}
}
module.save.occurred(callbackName);
},
remove: {
fixed: function() {
module.debug('Removing fixed position');
$module
.removeClass(className.fixed)
.css({
position : '',
top : '',
left : '',
zIndex : ''
})
;
settings.onUnfixed.call(element);
},
placeholder: function() {
module.debug('Removing placeholder content');
if($placeholder) {
$placeholder.remove();
}
},
occurred: function(callback) {
if(callback) {
var
occurred = module.cache.occurred
;
if(occurred[callback] !== undefined && occurred[callback] === true) {
module.debug('Callback can now be called again', callback);
module.cache.occurred[callback] = false;
}
}
else {
module.cache.occurred = {};
}
}
},
save: {
calculations: function() {
module.verbose('Saving all calculations necessary to determine positioning');
module.save.direction();
module.save.screenCalculations();
module.save.elementCalculations();
},
occurred: function(callback) {
if(callback) {
if(module.cache.occurred[callback] === undefined || (module.cache.occurred[callback] !== true)) {
module.verbose('Saving callback occurred', callback);
module.cache.occurred[callback] = true;
}
}
},
scroll: function(scrollPosition) {
scrollPosition = scrollPosition + settings.offset || $context.scrollTop() + settings.offset;
module.cache.scroll = scrollPosition;
},
direction: function() {
var
scroll = module.get.scroll(),
lastScroll = module.get.lastScroll(),
direction
;
if(scroll > lastScroll && lastScroll) {
direction = 'down';
}
else if(scroll < lastScroll && lastScroll) {
direction = 'up';
}
else {
direction = 'static';
}
module.cache.direction = direction;
return module.cache.direction;
},
elementPosition: function() {
var
element = module.cache.element,
screen = module.get.screenSize()
;
module.verbose('Saving element position');
// (quicker than $.extend)
element.fits = (element.height < screen.height);
element.offset = $module.offset();
element.width = $module.outerWidth();
element.height = $module.outerHeight();
// compensate for scroll in context
if(module.is.verticallyScrollableContext()) {
element.offset.top += $context.scrollTop() - $context.offset().top;
}
if(module.is.horizontallyScrollableContext()) {
element.offset.left += $context.scrollLeft - $context.offset().left;
}
// store
module.cache.element = element;
return element;
},
elementCalculations: function() {
var
screen = module.get.screenCalculations(),
element = module.get.elementPosition()
;
// offset
if(settings.includeMargin) {
element.margin = {};
element.margin.top = parseInt($module.css('margin-top'), 10);
element.margin.bottom = parseInt($module.css('margin-bottom'), 10);
element.top = element.offset.top - element.margin.top;
element.bottom = element.offset.top + element.height + element.margin.bottom;
}
else {
element.top = element.offset.top;
element.bottom = element.offset.top + element.height;
}
// visibility
element.topPassed = (screen.top >= element.top);
element.bottomPassed = (screen.top >= element.bottom);
element.topVisible = (screen.bottom >= element.top) && !element.topPassed;
element.bottomVisible = (screen.bottom >= element.bottom) && !element.bottomPassed;
element.pixelsPassed = 0;
element.percentagePassed = 0;
// meta calculations
element.onScreen = ((element.topVisible || element.passing) && !element.bottomPassed);
element.passing = (element.topPassed && !element.bottomPassed);
element.offScreen = (!element.onScreen);
// passing calculations
if(element.passing) {
element.pixelsPassed = (screen.top - element.top);
element.percentagePassed = (screen.top - element.top) / element.height;
}
module.cache.element = element;
module.verbose('Updated element calculations', element);
return element;
},
screenCalculations: function() {
var
scroll = module.get.scroll()
;
module.save.direction();
module.cache.screen.top = scroll;
module.cache.screen.bottom = scroll + module.cache.screen.height;
return module.cache.screen;
},
screenSize: function() {
module.verbose('Saving window position');
module.cache.screen = {
height: $context.height()
};
},
position: function() {
module.save.screenSize();
module.save.elementPosition();
}
},
get: {
pixelsPassed: function(amount) {
var
element = module.get.elementCalculations()
;
if(amount.search('%') > -1) {
return ( element.height * (parseInt(amount, 10) / 100) );
}
return parseInt(amount, 10);
},
occurred: function(callback) {
return (module.cache.occurred !== undefined)
? module.cache.occurred[callback] || false
: false
;
},
direction: function() {
if(module.cache.direction === undefined) {
module.save.direction();
}
return module.cache.direction;
},
elementPosition: function() {
if(module.cache.element === undefined) {
module.save.elementPosition();
}
return module.cache.element;
},
elementCalculations: function() {
if(module.cache.element === undefined) {
module.save.elementCalculations();
}
return module.cache.element;
},
screenCalculations: function() {
if(module.cache.screen === undefined) {
module.save.screenCalculations();
}
return module.cache.screen;
},
screenSize: function() {
if(module.cache.screen === undefined) {
module.save.screenSize();
}
return module.cache.screen;
},
scroll: function() {
if(module.cache.scroll === undefined) {
module.save.scroll();
}
return module.cache.scroll;
},
lastScroll: function() {
if(module.cache.screen === undefined) {
module.debug('First scroll event, no last scroll could be found');
return false;
}
return module.cache.screen.top;
}
},
setting: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
settings[name] = value;
}
else {
return settings[name];
}
},
internal: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, module, name);
}
else if(value !== undefined) {
module[name] = value;
}
else {
return module[name];
}
},
debug: function() {
if(!settings.silent && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.debug.apply(console, arguments);
}
}
},
verbose: function() {
if(!settings.silent && settings.verbose && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.verbose.apply(console, arguments);
}
}
},
error: function() {
if(!settings.silent) {
module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
module.error.apply(console, arguments);
}
},
performance: {
log: function(message) {
var
currentTime,
executionTime,
previousTime
;
if(settings.performance) {
currentTime = new Date().getTime();
previousTime = time || currentTime;
executionTime = currentTime - previousTime;
time = currentTime;
performance.push({
'Name' : message[0],
'Arguments' : [].slice.call(message, 1) || '',
'Element' : element,
'Execution Time' : executionTime
});
}
clearTimeout(module.performance.timer);
module.performance.timer = setTimeout(module.performance.display, 500);
},
display: function() {
var
title = settings.name + ':',
totalTime = 0
;
time = false;
clearTimeout(module.performance.timer);
$.each(performance, function(index, data) {
totalTime += data['Execution Time'];
});
title += ' ' + totalTime + 'ms';
if(moduleSelector) {
title += ' \'' + moduleSelector + '\'';
}
if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
console.groupCollapsed(title);
if(console.table) {
console.table(performance);
}
else {
$.each(performance, function(index, data) {
console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
});
}
console.groupEnd();
}
performance = [];
}
},
invoke: function(query, passedArguments, context) {
var
object = instance,
maxDepth,
found,
response
;
passedArguments = passedArguments || queryArguments;
context = element || context;
if(typeof query == 'string' && object !== undefined) {
query = query.split(/[\. ]/);
maxDepth = query.length - 1;
$.each(query, function(depth, value) {
var camelCaseValue = (depth != maxDepth)
? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
: query
;
if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
object = object[camelCaseValue];
}
else if( object[camelCaseValue] !== undefined ) {
found = object[camelCaseValue];
return false;
}
else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
object = object[value];
}
else if( object[value] !== undefined ) {
found = object[value];
return false;
}
else {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if(Array.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
instance.save.scroll();
instance.save.calculations();
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.visibility.settings = {
name : 'Visibility',
namespace : 'visibility',
debug : false,
verbose : false,
performance : true,
// whether to use mutation observers to follow changes
observeChanges : true,
// check position immediately on init
initialCheck : true,
// whether to refresh calculations after all page images load
refreshOnLoad : true,
// whether to refresh calculations after page resize event
refreshOnResize : true,
// should call callbacks on refresh event (resize, etc)
checkOnRefresh : true,
// callback should only occur one time
once : true,
// callback should fire continuously whe evaluates to true
continuous : false,
// offset to use with scroll top
offset : 0,
// whether to include margin in elements position
includeMargin : false,
// scroll context for visibility checks
context : window,
// visibility check delay in ms (defaults to animationFrame)
throttle : false,
// special visibility type (image, fixed)
type : false,
// z-index to use with visibility 'fixed'
zIndex : '10',
// image only animation settings
transition : 'fade in',
duration : 1000,
// array of callbacks for percentage
onPassed : {},
// standard callbacks
onOnScreen : false,
onOffScreen : false,
onPassing : false,
onTopVisible : false,
onBottomVisible : false,
onTopPassed : false,
onBottomPassed : false,
// reverse callbacks
onPassingReverse : false,
onTopVisibleReverse : false,
onBottomVisibleReverse : false,
onTopPassedReverse : false,
onBottomPassedReverse : false,
// special callbacks for image
onLoad : function() {},
onAllLoaded : function() {},
// special callbacks for fixed position
onFixed : function() {},
onUnfixed : function() {},
// utility callbacks
onUpdate : false, // disabled by default for performance
onRefresh : function(){},
metadata : {
src: 'src'
},
className: {
fixed : 'fixed',
placeholder : 'constraint',
visible : 'visible'
},
error : {
method : 'The method you called is not defined.',
visible : 'Element is hidden, you must call refresh after element becomes visible'
}
};
})( jQuery, window, document );
|
robotgear/robotgear
|
semantic/src/definitions/behaviors/visibility.js
|
JavaScript
|
mit
| 42,907
|
'use strict';
(function() {
// Photos Controller Spec
describe('Photos Controller Tests', function() {
// Initialize global variables
var PhotosController,
scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
// Initialize the Photos controller.
PhotosController = $controller('PhotosController', {
$scope: scope
});
}));
it('$scope.find() should create an array with at least one Photo object fetched from XHR', inject(function(Photos) {
// Create sample Photo using the Photos service
var samplePhoto = new Photos({
name: 'New Photo'
});
// Create a sample Photos array that includes the new Photo
var samplePhotos = [samplePhoto];
// Set GET response
$httpBackend.expectGET('photos').respond(samplePhotos);
// Run controller functionality
scope.find();
$httpBackend.flush();
// Test scope value
expect(scope.photos).toEqualData(samplePhotos);
}));
it('$scope.findOne() should create an array with one Photo object fetched from XHR using a photoId URL parameter', inject(function(Photos) {
// Define a sample Photo object
var samplePhoto = new Photos({
name: 'New Photo'
});
// Set the URL parameter
$stateParams.photoId = '525a8422f6d0f87f0e407a33';
// Set GET response
$httpBackend.expectGET(/photos\/([0-9a-fA-F]{24})$/).respond(samplePhoto);
// Run controller functionality
scope.findOne();
$httpBackend.flush();
// Test scope value
expect(scope.photo).toEqualData(samplePhoto);
}));
it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Photos) {
// Create a sample Photo object
var samplePhotoPostData = new Photos({
name: 'New Photo'
});
// Create a sample Photo response
var samplePhotoResponse = new Photos({
_id: '525cf20451979dea2c000001',
name: 'New Photo'
});
// Fixture mock form input values
scope.name = 'New Photo';
// Set POST response
$httpBackend.expectPOST('photos', samplePhotoPostData).respond(samplePhotoResponse);
// Run controller functionality
scope.create();
$httpBackend.flush();
// Test form inputs are reset
expect(scope.name).toEqual('');
// Test URL redirection after the Photo was created
expect($location.path()).toBe('/photos/' + samplePhotoResponse._id);
}));
it('$scope.update() should update a valid Photo', inject(function(Photos) {
// Define a sample Photo put data
var samplePhotoPutData = new Photos({
_id: '525cf20451979dea2c000001',
name: 'New Photo'
});
// Mock Photo in scope
scope.photo = samplePhotoPutData;
// Set PUT response
$httpBackend.expectPUT(/photos\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
scope.update();
$httpBackend.flush();
// Test URL location to new object
expect($location.path()).toBe('/photos/' + samplePhotoPutData._id);
}));
it('$scope.remove() should send a DELETE request with a valid photoId and remove the Photo from the scope', inject(function(Photos) {
// Create new Photo object
var samplePhoto = new Photos({
_id: '525a8422f6d0f87f0e407a33'
});
// Create new Photos array and include the Photo
scope.photos = [samplePhoto];
// Set expected DELETE response
$httpBackend.expectDELETE(/photos\/([0-9a-fA-F]{24})$/).respond(204);
// Run controller functionality
scope.remove(samplePhoto);
$httpBackend.flush();
// Test array after successful delete
expect(scope.photos.length).toBe(0);
}));
});
}());
|
nickeblewis/nfolioMEAN
|
public/modules/photos/tests/photos.client.controller.test.js
|
JavaScript
|
mit
| 4,953
|
/*
YUI 3.17.0 (build ce55cc9)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('graphics', function (Y, NAME) {
/**
*
* <p>The `Graphics` module provides a JavaScript API for creating shapes in a variety of formats across
* a <a href="http://developer.yahoo.com/yui/articles/gbs">browser test baseline</a>.
* Based on device and browser capabilities, `Graphics` leverages <a href="http://www.w3.org/TR/SVG/">SVG</a>,
* <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> and <a href="http://www.w3.org/TR/NOTE-VML">VML</a>
* to render its graphical elements.</p>
*
* <p>The `Graphics` module features a <a href="../classes/Graphic.html">`Graphic`</a> class that allows you to easily create and manage shapes.
* Currently, a <a href="../classes/Graphic.html">`Graphic`</a> instance can be used to create predifined shapes and free-form polygons with fill
* and stroke properties.</p>
*
* <p>The `Graphics` module normalizes an API through the use of alias and implementation classes that share
* interfaces. Each alias class points to an appropriate implementation class dependent on the browser's
* capabilities. There should rarely, if ever, be a need to interact directly with an implementation class.</p>
*
* <p>Below is a list of available classes.
* <ul>
* <li><a href="../classes/Graphic.html">`Graphic`</a>
* <li><a href="../classes/Shape.html">`Shape`</a>
* <li><a href="../classes/Circle.html">`Circle`</a>
* <li><a href="../classes/Ellipse.html">`Ellipse`</a>
* <li><a href="../classes/Rect.html">`Rect`</a>
* <li><a href="../classes/Path.html">`Path`</a>
* </ul>
* You can also extend the `Shape` class to create your own custom shape classes.</p>
* @module graphics
* @main graphics
*/
var SETTER = "setter",
PluginHost = Y.Plugin.Host,
VALUE = "value",
VALUEFN = "valueFn",
READONLY = "readOnly",
Y_LANG = Y.Lang,
STR = "string",
WRITE_ONCE = "writeOnce",
GraphicBase,
AttributeLite;
/**
* AttributeLite provides Attribute-like getters and setters for shape classes in the Graphics module.
* It provides a get/set API without the event infastructure. This class is temporary and a work in progress.
*
* @class AttributeLite
* @constructor
*/
AttributeLite = function()
{
var host = this; // help compression
// Perf tweak - avoid creating event literals if not required.
host._ATTR_E_FACADE = {};
Y.EventTarget.call(this, {emitFacade:true});
host._state = {};
host.prototype = Y.mix(AttributeLite.prototype, host.prototype);
};
AttributeLite.prototype = {
/**
* Initializes the attributes for a shape. If an attribute config is passed into the constructor of the host,
* the initial values will be overwritten.
*
* @method addAttrs
* @param {Object} cfg Optional object containing attributes key value pairs to be set.
*/
addAttrs: function(cfg)
{
var host = this,
attrConfig = this.constructor.ATTRS,
attr,
i,
fn,
state = host._state;
for(i in attrConfig)
{
if(attrConfig.hasOwnProperty(i))
{
attr = attrConfig[i];
if(attr.hasOwnProperty(VALUE))
{
state[i] = attr.value;
}
else if(attr.hasOwnProperty(VALUEFN))
{
fn = attr.valueFn;
if(Y_LANG.isString(fn))
{
state[i] = host[fn].apply(host);
}
else
{
state[i] = fn.apply(host);
}
}
}
}
host._state = state;
for(i in attrConfig)
{
if(attrConfig.hasOwnProperty(i))
{
attr = attrConfig[i];
if(attr.hasOwnProperty(READONLY) && attr.readOnly)
{
continue;
}
if(attr.hasOwnProperty(WRITE_ONCE) && attr.writeOnce)
{
attr.readOnly = true;
}
if(cfg && cfg.hasOwnProperty(i))
{
if(attr.hasOwnProperty(SETTER))
{
host._state[i] = attr.setter.apply(host, [cfg[i]]);
}
else
{
host._state[i] = cfg[i];
}
}
}
}
},
/**
* For a given item, returns the value of the property requested, or undefined if not found.
*
* @method get
* @param name {String} The name of the item
* @return {Any} The value of the supplied property.
*/
get: function(attr)
{
var host = this,
getter,
attrConfig = host.constructor.ATTRS;
if(attrConfig && attrConfig[attr])
{
getter = attrConfig[attr].getter;
if(getter)
{
if(typeof getter === STR)
{
return host[getter].apply(host);
}
return attrConfig[attr].getter.apply(host);
}
return host._state[attr];
}
return null;
},
/**
* Sets the value of an attribute.
*
* @method set
* @param {String|Object} name The name of the attribute. Alternatively, an object of key value pairs can
* be passed in to set multiple attributes at once.
* @param {Any} value The value to set the attribute to. This value is ignored if an object is received as
* the name param.
*/
set: function()
{
var attr = arguments[0],
i;
if(Y_LANG.isObject(attr))
{
for(i in attr)
{
if(attr.hasOwnProperty(i))
{
this._set(i, attr[i]);
}
}
}
else
{
this._set.apply(this, arguments);
}
},
/**
* Provides setter logic. Used by `set`.
*
* @method _set
* @param {String|Object} name The name of the attribute. Alternatively, an object of key value pairs can
* be passed in to set multiple attributes at once.
* @param {Any} value The value to set the attribute to. This value is ignored if an object is received as
* the name param.
* @protected
*/
_set: function(attr, val)
{
var host = this,
setter,
args,
attrConfig = host.constructor.ATTRS;
if(attrConfig && attrConfig.hasOwnProperty(attr))
{
setter = attrConfig[attr].setter;
if(setter)
{
args = [val];
if(typeof setter === STR)
{
val = host[setter].apply(host, args);
}
else
{
val = attrConfig[attr].setter.apply(host, args);
}
}
host._state[attr] = val;
}
}
};
Y.mix(AttributeLite, Y.EventTarget, false, null, 1);
Y.AttributeLite = AttributeLite;
/**
* GraphicBase serves as the base class for the graphic layer. It serves the same purpose as
* Base but uses a lightweight getter/setter class instead of Attribute.
* This class is temporary and a work in progress.
*
* @class GraphicBase
* @constructor
* @param {Object} cfg Key value pairs for attributes
*/
GraphicBase = function(cfg)
{
var host = this,
PluginHost = Y.Plugin && Y.Plugin.Host;
if (host._initPlugins && PluginHost) {
PluginHost.call(host);
}
host.name = host.constructor.NAME;
host._eventPrefix = host.constructor.EVENT_PREFIX || host.constructor.NAME;
AttributeLite.call(host);
host.addAttrs(cfg);
host.init.apply(this, arguments);
if (host._initPlugins) {
// Need to initPlugins manually, to handle constructor parsing, static Plug parsing
host._initPlugins(cfg);
}
host.initialized = true;
};
GraphicBase.NAME = "baseGraphic";
GraphicBase.prototype = {
/**
* Init method, invoked during construction.
* Fires an init event after calling `initializer` on implementers.
*
* @method init
* @protected
*/
init: function()
{
this.publish("init", {
fireOnce:true
});
this.initializer.apply(this, arguments);
this.fire("init", {cfg: arguments[0]});
},
/**
* Camel case concatanates two strings.
*
* @method _camelCaseConcat
* @param {String} prefix The first string
* @param {String} name The second string
* @return String
* @private
*/
_camelCaseConcat: function(prefix, name)
{
return prefix + name.charAt(0).toUpperCase() + name.slice(1);
}
};
//Straightup augment, no wrapper functions
Y.mix(GraphicBase, Y.AttributeLite, false, null, 1);
Y.mix(GraphicBase, PluginHost, false, null, 1);
GraphicBase.prototype.constructor = GraphicBase;
GraphicBase.plug = PluginHost.plug;
GraphicBase.unplug = PluginHost.unplug;
Y.GraphicBase = GraphicBase;
/**
* `Drawing` provides a set of drawing methods used by `Path` and custom shape classes.
* `Drawing` has the following implementations based on browser capability.
* <ul>
* <li><a href="SVGDrawing.html">`SVGDrawing`</a></li>
* <li><a href="VMLDrawing.html">`VMLDrawing`</a></li>
* <li><a href="CanvasDrawing.html">`CanvasDrawing`</a></li>
* </ul>
*
* @class Drawing
* @constructor
*/
/**
* Draws a bezier curve.
*
* @method curveTo
* @param {Number} cp1x x-coordinate for the first control point.
* @param {Number} cp1y y-coordinate for the first control point.
* @param {Number} cp2x x-coordinate for the second control point.
* @param {Number} cp2y y-coordinate for the second control point.
* @param {Number} x x-coordinate for the end point.
* @param {Number} y y-coordinate for the end point.
* @chainable
*/
/**
* Draws a quadratic bezier curve.
*
* @method quadraticCurveTo
* @param {Number} cpx x-coordinate for the control point.
* @param {Number} cpy y-coordinate for the control point.
* @param {Number} x x-coordinate for the end point.
* @param {Number} y y-coordinate for the end point.
* @chainable
*/
/**
* Draws a rectangle.
*
* @method drawRect
* @param {Number} x x-coordinate
* @param {Number} y y-coordinate
* @param {Number} w width
* @param {Number} h height
* @chainable
*/
/**
* Draws a rectangle with rounded corners.
*
* @method drawRoundRect
* @param {Number} x x-coordinate
* @param {Number} y y-coordinate
* @param {Number} w width
* @param {Number} h height
* @param {Number} ew width of the ellipse used to draw the rounded corners
* @param {Number} eh height of the ellipse used to draw the rounded corners
* @chainable
*/
/**
* Draws a circle.
*
* @method drawCircle
* @param {Number} x y-coordinate
* @param {Number} y x-coordinate
* @param {Number} r radius
* @chainable
* @protected
*/
/**
* Draws an ellipse.
*
* @method drawEllipse
* @param {Number} x x-coordinate
* @param {Number} y y-coordinate
* @param {Number} w width
* @param {Number} h height
* @chainable
* @protected
*/
/**
* Draws a diamond.
*
* @method drawDiamond
* @param {Number} x y-coordinate
* @param {Number} y x-coordinate
* @param {Number} width width
* @param {Number} height height
* @chainable
* @protected
*/
/**
* Draws a wedge.
*
* @method drawWedge
* @param {Number} x x-coordinate of the wedge's center point
* @param {Number} y y-coordinate of the wedge's center point
* @param {Number} startAngle starting angle in degrees
* @param {Number} arc sweep of the wedge. Negative values draw clockwise.
* @param {Number} radius radius of wedge. If [optional] yRadius is defined, then radius is the x radius.
* @param {Number} yRadius [optional] y radius for wedge.
* @chainable
* @private
*/
/**
* Draws a line segment using the current line style from the current drawing position to the specified x and y coordinates.
*
* @method lineTo
* @param {Number} point1 x-coordinate for the end point.
* @param {Number} point2 y-coordinate for the end point.
* @chainable
*/
/**
* Draws a line segment using the current line style from the current drawing position to the relative x and y coordinates.
*
* @method relativeLineTo
* @param {Number} point1 x-coordinate for the end point.
* @param {Number} point2 y-coordinate for the end point.
* @chainable
*/
/**
* Moves the current drawing position to specified x and y coordinates.
*
* @method moveTo
* @param {Number} x x-coordinate for the end point.
* @param {Number} y y-coordinate for the end point.
* @chainable
*/
/**
* Moves the current drawing position relative to specified x and y coordinates.
*
* @method relativeMoveTo
* @param {Number} x x-coordinate for the end point.
* @param {Number} y y-coordinate for the end point.
* @chainable
*/
/**
* Completes a drawing operation.
*
* @method end
* @chainable
*/
/**
* Clears the path.
*
* @method clear
* @chainable
*/
/**
* Ends a fill and stroke
*
* @method closePath
* @chainable
*/
/**
* <p>Base class for creating shapes.</p>
* <p>`Shape` is an abstract class and is not meant to be used directly. The following classes extend
* `Shape`.
*
* <ul>
* <li><a href="Circle.html">`Circle`</a></li>
* <li><a href="Ellipse.html">`Ellipse`</a></li>
* <li><a href="Rect.html">`Rect`</a></li>
* <li><a href="Path.html">`Path`</a></li>
* </ul>
*
* `Shape` can also be extended to create custom shape classes.</p>
*
* `Shape` has the following implementations based on browser capability.
* <ul>
* <li><a href="SVGShape.html">`SVGShape`</a></li>
* <li><a href="VMLShape.html">`VMLShape`</a></li>
* <li><a href="CanvasShape.html">`CanvasShape`</a></li>
* </ul>
*
* It is not necessary to interact with these classes directly. `Shape` will point to the appropriate implemention.</p>
*
* @class Shape
* @constructor
* @param {Object} cfg (optional) Attribute configs
*/
/**
* Init method, invoked during construction.
* Calls `initializer` method.
*
* @method init
* @protected
*/
/**
* Initializes the shape
*
* @private
* @method initializer
*/
/**
* Add a class name to each node.
*
* @method addClass
* @param {String} className the class name to add to the node's class attribute
*/
/**
* Removes a class name from each node.
*
* @method removeClass
* @param {String} className the class name to remove from the node's class attribute
*/
/**
* Gets the current position of the node in page coordinates.
*
* @method getXY
* @return Array The XY position of the shape.
*/
/**
* Set the position of the shape in page coordinates, regardless of how the node is positioned.
*
* @method setXY
* @param {Array} Contains x & y values for new position (coordinates are page-based)
*/
/**
* Determines whether the node is an ancestor of another HTML element in the DOM hierarchy.
*
* @method contains
* @param {Shape | HTMLElement} needle The possible node or descendent
* @return Boolean Whether or not this shape is the needle or its ancestor.
*/
/**
* Compares nodes to determine if they match.
* Node instances can be compared to each other and/or HTMLElements.
* @method compareTo
* @param {HTMLElement | Node} refNode The reference node to compare to the node.
* @return {Boolean} True if the nodes match, false if they do not.
*/
/**
* Test if the supplied node matches the supplied selector.
*
* @method test
* @param {String} selector The CSS selector to test against.
* @return Boolean Wheter or not the shape matches the selector.
*/
/**
* Sets the value of an attribute.
*
* @method set
* @param {String|Object} name The name of the attribute. Alternatively, an object of key value pairs can
* be passed in to set multiple attributes at once.
* @param {Any} value The value to set the attribute to. This value is ignored if an object is received as
* the name param.
*/
/**
* Specifies a 2d translation.
*
* @method translate
* @param {Number} x The value to transate on the x-axis.
* @param {Number} y The value to translate on the y-axis.
*/
/**
* Translates the shape along the x-axis. When translating x and y coordinates,
* use the `translate` method.
*
* @method translateX
* @param {Number} x The value to translate.
*/
/**
* Translates the shape along the y-axis. When translating x and y coordinates,
* use the `translate` method.
*
* @method translateY
* @param {Number} y The value to translate.
*/
/**
* Skews the shape around the x-axis and y-axis.
*
* @method skew
* @param {Number} x The value to skew on the x-axis.
* @param {Number} y The value to skew on the y-axis.
*/
/**
* Skews the shape around the x-axis.
*
* @method skewX
* @param {Number} x x-coordinate
*/
/**
* Skews the shape around the y-axis.
*
* @method skewY
* @param {Number} y y-coordinate
*/
/**
* Rotates the shape clockwise around it transformOrigin.
*
* @method rotate
* @param {Number} deg The degree of the rotation.
*/
/**
* Specifies a 2d scaling operation.
*
* @method scale
* @param {Number} val
*/
/**
* Returns the bounds for a shape.
*
* Calculates the a new bounding box from the original corner coordinates (base on size and position) and the transform matrix.
* The calculated bounding box is used by the graphic instance to calculate its viewBox.
*
* @method getBounds
* @return Object
*/
/**
* Destroys the instance.
*
* @method destroy
*/
/**
* An array of x, y values which indicates the transformOrigin in which to rotate the shape. Valid values range between 0 and 1 representing a
* fraction of the shape's corresponding bounding box dimension. The default value is [0.5, 0.5].
*
* @config transformOrigin
* @type Array
*/
/**
* <p>A string containing, in order, transform operations applied to the shape instance. The `transform` string can contain the following values:
*
* <dl>
* <dt>rotate</dt><dd>Rotates the shape clockwise around it transformOrigin.</dd>
* <dt>translate</dt><dd>Specifies a 2d translation.</dd>
* <dt>skew</dt><dd>Skews the shape around the x-axis and y-axis.</dd>
* <dt>scale</dt><dd>Specifies a 2d scaling operation.</dd>
* <dt>translateX</dt><dd>Translates the shape along the x-axis.</dd>
* <dt>translateY</dt><dd>Translates the shape along the y-axis.</dd>
* <dt>skewX</dt><dd>Skews the shape around the x-axis.</dd>
* <dt>skewY</dt><dd>Skews the shape around the y-axis.</dd>
* <dt>matrix</dt><dd>Specifies a 2D transformation matrix comprised of the specified six values.</dd>
* </dl>
* </p>
* <p>Applying transforms through the transform attribute will reset the transform matrix and apply a new transform. The shape class also contains
* corresponding methods for each transform that will apply the transform to the current matrix. The below code illustrates how you might use the
* `transform` attribute to instantiate a recangle with a rotation of 45 degrees.</p>
var myRect = new Y.Rect({
type:"rect",
width: 50,
height: 40,
transform: "rotate(45)"
};
* <p>The code below would apply `translate` and `rotate` to an existing shape.</p>
myRect.set("transform", "translate(40, 50) rotate(45)");
* @config transform
* @type String
*/
/**
* Unique id for class instance.
*
* @config id
* @type String
*/
/**
* Indicates the x position of shape.
*
* @config x
* @type Number
*/
/**
* Indicates the y position of shape.
*
* @config y
* @type Number
*/
/**
* Indicates the width of the shape
*
* @config width
* @type Number
*/
/**
* Indicates the height of the shape
*
* @config height
* @type Number
*/
/**
* Indicates whether the shape is visible.
*
* @config visible
* @type Boolean
*/
/**
* Contains information about the fill of the shape.
* <dl>
* <dt>color</dt><dd>The color of the fill.</dd>
* <dt>opacity</dt><dd>Number between 0 and 1 that indicates the opacity of the fill. The default value is 1.</dd>
* <dt>type</dt><dd>Type of fill.
* <dl>
* <dt>solid</dt><dd>Solid single color fill. (default)</dd>
* <dt>linear</dt><dd>Linear gradient fill.</dd>
* <dt>radial</dt><dd>Radial gradient fill.</dd>
* </dl>
* </dd>
* </dl>
* <p>If a `linear` or `radial` is specified as the fill type. The following additional property is used:
* <dl>
* <dt>stops</dt><dd>An array of objects containing the following properties:
* <dl>
* <dt>color</dt><dd>The color of the stop.</dd>
* <dt>opacity</dt><dd>Number between 0 and 1 that indicates the opacity of the stop. The default value is 1.
* Note: No effect for IE 6 - 8</dd>
* <dt>offset</dt><dd>Number between 0 and 1 indicating where the color stop is positioned.</dd>
* </dl>
* </dd>
* <p>Linear gradients also have the following property:</p>
* <dt>rotation</dt><dd>Linear gradients flow left to right by default. The rotation property allows you to change the
* flow by rotation. (e.g. A rotation of 180 would make the gradient pain from right to left.)</dd>
* <p>Radial gradients have the following additional properties:</p>
* <dt>r</dt><dd>Radius of the gradient circle.</dd>
* <dt>fx</dt><dd>Focal point x-coordinate of the gradient.</dd>
* <dt>fy</dt><dd>Focal point y-coordinate of the gradient.</dd>
* <dt>cx</dt><dd>
* <p>The x-coordinate of the center of the gradient circle. Determines where the color stop begins. The default value 0.5.</p>
* <p><strong>Note: </strong>Currently, this property is not implemented for corresponding `CanvasShape` and
* `VMLShape` classes which are used on Android or IE 6 - 8.</p>
* </dd>
* <dt>cy</dt><dd>
* <p>The y-coordinate of the center of the gradient circle. Determines where the color stop begins. The default value 0.5.</p>
* <p><strong>Note: </strong>Currently, this property is not implemented for corresponding `CanvasShape` and `VMLShape`
* classes which are used on Android or IE 6 - 8.</p>
* </dd>
* </dl>
*
* @config fill
* @type Object
*/
/**
* Contains information about the stroke of the shape.
* <dl>
* <dt>color</dt><dd>The color of the stroke.</dd>
* <dt>weight</dt><dd>Number that indicates the width of the stroke.</dd>
* <dt>opacity</dt><dd>Number between 0 and 1 that indicates the opacity of the stroke. The default value is 1.</dd>
* <dt>dashstyle</dt>Indicates whether to draw a dashed stroke. When set to "none", a solid stroke is drawn. When set
* to an array, the first index indicates the length of the dash. The second index indicates the length of gap.
* <dt>linecap</dt><dd>Specifies the linecap for the stroke. The following values can be specified:
* <dl>
* <dt>butt (default)</dt><dd>Specifies a butt linecap.</dd>
* <dt>square</dt><dd>Specifies a sqare linecap.</dd>
* <dt>round</dt><dd>Specifies a round linecap.</dd>
* </dl>
* </dd>
* <dt>linejoin</dt><dd>Specifies a linejoin for the stroke. The following values can be specified:
* <dl>
* <dt>round (default)</dt><dd>Specifies that the linejoin will be round.</dd>
* <dt>bevel</dt><dd>Specifies a bevel for the linejoin.</dd>
* <dt>miter limit</dt><dd>An integer specifying the miter limit of a miter linejoin. If you want to specify a linejoin
* of miter, you simply specify the limit as opposed to having separate miter and miter limit values.</dd>
* </dl>
* </dd>
* </dl>
*
* @config stroke
* @type Object
*/
/**
* Dom node for the shape.
*
* @config node
* @type HTMLElement
* @readOnly
*/
/**
* Represents an SVG Path string. This will be parsed and added to shape's API to represent the SVG data across all
* implementations. Note that when using VML or SVG implementations, part of this content will be added to the DOM using
* respective VML/SVG attributes. If your content comes from an untrusted source, you will need to ensure that no
* malicious code is included in that content.
*
* @config data
* @type String
*/
/**
* Reference to the parent graphic instance
*
* @config graphic
* @type Graphic
* @readOnly
*/
/**
* <p>Creates circle shape with editable attributes.</p>
* <p>`Circle` instances can be created using the <a href="Graphic.html#method_addShape">`addShape`</a> method of the
* <a href="Graphic.html">`Graphic`</a> class. The method's `cfg` argument contains a `type` attribute. Assigning "circle"
* or `Y.Circle` to this attribute will create a `Circle` instance. Required attributes for instantiating a `Circle` are
* `type` and `radius`. Optional attributes include:
* <ul>
* <li><a href="#attr_fill">fill</a></li>
* <li><a href="#attr_id">id</a></li>
* <li><a href="#attr_stroke">stroke</a></li>
* <li><a href="#attr_transform">transform</a></li>
* <li><a href="#attr_transformOrigin">transformOrigin</a></li>
* <li><a href="#attr_visible">visible</a></li>
* <li><a href="#attr_x">x</a></li>
* <li><a href="#attr_y">y</a></li>
* </ul>
*
* The below code creates a circle by defining the `type` attribute as "circle":</p>
var myCircle = myGraphic.addShape({
type: "circle",
radius: 10,
fill: {
color: "#9aa"
},
stroke: {
weight: 1,
color: "#000"
}
});
* Below, this same circle is created by defining the `type` attribute with a class reference:
*
var myCircle = myGraphic.addShape({
type: Y.Circle,
radius: 10,
fill: {
color: "#9aa"
},
stroke: {
weight: 1,
color: "#000"
}
});
*
* <p>`Circle` has the following implementations based on browser capability.
* <ul>
* <li><a href="SVGCircle.html">`SVGCircle`</a></li>
* <li><a href="VMLCircle.html">`VMLCircle`</a></li>
* <li><a href="CanvasCircle.html">`CanvasCircle`</a></li>
* </ul>
*
* It is not necessary to interact with these classes directly. `Circle` will point to the appropriate implemention.</p>
*
* @class Circle
* @extends Shape
* @constructor
*/
/**
* Radius of the circle
*
* @config radius
* @type Number
*/
/**
* <p>Creates an ellipse shape with editable attributes.</p>
* <p>`Ellipse` instances can be created using the <a href="Graphic.html#method_addShape">`addShape`</a> method of the
* <a href="Graphic.html">`Graphic`</a> class. The method's `cfg` argument contains a `type` attribute. Assigning "ellipse"
* or `Y.Ellipse` to this attribute will create a `Ellipse` instance. Required attributes for instantiating a `Ellipse` are
* `type`, `width` and `height`. Optional attributes include:
* <ul>
* <li><a href="#attr_fill">fill</a></li>
* <li><a href="#attr_id">id</a></li>
* <li><a href="#attr_stroke">stroke</a></li>
* <li><a href="#attr_transform">transform</a></li>
* <li><a href="#attr_transformOrigin">transformOrigin</a></li>
* <li><a href="#attr_visible">visible</a></li>
* <li><a href="#attr_x">x</a></li>
* <li><a href="#attr_y">y</a></li>
* </ul>
*
* The below code creates an ellipse by defining the `type` attribute as "ellipse":</p>
var myEllipse = myGraphic.addShape({
type: "ellipse",
width: 20,
height: 10,
fill: {
color: "#9aa"
},
stroke: {
weight: 1,
color: "#000"
}
});
* Below, the same ellipse is created by defining the `type` attribute with a class reference:
*
var myEllipse = myGraphic.addShape({
type: Y.Ellipse,
width: 20,
height: 10,
fill: {
color: "#9aa"
},
stroke: {
weight: 1,
color: "#000"
}
});
*
* <p>`Ellipse` has the following implementations based on browser capability.
* <ul>
* <li><a href="SVGEllipse.html">`SVGEllipse`</a></li>
* <li><a href="VMLEllipse.html">`VMLEllipse`</a></li>
* <li><a href="CanvasEllipse.html">`CanvasEllipse`</a></li>
* </ul>
*
* It is not necessary to interact with these classes directly. `Ellipse` will point to the appropriate implemention.</p>
*
* @class Ellipse
* @extends Shape
* @constructor
*/
/**
* <p>Creates an rectangle shape with editable attributes.</p>
* <p>`Rect` instances can be created using the <a href="Graphic.html#method_addShape">`addShape`</a> method of the
* <a href="Graphic.html">`Graphic`</a> class. The method's `cfg` argument contains a `type` attribute. Assigning "rect"
* or `Y.Rect` to this attribute will create a `Rect` instance. Required attributes for instantiating a `Rect` are `type`,
* `width` and `height`. Optional attributes include:
* <ul>
* <li><a href="#attr_fill">fill</a></li>
* <li><a href="#attr_id">id</a></li>
* <li><a href="#attr_stroke">stroke</a></li>
* <li><a href="#attr_transform">transform</a></li>
* <li><a href="#attr_transformOrigin">transformOrigin</a></li>
* <li><a href="#attr_visible">visible</a></li>
* <li><a href="#attr_x">x</a></li>
* <li><a href="#attr_y">y</a></li>
* </ul>
*
* The below code creates a rectangle by defining the `type` attribute as "rect":</p>
var myRect = myGraphic.addShape({
type: "rect",
width: 20,
height: 10,
fill: {
color: "#9aa"
},
stroke: {
weight: 1,
color: "#000"
}
});
* Below, the same rectangle is created by defining the `type` attribute with a class reference:
*
var myRect = myGraphic.addShape({
type: Y.Rect,
width: 20,
height: 10,
fill: {
color: "#9aa"
},
stroke: {
weight: 1,
color: "#000"
}
});
*
* <p>`Rect` has the following implementations based on browser capability.
* <ul>
* <li><a href="SVGRect.html">`SVGRect`</a></li>
* <li><a href="VMLRect.html">`VMLRect`</a></li>
* <li><a href="CanvasRect.html">`CanvasRect`</a></li>
* </ul>
*
* It is not necessary to interact with these classes directly. `Rect` will point to the appropriate implemention.</p>
*
* @class Rect
* @extends Shape
* @constructor
*/
/**
* <p>The `Path` class creates a shape through the use of drawing methods. The `Path` class has the following drawing methods available:</p>
* <ul>
* <li><a href="#method_clear">`clear`</a></li>
* <li><a href="#method_curveTo">`curveTo`</a></li>
* <li><a href="#method_drawRect">`drawRect`</a></li>
* <li><a href="#method_drawRoundRect">`drawRoundRect`</a></li>
* <li><a href="#method_end">`end`</a></li>
* <li><a href="#method_lineTo">`lineTo`</a></li>
* <li><a href="#method_moveTo">`moveTo`</a></li>
* <li><a href="#method_quadraticCurveTo">`quadraticCurveTo`</a></li>
* </ul>
*
* <p>Like other shapes, `Path` elements are created using the <a href="Graphic.html#method_addShape">`addShape`</a>
* method of the <a href="Graphic.html">`Graphic`</a> class. The method's `cfg` argument contains a `type` attribute.
* Assigning "path" or `Y.Path` to this attribute will create a `Path` instance. After instantiation, a series of drawing
* operations must be performed in order to render a shape. The below code instantiates a path element by defining the
* `type` attribute as "path":</p>
var myPath = myGraphic.addShape({
type: "path",
fill: {
color: "#9aa"
},
stroke: {
weight: 1,
color: "#000"
}
});
* Below a `Path` element with the same properties is instantiated by defining the `type` attribute with a class reference:
*
var myPath = myGraphic.addShape({
type: Y.Path,
fill: {
color: "#9aa"
},
stroke: {
weight: 1,
color: "#000"
}
});
* After instantiation, a shape or segment needs to be drawn for an element to render. After all draw operations are performed,
* the <a href="#method_end">`end`</a> method will render the shape. The code below will draw a triangle:
myPath.moveTo(35, 5);
myPath.lineTo(65, 65);
myPath.lineTo(5, 65);
myPath.lineTo(35, 5);
myPath.end();
*
* <p>`Path` has the following implementations based on browser capability.
* <ul>
* <li><a href="SVGPath.html">`SVGPath`</a></li>
* <li><a href="VMLPath.html">`VMLPath`</a></li>
* <li><a href="CanvasPath.html">`CanvasPath`</a></li>
* </ul>
* It is not necessary to interact with these classes directly. `Path` will point to the appropriate implemention.</p>
*
* @class Path
* @extends Shape
* @uses Drawing
* @constructor
*/
/**
* Indicates the path used for the node.
*
* @config path
* @type String
* @readOnly
*/
/**
* `Graphic` acts a factory and container for shapes. You need at least one `Graphic` instance to create shapes for your application.
* <p>The code block below creates a `Graphic` instance and appends it to an HTMLElement with the id 'mygraphiccontainer'.</p>
var myGraphic = new Y.Graphic({render:"#mygraphiccontainer"});
* <p>Alternatively, you can add a `Graphic` instance to the DOM using the <a href="#method_render">`render`</a> method.</p>
var myGraphic = new Y.Graphic();
myGraphic.render("#mygraphiccontainer");
* `Graphic` has the following implementations based on browser capability.
* <ul>
* <li><a href="SVGGraphic.html">`SVGGraphic`</a></li>
* <li><a href="VMLGraphic.html">`VMLGraphic`</a></li>
* <li><a href="CanvasGraphic.html">`CanvasGraphic`</a></li>
* </ul>
*
* It is not necessary to interact with these classes directly. `Graphic` will point to the appropriate implemention.</p>
*
* @class Graphic
* @constructor
*/
/**
* Whether or not to render the `Graphic` automatically after to a specified parent node after init. This can be a Node
* instance or a CSS selector string.
*
* @config render
* @type Node | String
*/
/**
* Unique id for class instance.
*
* @config id
* @type String
*/
/**
* Key value pairs in which a shape instance is associated with its id.
*
* @config shapes
* @type Object
* @readOnly
*/
/**
* Object containing size and coordinate data for the content of a Graphic in relation to the coordSpace node.
*
* @config contentBounds
* @type Object
* @readOnly
*/
/**
* The html element that represents to coordinate system of the Graphic instance.
*
* @config node
* @type HTMLElement
* @readOnly
*/
/**
* Indicates the width of the `Graphic`.
*
* @config width
* @type Number
*/
/**
* Indicates the height of the `Graphic`.
*
* @config height
* @type Number
*/
/**
* Determines the sizing of the Graphic.
*
* <dl>
* <dt>sizeContentToGraphic</dt><dd>The Graphic's width and height attributes are, either explicitly set through the
* <code>width</code> and <code>height</code> attributes or are determined by the dimensions of the parent element. The
* content contained in the Graphic will be sized to fit with in the Graphic instance's dimensions. When using this
* setting, the <code>preserveAspectRatio</code> attribute will determine how the contents are sized.</dd>
* <dt>sizeGraphicToContent</dt><dd>(Also accepts a value of true) The Graphic's width and height are determined by the
* size and positioning of the content.</dd>
* <dt>false</dt><dd>The Graphic's width and height attributes are, either explicitly set through the <code>width</code>
* and <code>height</code> attributes or are determined by the dimensions of the parent element. The contents of the
* Graphic instance are not affected by this setting.</dd>
* </dl>
*
*
* @config autoSize
* @type Boolean | String
* @default false
*/
/**
* Determines how content is sized when <code>autoSize</code> is set to <code>sizeContentToGraphic</code>.
*
* <dl>
* <dt>none<dt><dd>Do not force uniform scaling. Scale the graphic content of the given element non-uniformly if necessary
* such that the element's bounding box exactly matches the viewport rectangle.</dd>
* <dt>xMinYMin</dt><dd>Force uniform scaling position along the top left of the Graphic's node.</dd>
* <dt>xMidYMin</dt><dd>Force uniform scaling horizontally centered and positioned at the top of the Graphic's node.<dd>
* <dt>xMaxYMin</dt><dd>Force uniform scaling positioned horizontally from the right and vertically from the top.</dd>
* <dt>xMinYMid</dt>Force uniform scaling positioned horizontally from the left and vertically centered.</dd>
* <dt>xMidYMid (the default)</dt><dd>Force uniform scaling with the content centered.</dd>
* <dt>xMaxYMid</dt><dd>Force uniform scaling positioned horizontally from the right and vertically centered.</dd>
* <dt>xMinYMax</dt><dd>Force uniform scaling positioned horizontally from the left and vertically from the bottom.</dd>
* <dt>xMidYMax</dt><dd>Force uniform scaling horizontally centered and position vertically from the bottom.</dd>
* <dt>xMaxYMax</dt><dd>Force uniform scaling positioned horizontally from the right and vertically from the bottom.</dd>
* </dl>
*
* @config preserveAspectRatio
* @type String
* @default xMidYMid
*/
/**
* The contentBounds will resize to greater values but not to smaller values. (for performance)
* When resizing the contentBounds down is desirable, set the resizeDown value to true.
*
* @config resizeDown
* @type Boolean
*/
/**
* Indicates the x-coordinate for the instance.
*
* @config x
* @type Number
*/
/**
* Indicates the y-coordinate for the instance.
*
* @config y
* @type Number
*/
/**
* Indicates whether or not the instance will automatically redraw after a change is made to a shape.
* This property will get set to false when batching operations.
*
* @config autoDraw
* @type Boolean
* @default true
* @private
*/
/**
* Indicates whether the `Graphic` and its children are visible.
*
* @config visible
* @type Boolean
*/
/**
* Gets the current position of the graphic instance in page coordinates.
*
* @method getXY
* @return Array The XY position of the shape.
*/
/**
* Adds the graphics node to the dom.
*
* @method render
* @param {Node|String} parentNode node in which to render the graphics node into.
*/
/**
* Removes all nodes.
*
* @method destroy
*/
/**
* <p>Generates a shape instance by type. The method accepts an object that contain's the shape's
* type and attributes to be customized. For example, the code below would create a rectangle:</p>
*
var myRect = myGraphic.addShape({
type: "rect",
width: 40,
height: 30,
fill: {
color: "#9aa"
},
stroke: {
weight: 1,
color: "#000"
}
});
*
* <p>The `Graphics` module includes a few basic shapes. More information on their creation
* can be found in each shape's documentation:
*
* <ul>
* <li><a href="Circle.html">`Circle`</a></li>
* <li><a href="Ellipse.html">`Ellipse`</a></li>
* <li><a href="Rect.html">`Rect`</a></li>
* <li><a href="Path.html">`Path`</a></li>
* </ul>
*
* The `Graphics` module also allows for the creation of custom shapes. If a custom shape
* has been created, it can be instantiated with the `addShape` method as well. The attributes,
* required and optional, would need to be defined in the custom shape.
*
var myCustomShape = myGraphic.addShape({
type: Y.MyCustomShape,
width: 50,
height: 50,
fill: {
color: "#9aa"
},
stroke: {
weight: 1,
color: "#000"
}
});
*
* @method addShape
* @param {Object} cfg Object containing the shape's type and attributes.
* @return Shape
*/
/**
* Removes a shape instance from from the graphic instance.
*
* @method removeShape
* @param {Shape|String} shape The instance or id of the shape to be removed.
*/
/**
* Removes all shape instances from the dom.
*
* @method removeAllShapes
*/
/**
* Returns a shape based on the id of its dom node.
*
* @method getShapeById
* @param {String} id Dom id of the shape's node attribute.
* @return Shape
*/
/**
* Allows for creating multiple shapes in order to batch appending and redraw operations.
*
* @method batch
* @param {Function} method Method to execute.
*/
}, '3.17.0', {"requires": ["node", "event-custom", "pluginhost", "matrix", "classnamemanager"]});
|
wayne-lewis/baiducdnstatic
|
libs/yui/3.17.0/graphics/graphics.js
|
JavaScript
|
mit
| 43,760
|
var searchData=
[
['empty',['Empty',['../classv8_1_1_string.html#a93009e63fb89a2c8264b87ec422af963',1,'v8::String']]],
['enableagent',['EnableAgent',['../classv8_1_1_debug.html#a63f491229ef01576bfeb5814e9b14a5e',1,'v8::Debug']]],
['enableslidingstatewindow',['EnableSlidingStateWindow',['../classv8_1_1_v8.html#aa91df5fe1bb98b87952ef4bbf0aceb96',1,'v8::V8']]],
['enter',['Enter',['../classv8_1_1_context.html#a6995c49d9897eb49053f07874b825133',1,'v8::Context']]],
['equals',['Equals',['../classv8_1_1_value.html#adc2a7a92a120675bbd4c992163a20869',1,'v8::Value']]],
['exception',['Exception',['../classv8_1_1_try_catch.html#a99c425f29b3355b4294cbe762377f99b',1,'v8::TryCatch']]],
['exit',['Exit',['../classv8_1_1_context.html#a2db09d4fefb26023a40d88972a4c1599',1,'v8::Context']]]
];
|
v8-dox/v8-dox.github.io
|
fcff66b/html/search/functions_3.js
|
JavaScript
|
mit
| 796
|
/**
* @class Ext.scroll.Scroller
* @author Jacky Nguyen <jacky@sencha.com>
*
* Momentum scrolling is one of the most important part of the framework's UI layer. In Sencha Touch there are
* several scroller implementations so we can have the best performance on all mobile devices and browsers.
*
* Scroller settings can be changed using the {@link Ext.Container#scrollable scrollable} configuration in
* {@link Ext.Container}. Anything you pass to that method will be passed to the scroller when it is
* instantiated in your container.
*
* Please note that the {@link Ext.Container#getScrollable} method returns an instance of {@link Ext.scroll.View}.
* So if you need to get access to the scroller after your container has been instantiated, you must use the
* {@link Ext.scroll.View#getScroller} method.
*
* // lets assume container is a container you have
* // created which is scrollable
* container.getScrollable().getScroller().setFps(10);
*
* ## Example
*
* Here is a simple example of how to adjust the scroller settings when using a {@link Ext.Container} (or anything
* that extends it).
*
* @example
* var container = Ext.create('Ext.Container', {
* fullscreen: true,
* html: 'This container is scrollable!',
* scrollable: {
* direction: 'vertical'
* }
* });
*
* As you can see, we are passing the {@link #direction} configuration into the scroller instance in our container.
*
* You can pass any of the configs below in that {@link Ext.Container#scrollable scrollable} configuration and it will
* just work.
*
* Go ahead and try it in the live code editor above!
*/
Ext.define('Ext.scroll.Scroller', {
extend: 'Ext.Evented',
requires: [
'Ext.fx.easing.BoundMomentum',
'Ext.fx.easing.EaseOut',
'Ext.util.Translatable'
],
/**
* @event maxpositionchange
* Fires whenever the maximum position has changed.
* @param {Ext.scroll.Scroller} this
* @param {Number} maxPosition The new maximum position.
*/
/**
* @event refresh
* Fires whenever the Scroller is refreshed.
* @param {Ext.scroll.Scroller} this
*/
/**
* @event scrollstart
* Fires whenever the scrolling is started.
* @param {Ext.scroll.Scroller} this
* @param {Number} x The current x position.
* @param {Number} y The current y position.
*/
/**
* @event scrollend
* Fires whenever the scrolling is ended.
* @param {Ext.scroll.Scroller} this
* @param {Number} x The current x position.
* @param {Number} y The current y position.
*/
/**
* @event scroll
* Fires whenever the Scroller is scrolled.
* @param {Ext.scroll.Scroller} this
* @param {Number} x The new x position.
* @param {Number} y The new y position.
*/
config: {
/**
* @cfg element
* @private
*/
element: null,
/**
* @cfg {String} direction
* Possible values: 'auto', 'vertical', 'horizontal', or 'both'.
* @accessor
*/
direction: 'auto',
/**
* @cfg fps
* @private
*/
fps: 'auto',
/**
* @cfg {Boolean} disabled
* Whether or not this component is disabled.
* @accessor
*/
disabled: null,
/**
* @cfg {Boolean} directionLock
* `true` to lock the direction of the scroller when the user starts scrolling.
* This is useful when putting a scroller inside a scroller or a {@link Ext.Carousel}.
* @accessor
*/
directionLock: false,
/**
* @cfg {Object} momentumEasing
* A valid config for {@link Ext.fx.easing.BoundMomentum}. The default value is:
*
* {
* momentum: {
* acceleration: 30,
* friction: 0.5
* },
* bounce: {
* acceleration: 30,
* springTension: 0.3
* }
* }
*
* Note that supplied object will be recursively merged with the default object. For example, you can simply
* pass this to change the momentum acceleration only:
*
* {
* momentum: {
* acceleration: 10
* }
* }
*
* @accessor
*/
momentumEasing: {
momentum: {
acceleration: 30,
friction: 0.5
},
bounce: {
acceleration: 30,
springTension: 0.3
},
minVelocity: 1
},
/**
* @cfg bounceEasing
* @private
*/
bounceEasing: {
duration: 400
},
/**
* @cfg outOfBoundRestrictFactor
* @private
*/
outOfBoundRestrictFactor: 0.5,
/**
* @cfg startMomentumResetTime
* @private
*/
startMomentumResetTime: 300,
/**
* @cfg maxAbsoluteVelocity
* @private
*/
maxAbsoluteVelocity: 6,
/**
* @cfg containerSize
* @private
*/
containerSize: 'auto',
/**
* @cfg size
* @private
*/
size: 'auto',
/**
* @cfg autoRefresh
* @private
*/
autoRefresh: true,
/**
* @cfg {Object/Number} initialOffset
* The initial scroller position. When specified as Number,
* both x and y will be set to that value.
*/
initialOffset: {
x: 0,
y: 0
},
/**
* @cfg {Number/Object} slotSnapSize
* The size of each slot to snap to in 'px', can be either an object with `x` and `y` values, i.e:
*
* {
* x: 50,
* y: 100
* }
*
* or a number value to be used for both directions. For example, a value of `50` will be treated as:
*
* {
* x: 50,
* y: 50
* }
*
* @accessor
*/
slotSnapSize: {
x: 0,
y: 0
},
/**
* @cfg slotSnapOffset
* @private
*/
slotSnapOffset: {
x: 0,
y: 0
},
slotSnapEasing: {
duration: 150
},
translatable: {
translationMethod: 'auto',
useWrapper: false
}
},
cls: Ext.baseCSSPrefix + 'scroll-scroller',
containerCls: Ext.baseCSSPrefix + 'scroll-container',
dragStartTime: 0,
dragEndTime: 0,
isDragging: false,
isAnimating: false,
/**
* @private
* @constructor
* @chainable
*/
constructor: function(config) {
var element = config && config.element;
this.listeners = {
scope: this,
touchstart: 'onTouchStart',
touchend: 'onTouchEnd',
dragstart: 'onDragStart',
drag: 'onDrag',
dragend: 'onDragEnd'
};
this.minPosition = { x: 0, y: 0 };
this.startPosition = { x: 0, y: 0 };
this.position = { x: 0, y: 0 };
this.velocity = { x: 0, y: 0 };
this.isAxisEnabledFlags = { x: false, y: false };
this.flickStartPosition = { x: 0, y: 0 };
this.flickStartTime = { x: 0, y: 0 };
this.lastDragPosition = { x: 0, y: 0 };
this.dragDirection = { x: 0, y: 0};
this.initialConfig = config;
if (element) {
this.setElement(element);
}
return this;
},
/**
* @private
*/
applyElement: function(element) {
if (!element) {
return;
}
return Ext.get(element);
},
/**
* @private
* @chainable
*/
updateElement: function(element) {
this.initialize();
if (!this.FixedHBoxStretching) {
element.addCls(this.cls);
}
if (!this.getDisabled()) {
this.attachListeneners();
}
this.onConfigUpdate(['containerSize', 'size'], 'refreshMaxPosition');
this.on('maxpositionchange', 'snapToBoundary');
this.on('minpositionchange', 'snapToBoundary');
return this;
},
applyTranslatable: function(config, translatable) {
return Ext.factory(config, Ext.util.Translatable, translatable);
},
updateTranslatable: function(translatable) {
translatable.setConfig({
element: this.getElement(),
listeners: {
animationframe: 'onAnimationFrame',
animationend: 'onAnimationEnd',
scope: this
}
});
},
updateFps: function(fps) {
if (fps !== 'auto') {
this.getTranslatable().setFps(fps);
}
},
/**
* @private
*/
attachListeneners: function() {
this.getContainer().on(this.listeners);
},
/**
* @private
*/
detachListeners: function() {
this.getContainer().un(this.listeners);
},
/**
* @private
*/
updateDisabled: function(disabled) {
if (disabled) {
this.detachListeners();
}
else {
this.attachListeneners();
}
},
updateInitialOffset: function(initialOffset) {
if (typeof initialOffset == 'number') {
initialOffset = {
x: initialOffset,
y: initialOffset
};
}
var position = this.position,
x, y;
position.x = x = initialOffset.x;
position.y = y = initialOffset.y;
this.getTranslatable().translate(-x, -y);
},
/**
* @private
* @return {String}
*/
applyDirection: function(direction) {
var minPosition = this.getMinPosition(),
maxPosition = this.getMaxPosition(),
isHorizontal, isVertical;
this.givenDirection = direction;
if (direction === 'auto') {
isHorizontal = maxPosition.x > minPosition.x;
isVertical = maxPosition.y > minPosition.y;
if (isHorizontal && isVertical) {
direction = 'both';
}
else if (isHorizontal) {
direction = 'horizontal';
}
else {
direction = 'vertical';
}
}
return direction;
},
/**
* @private
*/
updateDirection: function(direction) {
var isAxisEnabledFlags = this.isAxisEnabledFlags;
isAxisEnabledFlags.x = (direction === 'both' || direction === 'horizontal');
isAxisEnabledFlags.y = (direction === 'both' || direction === 'vertical');
},
/**
* Returns `true` if a specified axis is enabled.
* @param {String} axis The axis to check (`x` or `y`).
* @return {Boolean} `true` if the axis is enabled.
*/
isAxisEnabled: function(axis) {
this.getDirection();
return this.isAxisEnabledFlags[axis];
},
/**
* @private
* @return {Object}
*/
applyMomentumEasing: function(easing) {
var defaultClass = Ext.fx.easing.BoundMomentum;
return {
x: Ext.factory(easing, defaultClass),
y: Ext.factory(easing, defaultClass)
};
},
/**
* @private
* @return {Object}
*/
applyBounceEasing: function(easing) {
var defaultClass = Ext.fx.easing.EaseOut;
return {
x: Ext.factory(easing, defaultClass),
y: Ext.factory(easing, defaultClass)
};
},
updateBounceEasing: function(easing) {
this.getTranslatable().setEasingX(easing.x).setEasingY(easing.y);
},
/**
* @private
* @return {Object}
*/
applySlotSnapEasing: function(easing) {
var defaultClass = Ext.fx.easing.EaseOut;
return {
x: Ext.factory(easing, defaultClass),
y: Ext.factory(easing, defaultClass)
};
},
/**
* @private
* @return {Object}
*/
getMinPosition: function() {
var minPosition = this.minPosition;
if (!minPosition) {
this.minPosition = minPosition = {
x: 0,
y: 0
};
this.fireEvent('minpositionchange', this, minPosition);
}
return minPosition;
},
/**
* @private
* @return {Object}
*/
getMaxPosition: function() {
var maxPosition = this.maxPosition,
size, containerSize;
if (!maxPosition) {
size = this.getSize();
containerSize = this.getContainerSize();
this.maxPosition = maxPosition = {
x: Math.max(0, size.x - containerSize.x),
y: Math.max(0, size.y - containerSize.y)
};
this.fireEvent('maxpositionchange', this, maxPosition);
}
return maxPosition;
},
/**
* @private
*/
refreshMaxPosition: function() {
this.maxPosition = null;
this.getMaxPosition();
},
/**
* @private
* @return {Object}
*/
applyContainerSize: function(size) {
var containerDom = this.getContainer().dom,
x, y;
if (!containerDom) {
return;
}
this.givenContainerSize = size;
if (size === 'auto') {
x = containerDom.offsetWidth;
y = containerDom.offsetHeight;
}
else {
x = size.x;
y = size.y;
}
return {
x: x,
y: y
};
},
/**
* @private
* @param {String/Object} size
* @return {Object}
*/
applySize: function(size) {
var dom = this.getElement().dom,
x, y;
if (!dom) {
return;
}
this.givenSize = size;
if (size === 'auto') {
x = dom.offsetWidth;
y = dom.offsetHeight;
}
else if (typeof size == 'number') {
x = size;
y = size;
}
else {
x = size.x;
y = size.y;
}
return {
x: x,
y: y
};
},
/**
* @private
*/
updateAutoRefresh: function(autoRefresh) {
this.getElement().toggleListener(autoRefresh, 'resize', 'onElementResize', this);
this.getContainer().toggleListener(autoRefresh, 'resize', 'onContainerResize', this);
},
applySlotSnapSize: function(snapSize) {
if (typeof snapSize == 'number') {
return {
x: snapSize,
y: snapSize
};
}
return snapSize;
},
applySlotSnapOffset: function(snapOffset) {
if (typeof snapOffset == 'number') {
return {
x: snapOffset,
y: snapOffset
};
}
return snapOffset;
},
/**
* @private
* Returns the container for this scroller
*/
getContainer: function() {
var container = this.container,
element;
if (!container) {
element = this.getElement().getParent();
this.container = container = this.FixedHBoxStretching ? element.getParent() : element;
//<debug error>
if (!container) {
Ext.Logger.error("Making an element scrollable that doesn't have any container");
}
//</debug>
container.addCls(this.containerCls);
}
return container;
},
/**
* @private
* @return {Ext.scroll.Scroller} this
* @chainable
*/
refresh: function() {
this.stopAnimation();
this.getTranslatable().refresh();
this.setSize(this.givenSize);
this.setContainerSize(this.givenContainerSize);
this.setDirection(this.givenDirection);
this.fireEvent('refresh', this);
return this;
},
onElementResize: function(element, info) {
this.setSize({
x: info.width,
y: info.height
});
this.refresh();
},
onContainerResize: function(container, info) {
this.setContainerSize({
x: info.width,
y: info.height
});
this.refresh();
},
/**
* Scrolls to the given location.
*
* @param {Number} x The scroll position on the x axis.
* @param {Number} y The scroll position on the y axis.
* @param {Boolean/Object} animation (optional) Whether or not to animate the scrolling to the new position.
*
* @return {Ext.scroll.Scroller} this
* @chainable
*/
scrollTo: function(x, y, animation) {
if (this.isDestroyed) {
return this;
}
//<deprecated product=touch since=2.0>
if (typeof x != 'number' && arguments.length === 1) {
//<debug warn>
Ext.Logger.deprecate("Calling scrollTo() with an object argument is deprecated, " +
"please pass x and y arguments instead", this);
//</debug>
y = x.y;
x = x.x;
}
//</deprecated>
var translatable = this.getTranslatable(),
position = this.position,
positionChanged = false,
translationX, translationY;
if (this.isAxisEnabled('x')) {
if (isNaN(x) || typeof x != 'number') {
x = position.x;
}
else {
if (position.x !== x) {
position.x = x;
positionChanged = true;
}
}
translationX = -x;
}
if (this.isAxisEnabled('y')) {
if (isNaN(y) || typeof y != 'number') {
y = position.y;
}
else {
if (position.y !== y) {
position.y = y;
positionChanged = true;
}
}
translationY = -y;
}
if (positionChanged) {
if (animation !== undefined && animation !== false) {
translatable.translateAnimated(translationX, translationY, animation);
}
else {
this.fireEvent('scroll', this, position.x, position.y);
translatable.translate(translationX, translationY);
}
}
return this;
},
/**
* @private
* @return {Ext.scroll.Scroller} this
* @chainable
*/
scrollToTop: function(animation) {
var initialOffset = this.getInitialOffset();
return this.scrollTo(initialOffset.x, initialOffset.y, animation);
},
/**
* Scrolls to the end of the scrollable view.
* @return {Ext.scroll.Scroller} this
* @chainable
*/
scrollToEnd: function(animation) {
var size = this.getSize(),
cntSize = this.getContainerSize();
return this.scrollTo(size.x - cntSize.x, size.y - cntSize.y, animation);
},
/**
* Change the scroll offset by the given amount.
* @param {Number} x The offset to scroll by on the x axis.
* @param {Number} y The offset to scroll by on the y axis.
* @param {Boolean/Object} animation (optional) Whether or not to animate the scrolling to the new position.
* @return {Ext.scroll.Scroller} this
* @chainable
*/
scrollBy: function(x, y, animation) {
var position = this.position;
x = (typeof x == 'number') ? x + position.x : null;
y = (typeof y == 'number') ? y + position.y : null;
return this.scrollTo(x, y, animation);
},
/**
* @private
*/
onTouchStart: function() {
this.isTouching = true;
this.stopAnimation();
},
/**
* @private
*/
onTouchEnd: function() {
var position = this.position;
this.isTouching = false;
if (!this.isDragging && this.snapToSlot()) {
this.fireEvent('scrollstart', this, position.x, position.y);
}
},
/**
* @private
*/
onDragStart: function(e) {
var direction = this.getDirection(),
absDeltaX = e.absDeltaX,
absDeltaY = e.absDeltaY,
directionLock = this.getDirectionLock(),
startPosition = this.startPosition,
flickStartPosition = this.flickStartPosition,
flickStartTime = this.flickStartTime,
lastDragPosition = this.lastDragPosition,
currentPosition = this.position,
dragDirection = this.dragDirection,
x = currentPosition.x,
y = currentPosition.y,
now = Ext.Date.now();
this.isDragging = true;
if (directionLock && direction !== 'both') {
if ((direction === 'horizontal' && absDeltaX > absDeltaY)
|| (direction === 'vertical' && absDeltaY > absDeltaX)) {
e.stopPropagation();
}
else {
this.isDragging = false;
return;
}
}
lastDragPosition.x = x;
lastDragPosition.y = y;
flickStartPosition.x = x;
flickStartPosition.y = y;
startPosition.x = x;
startPosition.y = y;
flickStartTime.x = now;
flickStartTime.y = now;
dragDirection.x = 0;
dragDirection.y = 0;
this.dragStartTime = now;
this.isDragging = true;
this.fireEvent('scrollstart', this, x, y);
},
/**
* @private
*/
onAxisDrag: function(axis, delta) {
if (!this.isAxisEnabled(axis)) {
return;
}
var flickStartPosition = this.flickStartPosition,
flickStartTime = this.flickStartTime,
lastDragPosition = this.lastDragPosition,
dragDirection = this.dragDirection,
old = this.position[axis],
min = this.getMinPosition()[axis],
max = this.getMaxPosition()[axis],
start = this.startPosition[axis],
last = lastDragPosition[axis],
current = start - delta,
lastDirection = dragDirection[axis],
restrictFactor = this.getOutOfBoundRestrictFactor(),
startMomentumResetTime = this.getStartMomentumResetTime(),
now = Ext.Date.now(),
distance;
if (current < min) {
current *= restrictFactor;
}
else if (current > max) {
distance = current - max;
current = max + distance * restrictFactor;
}
if (current > last) {
dragDirection[axis] = 1;
}
else if (current < last) {
dragDirection[axis] = -1;
}
if ((lastDirection !== 0 && (dragDirection[axis] !== lastDirection))
|| (now - flickStartTime[axis]) > startMomentumResetTime) {
flickStartPosition[axis] = old;
flickStartTime[axis] = now;
}
lastDragPosition[axis] = current;
},
/**
* @private
*/
onDrag: function(e) {
if (!this.isDragging) {
return;
}
var lastDragPosition = this.lastDragPosition;
this.onAxisDrag('x', e.deltaX);
this.onAxisDrag('y', e.deltaY);
this.scrollTo(lastDragPosition.x, lastDragPosition.y);
},
/**
* @private
*/
onDragEnd: function(e) {
var easingX, easingY;
if (!this.isDragging) {
return;
}
this.dragEndTime = Ext.Date.now();
this.onDrag(e);
this.isDragging = false;
easingX = this.getAnimationEasing('x', e);
easingY = this.getAnimationEasing('y', e);
if (easingX || easingY) {
this.getTranslatable().animate(easingX, easingY);
}
else {
this.onScrollEnd();
}
},
/**
* @private
*/
getAnimationEasing: function(axis, e) {
if (!this.isAxisEnabled(axis)) {
return null;
}
var currentPosition = this.position[axis],
minPosition = this.getMinPosition()[axis],
maxPosition = this.getMaxPosition()[axis],
maxAbsVelocity = this.getMaxAbsoluteVelocity(),
boundValue = null,
dragEndTime = this.dragEndTime,
velocity = e.flick.velocity[axis],
easing;
if (currentPosition < minPosition) {
boundValue = minPosition;
}
else if (currentPosition > maxPosition) {
boundValue = maxPosition;
}
// Out of bound, to be pulled back
if (boundValue !== null) {
easing = this.getBounceEasing()[axis];
easing.setConfig({
startTime: dragEndTime,
startValue: -currentPosition,
endValue: -boundValue
});
return easing;
}
if (velocity === 0) {
return null;
}
if (velocity < -maxAbsVelocity) {
velocity = -maxAbsVelocity;
}
else if (velocity > maxAbsVelocity) {
velocity = maxAbsVelocity;
}
if (Ext.browser.is.IE) {
velocity *= 2;
}
easing = this.getMomentumEasing()[axis];
easing.setConfig({
startTime: dragEndTime,
startValue: -currentPosition,
startVelocity: velocity * 1.5,
minMomentumValue: -maxPosition,
maxMomentumValue: 0
});
return easing;
},
/**
* @private
*/
onAnimationFrame: function(translatable, x, y) {
var position = this.position;
position.x = -x;
position.y = -y;
this.fireEvent('scroll', this, position.x, position.y);
},
/**
* @private
*/
onAnimationEnd: function() {
this.snapToBoundary();
this.onScrollEnd();
},
/**
* @private
* Stops the animation of the scroller at any time.
*/
stopAnimation: function() {
this.getTranslatable().stopAnimation();
},
/**
* @private
*/
onScrollEnd: function() {
var position = this.position;
if (this.isTouching || !this.snapToSlot()) {
this.fireEvent('scrollend', this, position.x, position.y);
}
},
/**
* @private
* @return {Boolean}
*/
snapToSlot: function() {
var snapX = this.getSnapPosition('x'),
snapY = this.getSnapPosition('y'),
easing = this.getSlotSnapEasing();
if (snapX !== null || snapY !== null) {
this.scrollTo(snapX, snapY, {
easingX: easing.x,
easingY: easing.y
});
return true;
}
return false;
},
/**
* @private
* @return {Number/null}
*/
getSnapPosition: function(axis) {
var snapSize = this.getSlotSnapSize()[axis],
snapPosition = null,
position, snapOffset, maxPosition, mod;
if (snapSize !== 0 && this.isAxisEnabled(axis)) {
position = this.position[axis];
snapOffset = this.getSlotSnapOffset()[axis];
maxPosition = this.getMaxPosition()[axis];
mod = Math.floor((position - snapOffset) % snapSize);
if (mod !== 0) {
if (position !== maxPosition) {
if (Math.abs(mod) > snapSize / 2) {
snapPosition = Math.min(maxPosition, position + ((mod > 0) ? snapSize - mod : mod - snapSize));
}
else {
snapPosition = position - mod;
}
}
else {
snapPosition = position - mod;
}
}
}
return snapPosition;
},
/**
* @private
*/
snapToBoundary: function() {
var position = this.position,
minPosition = this.getMinPosition(),
maxPosition = this.getMaxPosition(),
minX = minPosition.x,
minY = minPosition.y,
maxX = maxPosition.x,
maxY = maxPosition.y,
x = Math.round(position.x),
y = Math.round(position.y);
if (x < minX) {
x = minX;
}
else if (x > maxX) {
x = maxX;
}
if (y < minY) {
y = minY;
}
else if (y > maxY) {
y = maxY;
}
this.scrollTo(x, y);
},
destroy: function() {
var element = this.getElement(),
sizeMonitors = this.sizeMonitors,
container;
if (sizeMonitors) {
sizeMonitors.element.destroy();
sizeMonitors.container.destroy();
}
if (element && !element.isDestroyed) {
element.removeCls(this.cls);
container = this.getContainer();
if (container && !container.isDestroyed) {
container.removeCls(this.containerCls);
}
}
Ext.destroy(this.getTranslatable());
this.callParent(arguments);
}
}, function() {
//<deprecated product=touch since=2.0>
this.override({
constructor: function(config) {
var element, acceleration, slotSnapOffset, friction, springTension, minVelocity;
if (!config) {
config = {};
}
if (typeof config == 'string') {
config = {
direction: config
};
}
if (arguments.length == 2) {
//<debug warn>
Ext.Logger.deprecate("Passing element as the first argument is deprecated, pass it as the " +
"'element' property of the config object instead");
//</debug>
element = config;
config = arguments[1];
if (!config) {
config = {};
}
config.element = element;
}
/**
* @cfg {Number} acceleration A higher acceleration gives the scroller more initial velocity.
* @deprecated 2.0.0 Please use {@link #momentumEasing}.momentum.acceleration and {@link #momentumEasing}.bounce.acceleration instead.
*/
if (config.hasOwnProperty('acceleration')) {
acceleration = config.acceleration;
delete config.acceleration;
//<debug warn>
Ext.Logger.deprecate("'acceleration' config is deprecated, set momentumEasing.momentum.acceleration and momentumEasing.bounce.acceleration configs instead");
//</debug>
Ext.merge(config, {
momentumEasing: {
momentum: { acceleration: acceleration },
bounce: { acceleration: acceleration }
}
});
}
if (config.hasOwnProperty('snap')) {
config.slotSnapOffset = config.snap;
//<debug warn>
Ext.Logger.deprecate("'snap' config is deprecated, please use the 'slotSnapOffset' config instead");
//</debug>
}
/**
* @cfg {Number} friction The friction of the scroller. By raising this value the length that momentum scrolls
* becomes shorter. This value is best kept between 0 and 1.
* @deprecated 2.0.0 Please set the {@link #momentumEasing}.momentum.friction configuration instead
*/
if (config.hasOwnProperty('friction')) {
friction = config.friction;
delete config.friction;
//<debug warn>
Ext.Logger.deprecate("'friction' config is deprecated, set momentumEasing.momentum.friction config instead");
//</debug>
Ext.merge(config, {
momentumEasing: {
momentum: { friction: friction }
}
});
}
if (config.hasOwnProperty('springTension')) {
springTension = config.springTension;
delete config.springTension;
//<debug warn>
Ext.Logger.deprecate("'springTension' config is deprecated, set momentumEasing.momentum.springTension config instead");
//</debug>
Ext.merge(config, {
momentumEasing: {
momentum: { springTension: springTension }
}
});
}
if (config.hasOwnProperty('minVelocityForAnimation')) {
minVelocity = config.minVelocityForAnimation;
delete config.minVelocityForAnimation;
//<debug warn>
Ext.Logger.deprecate("'minVelocityForAnimation' config is deprecated, set momentumEasing.minVelocity config instead");
//</debug>
Ext.merge(config, {
momentumEasing: {
minVelocity: minVelocity
}
});
}
this.callOverridden(arguments);
},
scrollToAnimated: function(x, y, animation) {
//<debug warn>
Ext.Logger.deprecate("scrollToAnimated() is deprecated, please use `scrollTo()` and pass 'animation' as " +
"the third argument instead");
//</debug>
return this.scrollTo.apply(this, arguments);
},
scrollBy: function(x, y, animation) {
if (Ext.isObject(x)) {
//<debug warn>
Ext.Logger.deprecate("calling `scrollBy()` with an object of `x` and `y` properties is no longer supported. " +
"Please pass `x` and `y` values as two separate arguments instead");
//</debug>
y = x.y;
x = x.x;
}
return this.callOverridden([x, y, animation]);
},
/**
* Sets the offset of this scroller.
* @param {Object} offset The offset to move to.
* @param {Number} offset.x The x-axis offset.
* @param {Number} offset.y The y-axis offset.
* @deprecated 2.0.0 Please use `{@link #scrollTo}` instead.
* @return {Ext.scroll.Scroller} this
* @chainable
*/
setOffset: function(offset) {
return this.scrollToAnimated(-offset.x, -offset.y);
}
});
/**
* @method updateBoundary
* Updates the boundary information for this scroller.
* @return {Ext.scroll.Scroller} this
* @removed 2.0.0 Please use {@link #method-refresh} instead.
* @chainable
*/
// Ext.deprecateClassMethod('updateBoundary', 'refresh');
//</deprecated>
});
|
appcodechile/Rockola
|
webapp/touch/src/scroll/Scroller.js
|
JavaScript
|
mit
| 35,616
|
"use strict";
var Configuration = (function () {
function Configuration() {
}
return Configuration;
}());
exports.Configuration = Configuration;
//# sourceMappingURL=configuration.js.map
|
raymonddavis/Angular-SailsJs-SocketIo
|
web/node_modules/jasmine-spec-reporter/built/configuration.js
|
JavaScript
|
mit
| 198
|
/**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'widget', 'ar', {
'move': 'إضغط و إسحب للتحريك',
'label': '%1 widget' // MISSING
} );
|
er361/yii-zadanie-somnium
|
zadanie/protected/extensions/ckeditor/plugins/widget/lang/ar.js
|
JavaScript
|
bsd-3-clause
| 290
|
import "projection";
function hill(K) {
var L = 1 + K,
sinβ = Math.sin(1 / L),
β = asin(sinβ),
A = 2 * Math.sqrt(π / (B = π + 4 * β * L)),
B,
ρ0 = .5 * A * (L + Math.sqrt(K * (2 + K))),
K2 = K * K,
L2 = L * L;
function forward(λ, φ) {
var t = 1 - Math.sin(φ),
ρ,
ω;
if (t && t < 2) {
var θ = halfπ - φ, i = 25, δ;
do {
var sinθ = Math.sin(θ),
cosθ = Math.cos(θ),
β_β1 = β + Math.atan2(sinθ, L - cosθ),
C = 1 + L2 - 2 * L * cosθ;
θ -= δ = (θ - K2 * β - L * sinθ + C * β_β1 - .5 * t * B) / (2 * L * sinθ * β_β1);
} while (Math.abs(δ) > ε2 && --i > 0);
ρ = A * Math.sqrt(C);
ω = λ * β_β1 / π;
} else {
ρ = A * (K + t);
ω = λ * β / π;
}
return [
ρ * Math.sin(ω),
ρ0 - ρ * Math.cos(ω)
];
};
forward.invert = function(x, y) {
var ρ2 = x * x + (y -= ρ0) * y,
cosθ = (1 + L2 - ρ2 / (A * A)) / (2 * L),
θ = acos(cosθ),
sinθ = Math.sin(θ),
β_β1 = β + Math.atan2(sinθ, L - cosθ);
return [
asin(x / Math.sqrt(ρ2)) * π / β_β1,
asin(1 - 2 * (θ - K2 * β - L * sinθ + (1 + L2 - 2 * L * cosθ) * β_β1) / B)
];
};
return forward;
}
function hillProjection() {
var K = 1,
m = projectionMutator(hill),
p = m(K);
p.ratio = function(_) {
if (!arguments.length) return K;
return m(K = +_);
};
return p;
}
(d3.geo.hill = hillProjection).raw = hill;
|
jswiss/d3-geo-projection
|
src/hill.js
|
JavaScript
|
bsd-3-clause
| 1,593
|
// Load modules
var Path = require('path');
var Hoek = require('hoek');
var Ref = require('./ref');
var Errors = require('./errors');
var Alternatives = null; // Delay-loaded to prevent circular dependencies
var Cast = null;
// Declare internals
var internals = {};
internals.defaults = {
abortEarly: true,
convert: true,
allowUnknown: false,
skipFunctions: false,
stripUnknown: false,
language: {},
presence: 'optional'
// context: null
};
module.exports = internals.Any = function () {
this.isJoi = true;
this._type = 'any';
this._settings = null;
this._valids = new internals.Set();
this._invalids = new internals.Set();
this._tests = [];
this._refs = [];
this._flags = { /*
presence: 'optional', // optional, required, forbidden, ignore
allowOnly: false,
allowUnknown: undefined,
default: undefined,
forbidden: false,
encoding: undefined,
insensitive: false,
trim: false,
case: undefined // upper, lower
*/ };
this._description = null;
this._unit = null;
this._notes = [];
this._tags = [];
this._examples = [];
this._meta = [];
this._inner = {}; // Hash of arrays of immutable objects
};
internals.Any.prototype.isImmutable = true; // Prevents Hoek from deep cloning schema objects
internals.Any.prototype.clone = function () {
var obj = Object.create(Object.getPrototypeOf(this));
obj.isJoi = true;
obj._type = this._type;
obj._settings = internals.concatSettings(this._settings);
obj._valids = Hoek.clone(this._valids);
obj._invalids = Hoek.clone(this._invalids);
obj._tests = this._tests.slice();
obj._refs = this._refs.slice();
obj._flags = Hoek.clone(this._flags);
obj._description = this._description;
obj._unit = this._unit;
obj._notes = this._notes.slice();
obj._tags = this._tags.slice();
obj._examples = this._examples.slice();
obj._meta = this._meta.slice();
obj._inner = {};
var inners = Object.keys(this._inner);
for (var i = 0, il = inners.length; i < il; ++i) {
var key = inners[i];
obj._inner[key] = this._inner[key] ? this._inner[key].slice() : null;
}
return obj;
};
internals.Any.prototype.concat = function (schema) {
Hoek.assert(schema && schema.isJoi, 'Invalid schema object');
Hoek.assert(schema._type === 'any' || schema._type === this._type, 'Cannot merge with another type:', schema._type);
var obj = this.clone();
obj._settings = obj._settings ? internals.concatSettings(obj._settings, schema._settings) : schema._settings;
obj._valids.merge(schema._valids, schema._invalids);
obj._invalids.merge(schema._invalids, schema._valids);
obj._tests = obj._tests.concat(schema._tests);
obj._refs = obj._refs.concat(schema._refs);
Hoek.merge(obj._flags, schema._flags);
obj._description = schema._description || obj._description;
obj._unit = schema._unit || obj._unit;
obj._notes = obj._notes.concat(schema._notes);
obj._tags = obj._tags.concat(schema._tags);
obj._examples = obj._examples.concat(schema._examples);
obj._meta = obj._meta.concat(schema._meta);
var inners = Object.keys(schema._inner);
for (var i = 0, il = inners.length; i < il; ++i) {
var key = inners[i];
if (schema._inner[key]) {
obj._inner[key] = (obj._inner[key] ? obj._inner[key].concat(schema._inner[key]) : schema._inner[key].slice());
}
}
return obj;
};
internals.Any.prototype._test = function (name, arg, func) {
Hoek.assert(!this._flags.allowOnly, 'Cannot define rules when valid values specified');
var obj = this.clone();
obj._tests.push({ func: func, name: name, arg: arg });
return obj;
};
internals.Any.prototype.options = function (options) {
Hoek.assert(!options.context, 'Cannot override context');
var obj = this.clone();
obj._settings = internals.concatSettings(obj._settings, options);
return obj;
};
internals.Any.prototype.strict = function () {
var obj = this.clone();
obj._settings = obj._settings || {};
obj._settings.convert = false;
return obj;
};
internals.Any.prototype._allow = function () {
var values = Hoek.flatten(Array.prototype.slice.call(arguments));
for (var i = 0, il = values.length; i < il; ++i) {
var value = values[i];
this._invalids.remove(value);
this._valids.add(value, this._refs);
}
};
internals.Any.prototype.allow = function () {
var obj = this.clone();
obj._allow.apply(obj, arguments);
return obj;
};
internals.Any.prototype.valid = internals.Any.prototype.equal = function () {
Hoek.assert(!this._tests.length, 'Cannot set valid values when rules specified');
var obj = this.allow.apply(this, arguments);
obj._flags.allowOnly = true;
return obj;
};
internals.Any.prototype.invalid = internals.Any.prototype.not = function (value) {
var obj = this.clone();
var values = Hoek.flatten(Array.prototype.slice.call(arguments));
for (var i = 0, il = values.length; i < il; ++i) {
var value = values[i];
obj._valids.remove(value);
obj._invalids.add(value, this._refs);
}
return obj;
};
internals.Any.prototype.required = internals.Any.prototype.exist = function () {
var obj = this.clone();
obj._flags.presence = 'required';
return obj;
};
internals.Any.prototype.optional = function () {
var obj = this.clone();
obj._flags.presence = 'optional';
return obj;
};
internals.Any.prototype.forbidden = function () {
var obj = this.clone();
obj._flags.presence = 'forbidden';
return obj;
};
internals.Any.prototype.default = function (value) {
var obj = this.clone();
obj._flags.default = value;
Ref.push(obj._refs, value);
return obj;
};
internals.Any.prototype.when = function (ref, options) {
Hoek.assert(options && typeof options === 'object', 'Invalid options');
Hoek.assert(options.then !== undefined || options.otherwise !== undefined, 'options must have at least one of "then" or "otherwise"');
Cast = Cast || require('./cast');
var then = options.then ? this.concat(Cast.schema(options.then)) : this;
var otherwise = options.otherwise ? this.concat(Cast.schema(options.otherwise)) : this;
Alternatives = Alternatives || require('./alternatives');
var obj = Alternatives.when(ref, { is: options.is, then: then, otherwise: otherwise });
obj._flags.presence = 'ignore';
return obj;
};
internals.Any.prototype.description = function (desc) {
Hoek.assert(desc && typeof desc === 'string', 'Description must be a non-empty string');
var obj = this.clone();
obj._description = desc;
return obj;
};
internals.Any.prototype.notes = function (notes) {
Hoek.assert(notes && (typeof notes === 'string' || Array.isArray(notes)), 'Notes must be a non-empty string or array');
var obj = this.clone();
obj._notes = obj._notes.concat(notes);
return obj;
};
internals.Any.prototype.tags = function (tags) {
Hoek.assert(tags && (typeof tags === 'string' || Array.isArray(tags)), 'Tags must be a non-empty string or array');
var obj = this.clone();
obj._tags = obj._tags.concat(tags);
return obj;
};
internals.Any.prototype.meta = function (meta) {
Hoek.assert(meta !== undefined, 'Meta cannot be undefined');
var obj = this.clone();
obj._meta = obj._meta.concat(meta);
return obj;
};
internals.Any.prototype.example = function (value) {
Hoek.assert(arguments.length, 'Missing example');
var result = this._validate(value, null, internals.defaults);
Hoek.assert(!result.errors, 'Bad example:', result.errors && Errors.process(result.errors, value));
var obj = this.clone();
obj._examples = obj._examples.concat(value);
return obj;
};
internals.Any.prototype.unit = function (name) {
Hoek.assert(name && typeof name === 'string', 'Unit name must be a non-empty string');
var obj = this.clone();
obj._unit = name;
return obj;
};
internals.Any.prototype._validate = function (value, state, options, reference) {
var self = this;
// Setup state and settings
state = state || { key: '', path: '', parent: null, reference: reference };
if (this._settings) {
options = internals.concatSettings(options, this._settings);
}
var errors = [];
var finish = function () {
return {
value: (value !== undefined) ? value : (Ref.isRef(self._flags.default) ? self._flags.default(state.parent, options) : self._flags.default),
errors: errors.length ? errors : null
};
};
// Check presence requirements
var presence = this._flags.presence || options.presence;
if (presence === 'optional') {
if (value === undefined) {
return finish();
}
}
else if (presence === 'required' &&
value === undefined) {
errors.push(Errors.create('any.required', null, state, options));
return finish();
}
else if (presence === 'forbidden') {
if (value === undefined) {
return finish();
}
errors.push(Errors.create('any.unknown', null, state, options));
return finish();
}
// Check allowed and denied values using the original value
if (this._valids.has(value, state, options, this._flags.insensitive)) {
return finish();
}
if (this._invalids.has(value, state, options, this._flags.insensitive)) {
errors.push(Errors.create(value === '' ? 'any.empty' : 'any.invalid', null, state, options));
if (options.abortEarly ||
value === undefined) { // No reason to keep validating missing value
return finish();
}
}
// Convert value and validate type
if (this._base) {
var base = this._base.call(this, value, state, options);
if (base.errors) {
value = base.value;
errors = errors.concat(base.errors);
return finish(); // Base error always aborts early
}
if (base.value !== value) {
value = base.value;
// Check allowed and denied values using the converted value
if (this._valids.has(value, state, options, this._flags.insensitive)) {
return finish();
}
if (this._invalids.has(value, state, options, this._flags.insensitive)) {
errors.push(Errors.create('any.invalid', null, state, options));
if (options.abortEarly) {
return finish();
}
}
}
}
// Required values did not match
if (this._flags.allowOnly) {
errors.push(Errors.create('any.allowOnly', { valids: this._valids.toString(false) }, state, options));
if (options.abortEarly) {
return finish();
}
}
// Helper.validate tests
for (var i = 0, il = this._tests.length; i < il; ++i) {
var test = this._tests[i];
var err = test.func.call(this, value, state, options);
if (err) {
errors.push(err);
if (options.abortEarly) {
return finish();
}
}
}
return finish();
};
internals.Any.prototype._validateWithOptions = function (value, options, callback) {
var settings = internals.concatSettings(internals.defaults, options);
var result = this._validate(value, null, settings);
var errors = Errors.process(result.errors, value);
if (callback) {
return callback(errors, result.value);
}
return { error: errors, value: result.value };
};
internals.Any.prototype.validate = function (value, callback) {
var result = this._validate(value, null, internals.defaults);
var errors = Errors.process(result.errors, value);
if (callback) {
return callback(errors, result.value);
}
return { error: errors, value: result.value };
};
internals.Any.prototype.describe = function () {
var description = {
type: this._type
};
if (Object.keys(this._flags).length) {
description.flags = this._flags;
}
if (this._description) {
description.description = this._description;
}
if (this._notes.length) {
description.notes = this._notes;
}
if (this._tags.length) {
description.tags = this._tags;
}
if (this._meta.length) {
description.meta = this._meta;
}
if (this._examples.length) {
description.examples = this._examples;
}
if (this._unit) {
description.unit = this._unit;
}
var valids = this._valids.values();
if (valids.length) {
description.valids = valids;
}
var invalids = this._invalids.values();
if (invalids.length) {
description.invalids = invalids;
}
description.rules = [];
for (var i = 0, il = this._tests.length; i < il; ++i) {
var validator = this._tests[i];
var item = { name: validator.name };
if (validator.arg !== void 0) {
item.arg = validator.arg;
}
description.rules.push(item);
}
if (!description.rules.length) {
delete description.rules;
}
return description;
};
internals.Any.prototype.label = function (name) {
Hoek.assert(name && typeof name === 'string', 'Label name must be a non-empty string');
var obj = this.clone();
var options = { language: { label: name } };
// If language.label is set, it should override this label
obj._settings = internals.concatSettings(options, obj._settings);
return obj;
};
// Set
internals.Set = function () {
this._set = [];
};
internals.Set.prototype.add = function (value, refs) {
Hoek.assert(value === null || value === undefined || value instanceof Date || Buffer.isBuffer(value) || Ref.isRef(value) || (typeof value !== 'function' && typeof value !== 'object'), 'Value cannot be an object or function');
if (typeof value !== 'function' &&
this.has(value, null, null, false)) {
return;
}
Ref.push(refs, value);
this._set.push(value);
};
internals.Set.prototype.merge = function (add, remove) {
for (var i = 0, il = add._set.length; i < il; ++i) {
this.add(add._set[i]);
}
for (i = 0, il = remove._set.length; i < il; ++i) {
this.remove(remove._set[i]);
}
};
internals.Set.prototype.remove = function (value) {
this._set = this._set.filter(function (item) {
return value !== item;
});
};
internals.Set.prototype.has = function (value, state, options, insensitive) {
for (var i = 0, il = this._set.length; i < il; ++i) {
var item = this._set[i];
if (Ref.isRef(item)) {
item = item(state.reference || state.parent, options);
}
if (typeof value !== typeof item) {
continue;
}
if (value === item ||
(value instanceof Date && item instanceof Date && value.getTime() === item.getTime()) ||
(insensitive && typeof value === 'string' && value.toLowerCase() === item.toLowerCase()) ||
(Buffer.isBuffer(value) && Buffer.isBuffer(item) && value.length === item.length && value.toString('binary') === item.toString('binary'))) {
return true;
}
}
return false;
};
internals.Set.prototype.values = function () {
return this._set.slice();
};
internals.Set.prototype.toString = function (includeUndefined) {
var list = '';
for (var i = 0, il = this._set.length; i < il; ++i) {
var item = this._set[i];
if (item !== undefined || includeUndefined) {
list += (list ? ', ' : '') + internals.stringify(item);
}
}
return list;
};
internals.stringify = function (value) {
if (value === undefined) {
return 'undefined';
}
if (value === null) {
return 'null';
}
if (typeof value === 'string') {
return value;
}
return value.toString();
};
internals.concatSettings = function (target, source) {
// Used to avoid cloning context
if (!target &&
!source) {
return null;
}
var obj = {};
if (target) {
var tKeys = Object.keys(target);
for (var i = 0, il = tKeys.length; i < il; ++i) {
var key = tKeys[i];
obj[key] = target[key];
}
}
if (source) {
var sKeys = Object.keys(source);
for (var j = 0, jl = sKeys.length; j < jl; ++j) {
var key = sKeys[j];
if (key !== 'language' ||
!obj.hasOwnProperty(key)) {
obj[key] = source[key];
}
else {
obj[key] = Hoek.applyToDefaults(obj[key], source[key]);
}
}
}
return obj;
};
|
annefried/discanno
|
src/main/webapp/node_modules/joi/lib/any.js
|
JavaScript
|
gpl-2.0
| 17,176
|
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("javascript", function(config, parserConfig) {
var indentUnit = config.indentUnit;
var statementIndent = parserConfig.statementIndent;
var jsonldMode = parserConfig.jsonld;
var jsonMode = parserConfig.json || jsonldMode;
var isTS = parserConfig.typescript;
var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
// Tokenizer
var keywords = function(){
function kw(type) {return {type: type, style: "keyword"};}
var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d");
var operator = kw("operator"), atom = {type: "atom", style: "atom"};
return {
"if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
"return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C,
"debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"),
"function": kw("function"), "catch": kw("catch"),
"for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
"in": operator, "typeof": operator, "instanceof": operator,
"true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
"this": kw("this"), "class": kw("class"), "super": kw("atom"),
"yield": C, "export": kw("export"), "import": kw("import"), "extends": C,
"await": C
};
}();
var isOperatorChar = /[+\-*&%=<>!?|~^@]/;
var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
function readRegexp(stream) {
var escaped = false, next, inSet = false;
while ((next = stream.next()) != null) {
if (!escaped) {
if (next == "/" && !inSet) return;
if (next == "[") inSet = true;
else if (inSet && next == "]") inSet = false;
}
escaped = !escaped && next == "\\";
}
}
// Used as scratch variables to communicate multiple values without
// consing up tons of objects.
var type, content;
function ret(tp, style, cont) {
type = tp; content = cont;
return style;
}
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == '"' || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
} else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) {
return ret("number", "number");
} else if (ch == "." && stream.match("..")) {
return ret("spread", "meta");
} else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
return ret(ch);
} else if (ch == "=" && stream.eat(">")) {
return ret("=>", "operator");
} else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) {
return ret("number", "number");
} else if (/\d/.test(ch)) {
stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/);
return ret("number", "number");
} else if (ch == "/") {
if (stream.eat("*")) {
state.tokenize = tokenComment;
return tokenComment(stream, state);
} else if (stream.eat("/")) {
stream.skipToEnd();
return ret("comment", "comment");
} else if (expressionAllowed(stream, state, 1)) {
readRegexp(stream);
stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);
return ret("regexp", "string-2");
} else {
stream.eat("=");
return ret("operator", "operator", stream.current());
}
} else if (ch == "`") {
state.tokenize = tokenQuasi;
return tokenQuasi(stream, state);
} else if (ch == "#" && stream.peek() == "!") {
stream.skipToEnd();
return ret("meta", "meta");
} else if (ch == "#" && stream.eatWhile(wordRE)) {
return ret("variable", "property")
} else if (ch == "<" && stream.match("!--") ||
(ch == "-" && stream.match("->") && !/\S/.test(stream.string.slice(0, stream.start)))) {
stream.skipToEnd()
return ret("comment", "comment")
} else if (isOperatorChar.test(ch)) {
if (ch != ">" || !state.lexical || state.lexical.type != ">") {
if (stream.eat("=")) {
if (ch == "!" || ch == "=") stream.eat("=")
} else if (/[<>*+\-]/.test(ch)) {
stream.eat(ch)
if (ch == ">") stream.eat(ch)
}
}
if (ch == "?" && stream.eat(".")) return ret(".")
return ret("operator", "operator", stream.current());
} else if (wordRE.test(ch)) {
stream.eatWhile(wordRE);
var word = stream.current()
if (state.lastType != ".") {
if (keywords.propertyIsEnumerable(word)) {
var kw = keywords[word]
return ret(kw.type, kw.style, word)
}
if (word == "async" && stream.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/, false))
return ret("async", "keyword", word)
}
return ret("variable", "variable", word)
}
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, next;
if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
state.tokenize = tokenBase;
return ret("jsonld-keyword", "meta");
}
while ((next = stream.next()) != null) {
if (next == quote && !escaped) break;
escaped = !escaped && next == "\\";
}
if (!escaped) state.tokenize = tokenBase;
return ret("string", "string");
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return ret("comment", "comment");
}
function tokenQuasi(stream, state) {
var escaped = false, next;
while ((next = stream.next()) != null) {
if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
state.tokenize = tokenBase;
break;
}
escaped = !escaped && next == "\\";
}
return ret("quasi", "string-2", stream.current());
}
var brackets = "([{}])";
// This is a crude lookahead trick to try and notice that we're
// parsing the argument patterns for a fat-arrow function before we
// actually hit the arrow token. It only works if the arrow is on
// the same line as the arguments and there's no strange noise
// (comments) in between. Fallback is to only notice when we hit the
// arrow, and not declare the arguments as locals for the arrow
// body.
function findFatArrow(stream, state) {
if (state.fatArrowAt) state.fatArrowAt = null;
var arrow = stream.string.indexOf("=>", stream.start);
if (arrow < 0) return;
if (isTS) { // Try to skip TypeScript return type declarations after the arguments
var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow))
if (m) arrow = m.index
}
var depth = 0, sawSomething = false;
for (var pos = arrow - 1; pos >= 0; --pos) {
var ch = stream.string.charAt(pos);
var bracket = brackets.indexOf(ch);
if (bracket >= 0 && bracket < 3) {
if (!depth) { ++pos; break; }
if (--depth == 0) { if (ch == "(") sawSomething = true; break; }
} else if (bracket >= 3 && bracket < 6) {
++depth;
} else if (wordRE.test(ch)) {
sawSomething = true;
} else if (/["'\/`]/.test(ch)) {
for (;; --pos) {
if (pos == 0) return
var next = stream.string.charAt(pos - 1)
if (next == ch && stream.string.charAt(pos - 2) != "\\") { pos--; break }
}
} else if (sawSomething && !depth) {
++pos;
break;
}
}
if (sawSomething && !depth) state.fatArrowAt = pos;
}
// Parser
var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
function JSLexical(indented, column, type, align, prev, info) {
this.indented = indented;
this.column = column;
this.type = type;
this.prev = prev;
this.info = info;
if (align != null) this.align = align;
}
function inScope(state, varname) {
for (var v = state.localVars; v; v = v.next)
if (v.name == varname) return true;
for (var cx = state.context; cx; cx = cx.prev) {
for (var v = cx.vars; v; v = v.next)
if (v.name == varname) return true;
}
}
function parseJS(state, style, type, content, stream) {
var cc = state.cc;
// Communicate our context to the combinators.
// (Less wasteful than consing up a hundred closures on every call.)
cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = true;
while(true) {
var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
if (combinator(type, content)) {
while(cc.length && cc[cc.length - 1].lex)
cc.pop()();
if (cx.marked) return cx.marked;
if (type == "variable" && inScope(state, content)) return "variable-2";
return style;
}
}
}
// Combinator utils
var cx = {state: null, column: null, marked: null, cc: null};
function pass() {
for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
}
function cont() {
pass.apply(null, arguments);
return true;
}
function inList(name, list) {
for (var v = list; v; v = v.next) if (v.name == name) return true
return false;
}
function register(varname) {
var state = cx.state;
cx.marked = "def";
if (state.context) {
if (state.lexical.info == "var" && state.context && state.context.block) {
// FIXME function decls are also not block scoped
var newContext = registerVarScoped(varname, state.context)
if (newContext != null) {
state.context = newContext
return
}
} else if (!inList(varname, state.localVars)) {
state.localVars = new Var(varname, state.localVars)
return
}
}
// Fall through means this is global
if (parserConfig.globalVars && !inList(varname, state.globalVars))
state.globalVars = new Var(varname, state.globalVars)
}
function registerVarScoped(varname, context) {
if (!context) {
return null
} else if (context.block) {
var inner = registerVarScoped(varname, context.prev)
if (!inner) return null
if (inner == context.prev) return context
return new Context(inner, context.vars, true)
} else if (inList(varname, context.vars)) {
return context
} else {
return new Context(context.prev, new Var(varname, context.vars), false)
}
}
function isModifier(name) {
return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"
}
// Combinators
function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block }
function Var(name, next) { this.name = name; this.next = next }
var defaultVars = new Var("this", new Var("arguments", null))
function pushcontext() {
cx.state.context = new Context(cx.state.context, cx.state.localVars, false)
cx.state.localVars = defaultVars
}
function pushblockcontext() {
cx.state.context = new Context(cx.state.context, cx.state.localVars, true)
cx.state.localVars = null
}
function popcontext() {
cx.state.localVars = cx.state.context.vars
cx.state.context = cx.state.context.prev
}
popcontext.lex = true
function pushlex(type, info) {
var result = function() {
var state = cx.state, indent = state.indented;
if (state.lexical.type == "stat") indent = state.lexical.indented;
else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
indent = outer.indented;
state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
};
result.lex = true;
return result;
}
function poplex() {
var state = cx.state;
if (state.lexical.prev) {
if (state.lexical.type == ")")
state.indented = state.lexical.indented;
state.lexical = state.lexical.prev;
}
}
poplex.lex = true;
function expect(wanted) {
function exp(type) {
if (type == wanted) return cont();
else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass();
else return cont(exp);
};
return exp;
}
function statement(type, value) {
if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex);
if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex);
if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex);
if (type == "debugger") return cont(expect(";"));
if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext);
if (type == ";") return cont();
if (type == "if") {
if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
cx.state.cc.pop()();
return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse);
}
if (type == "function") return cont(functiondef);
if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
if (type == "class" || (isTS && value == "interface")) {
cx.marked = "keyword"
return cont(pushlex("form", type == "class" ? type : value), className, poplex)
}
if (type == "variable") {
if (isTS && value == "declare") {
cx.marked = "keyword"
return cont(statement)
} else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) {
cx.marked = "keyword"
if (value == "enum") return cont(enumdef);
else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";"));
else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex)
} else if (isTS && value == "namespace") {
cx.marked = "keyword"
return cont(pushlex("form"), expression, statement, poplex)
} else if (isTS && value == "abstract") {
cx.marked = "keyword"
return cont(statement)
} else {
return cont(pushlex("stat"), maybelabel);
}
}
if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext,
block, poplex, poplex, popcontext);
if (type == "case") return cont(expression, expect(":"));
if (type == "default") return cont(expect(":"));
if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext);
if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
if (type == "async") return cont(statement)
if (value == "@") return cont(expression, statement)
return pass(pushlex("stat"), expression, expect(";"), poplex);
}
function maybeCatchBinding(type) {
if (type == "(") return cont(funarg, expect(")"))
}
function expression(type, value) {
return expressionInner(type, value, false);
}
function expressionNoComma(type, value) {
return expressionInner(type, value, true);
}
function parenExpr(type) {
if (type != "(") return pass()
return cont(pushlex(")"), maybeexpression, expect(")"), poplex)
}
function expressionInner(type, value, noComma) {
if (cx.state.fatArrowAt == cx.stream.start) {
var body = noComma ? arrowBodyNoComma : arrowBody;
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);
else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
}
var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
if (type == "function") return cont(functiondef, maybeop);
if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); }
if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression);
if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
if (type == "{") return contCommasep(objprop, "}", null, maybeop);
if (type == "quasi") return pass(quasi, maybeop);
if (type == "new") return cont(maybeTarget(noComma));
if (type == "import") return cont(expression);
return cont();
}
function maybeexpression(type) {
if (type.match(/[;\}\)\],]/)) return pass();
return pass(expression);
}
function maybeoperatorComma(type, value) {
if (type == ",") return cont(maybeexpression);
return maybeoperatorNoComma(type, value, false);
}
function maybeoperatorNoComma(type, value, noComma) {
var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
var expr = noComma == false ? expression : expressionNoComma;
if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
if (type == "operator") {
if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me);
if (isTS && value == "<" && cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false))
return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me);
if (value == "?") return cont(expression, expect(":"), expr);
return cont(expr);
}
if (type == "quasi") { return pass(quasi, me); }
if (type == ";") return;
if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
if (type == ".") return cont(property, me);
if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) }
if (type == "regexp") {
cx.state.lastType = cx.marked = "operator"
cx.stream.backUp(cx.stream.pos - cx.stream.start - 1)
return cont(expr)
}
}
function quasi(type, value) {
if (type != "quasi") return pass();
if (value.slice(value.length - 2) != "${") return cont(quasi);
return cont(expression, continueQuasi);
}
function continueQuasi(type) {
if (type == "}") {
cx.marked = "string-2";
cx.state.tokenize = tokenQuasi;
return cont(quasi);
}
}
function arrowBody(type) {
findFatArrow(cx.stream, cx.state);
return pass(type == "{" ? statement : expression);
}
function arrowBodyNoComma(type) {
findFatArrow(cx.stream, cx.state);
return pass(type == "{" ? statement : expressionNoComma);
}
function maybeTarget(noComma) {
return function(type) {
if (type == ".") return cont(noComma ? targetNoComma : target);
else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma)
else return pass(noComma ? expressionNoComma : expression);
};
}
function target(_, value) {
if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
}
function targetNoComma(_, value) {
if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
}
function maybelabel(type) {
if (type == ":") return cont(poplex, statement);
return pass(maybeoperatorComma, expect(";"), poplex);
}
function property(type) {
if (type == "variable") {cx.marked = "property"; return cont();}
}
function objprop(type, value) {
if (type == "async") {
cx.marked = "property";
return cont(objprop);
} else if (type == "variable" || cx.style == "keyword") {
cx.marked = "property";
if (value == "get" || value == "set") return cont(getterSetter);
var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params
if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false)))
cx.state.fatArrowAt = cx.stream.pos + m[0].length
return cont(afterprop);
} else if (type == "number" || type == "string") {
cx.marked = jsonldMode ? "property" : (cx.style + " property");
return cont(afterprop);
} else if (type == "jsonld-keyword") {
return cont(afterprop);
} else if (isTS && isModifier(value)) {
cx.marked = "keyword"
return cont(objprop)
} else if (type == "[") {
return cont(expression, maybetype, expect("]"), afterprop);
} else if (type == "spread") {
return cont(expressionNoComma, afterprop);
} else if (value == "*") {
cx.marked = "keyword";
return cont(objprop);
} else if (type == ":") {
return pass(afterprop)
}
}
function getterSetter(type) {
if (type != "variable") return pass(afterprop);
cx.marked = "property";
return cont(functiondef);
}
function afterprop(type) {
if (type == ":") return cont(expressionNoComma);
if (type == "(") return pass(functiondef);
}
function commasep(what, end, sep) {
function proceed(type, value) {
if (sep ? sep.indexOf(type) > -1 : type == ",") {
var lex = cx.state.lexical;
if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
return cont(function(type, value) {
if (type == end || value == end) return pass()
return pass(what)
}, proceed);
}
if (type == end || value == end) return cont();
if (sep && sep.indexOf(";") > -1) return pass(what)
return cont(expect(end));
}
return function(type, value) {
if (type == end || value == end) return cont();
return pass(what, proceed);
};
}
function contCommasep(what, end, info) {
for (var i = 3; i < arguments.length; i++)
cx.cc.push(arguments[i]);
return cont(pushlex(end, info), commasep(what, end), poplex);
}
function block(type) {
if (type == "}") return cont();
return pass(statement, block);
}
function maybetype(type, value) {
if (isTS) {
if (type == ":") return cont(typeexpr);
if (value == "?") return cont(maybetype);
}
}
function maybetypeOrIn(type, value) {
if (isTS && (type == ":" || value == "in")) return cont(typeexpr)
}
function mayberettype(type) {
if (isTS && type == ":") {
if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr)
else return cont(typeexpr)
}
}
function isKW(_, value) {
if (value == "is") {
cx.marked = "keyword"
return cont()
}
}
function typeexpr(type, value) {
if (value == "keyof" || value == "typeof" || value == "infer") {
cx.marked = "keyword"
return cont(value == "typeof" ? expressionNoComma : typeexpr)
}
if (type == "variable" || value == "void") {
cx.marked = "type"
return cont(afterType)
}
if (value == "|" || value == "&") return cont(typeexpr)
if (type == "string" || type == "number" || type == "atom") return cont(afterType);
if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType)
if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType)
if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType)
if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr)
}
function maybeReturnType(type) {
if (type == "=>") return cont(typeexpr)
}
function typeprop(type, value) {
if (type == "variable" || cx.style == "keyword") {
cx.marked = "property"
return cont(typeprop)
} else if (value == "?" || type == "number" || type == "string") {
return cont(typeprop)
} else if (type == ":") {
return cont(typeexpr)
} else if (type == "[") {
return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop)
} else if (type == "(") {
return pass(functiondecl, typeprop)
}
}
function typearg(type, value) {
if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg)
if (type == ":") return cont(typeexpr)
if (type == "spread") return cont(typearg)
return pass(typeexpr)
}
function afterType(type, value) {
if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
if (value == "|" || type == "." || value == "&") return cont(typeexpr)
if (type == "[") return cont(typeexpr, expect("]"), afterType)
if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) }
if (value == "?") return cont(typeexpr, expect(":"), typeexpr)
}
function maybeTypeArgs(_, value) {
if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
}
function typeparam() {
return pass(typeexpr, maybeTypeDefault)
}
function maybeTypeDefault(_, value) {
if (value == "=") return cont(typeexpr)
}
function vardef(_, value) {
if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)}
return pass(pattern, maybetype, maybeAssign, vardefCont);
}
function pattern(type, value) {
if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) }
if (type == "variable") { register(value); return cont(); }
if (type == "spread") return cont(pattern);
if (type == "[") return contCommasep(eltpattern, "]");
if (type == "{") return contCommasep(proppattern, "}");
}
function proppattern(type, value) {
if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
register(value);
return cont(maybeAssign);
}
if (type == "variable") cx.marked = "property";
if (type == "spread") return cont(pattern);
if (type == "}") return pass();
if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern);
return cont(expect(":"), pattern, maybeAssign);
}
function eltpattern() {
return pass(pattern, maybeAssign)
}
function maybeAssign(_type, value) {
if (value == "=") return cont(expressionNoComma);
}
function vardefCont(type) {
if (type == ",") return cont(vardef);
}
function maybeelse(type, value) {
if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
}
function forspec(type, value) {
if (value == "await") return cont(forspec);
if (type == "(") return cont(pushlex(")"), forspec1, poplex);
}
function forspec1(type) {
if (type == "var") return cont(vardef, forspec2);
if (type == "variable") return cont(forspec2);
return pass(forspec2)
}
function forspec2(type, value) {
if (type == ")") return cont()
if (type == ";") return cont(forspec2)
if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression, forspec2) }
return pass(expression, forspec2)
}
function functiondef(type, value) {
if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
if (type == "variable") {register(value); return cont(functiondef);}
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext);
if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef)
}
function functiondecl(type, value) {
if (value == "*") {cx.marked = "keyword"; return cont(functiondecl);}
if (type == "variable") {register(value); return cont(functiondecl);}
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext);
if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl)
}
function typename(type, value) {
if (type == "keyword" || type == "variable") {
cx.marked = "type"
return cont(typename)
} else if (value == "<") {
return cont(pushlex(">"), commasep(typeparam, ">"), poplex)
}
}
function funarg(type, value) {
if (value == "@") cont(expression, funarg)
if (type == "spread") return cont(funarg);
if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); }
if (isTS && type == "this") return cont(maybetype, maybeAssign)
return pass(pattern, maybetype, maybeAssign);
}
function classExpression(type, value) {
// Class expressions may have an optional name.
if (type == "variable") return className(type, value);
return classNameAfter(type, value);
}
function className(type, value) {
if (type == "variable") {register(value); return cont(classNameAfter);}
}
function classNameAfter(type, value) {
if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter)
if (value == "extends" || value == "implements" || (isTS && type == ",")) {
if (value == "implements") cx.marked = "keyword";
return cont(isTS ? typeexpr : expression, classNameAfter);
}
if (type == "{") return cont(pushlex("}"), classBody, poplex);
}
function classBody(type, value) {
if (type == "async" ||
(type == "variable" &&
(value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) &&
cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) {
cx.marked = "keyword";
return cont(classBody);
}
if (type == "variable" || cx.style == "keyword") {
cx.marked = "property";
return cont(classfield, classBody);
}
if (type == "number" || type == "string") return cont(classfield, classBody);
if (type == "[")
return cont(expression, maybetype, expect("]"), classfield, classBody)
if (value == "*") {
cx.marked = "keyword";
return cont(classBody);
}
if (isTS && type == "(") return pass(functiondecl, classBody)
if (type == ";" || type == ",") return cont(classBody);
if (type == "}") return cont();
if (value == "@") return cont(expression, classBody)
}
function classfield(type, value) {
if (value == "?") return cont(classfield)
if (type == ":") return cont(typeexpr, maybeAssign)
if (value == "=") return cont(expressionNoComma)
var context = cx.state.lexical.prev, isInterface = context && context.info == "interface"
return pass(isInterface ? functiondecl : functiondef)
}
function afterExport(type, value) {
if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";"));
return pass(statement);
}
function exportField(type, value) {
if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); }
if (type == "variable") return pass(expressionNoComma, exportField);
}
function afterImport(type) {
if (type == "string") return cont();
if (type == "(") return pass(expression);
return pass(importSpec, maybeMoreImports, maybeFrom);
}
function importSpec(type, value) {
if (type == "{") return contCommasep(importSpec, "}");
if (type == "variable") register(value);
if (value == "*") cx.marked = "keyword";
return cont(maybeAs);
}
function maybeMoreImports(type) {
if (type == ",") return cont(importSpec, maybeMoreImports)
}
function maybeAs(_type, value) {
if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
}
function maybeFrom(_type, value) {
if (value == "from") { cx.marked = "keyword"; return cont(expression); }
}
function arrayLiteral(type) {
if (type == "]") return cont();
return pass(commasep(expressionNoComma, "]"));
}
function enumdef() {
return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex)
}
function enummember() {
return pass(pattern, maybeAssign);
}
function isContinuedStatement(state, textAfter) {
return state.lastType == "operator" || state.lastType == "," ||
isOperatorChar.test(textAfter.charAt(0)) ||
/[,.]/.test(textAfter.charAt(0));
}
function expressionAllowed(stream, state, backUp) {
return state.tokenize == tokenBase &&
/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) ||
(state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))
}
// Interface
return {
startState: function(basecolumn) {
var state = {
tokenize: tokenBase,
lastType: "sof",
cc: [],
lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
localVars: parserConfig.localVars,
context: parserConfig.localVars && new Context(null, null, false),
indented: basecolumn || 0
};
if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
state.globalVars = parserConfig.globalVars;
return state;
},
token: function(stream, state) {
if (stream.sol()) {
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = false;
state.indented = stream.indentation();
findFatArrow(stream, state);
}
if (state.tokenize != tokenComment && stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
if (type == "comment") return style;
state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
return parseJS(state, style, type, content, stream);
},
indent: function(state, textAfter) {
if (state.tokenize == tokenComment) return CodeMirror.Pass;
if (state.tokenize != tokenBase) return 0;
var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top
// Kludge to prevent 'maybelse' from blocking lexical scope pops
if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
var c = state.cc[i];
if (c == poplex) lexical = lexical.prev;
else if (c != maybeelse) break;
}
while ((lexical.type == "stat" || lexical.type == "form") &&
(firstChar == "}" || ((top = state.cc[state.cc.length - 1]) &&
(top == maybeoperatorComma || top == maybeoperatorNoComma) &&
!/^[,\.=+\-*:?[\(]/.test(textAfter))))
lexical = lexical.prev;
if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
lexical = lexical.prev;
var type = lexical.type, closing = firstChar == type;
if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0);
else if (type == "form" && firstChar == "{") return lexical.indented;
else if (type == "form") return lexical.indented + indentUnit;
else if (type == "stat")
return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
else if (lexical.align) return lexical.column + (closing ? 0 : 1);
else return lexical.indented + (closing ? 0 : indentUnit);
},
electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
blockCommentStart: jsonMode ? null : "/*",
blockCommentEnd: jsonMode ? null : "*/",
blockCommentContinue: jsonMode ? null : " * ",
lineComment: jsonMode ? null : "//",
fold: "brace",
closeBrackets: "()[]{}''\"\"``",
helperType: jsonMode ? "json" : "javascript",
jsonldMode: jsonldMode,
jsonMode: jsonMode,
expressionAllowed: expressionAllowed,
skipExpression: function(state) {
var top = state.cc[state.cc.length - 1]
if (top == expression || top == expressionNoComma) state.cc.pop()
}
};
});
CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
CodeMirror.defineMIME("text/javascript", "javascript");
CodeMirror.defineMIME("text/ecmascript", "javascript");
CodeMirror.defineMIME("application/javascript", "javascript");
CodeMirror.defineMIME("application/x-javascript", "javascript");
CodeMirror.defineMIME("application/ecmascript", "javascript");
CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
});
|
bobmagicii/atlantis
|
www/share/js/codemirror-modes/javascript/javascript.js
|
JavaScript
|
bsd-2-clause
| 37,805
|
/* flatpickr v4.0.7, @license MIT */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.fi = {})));
}(this, (function (exports) { 'use strict';
var fp = typeof window !== "undefined" && window.flatpickr !== undefined
? window.flatpickr
: {
l10ns: {},
};
var Finnish = {
firstDayOfWeek: 1,
weekdays: {
shorthand: ["Su", "Ma", "Ti", "Ke", "To", "Pe", "La"],
longhand: [
"Sunnuntai",
"Maanantai",
"Tiistai",
"Keskiviikko",
"Torstai",
"Perjantai",
"Lauantai",
],
},
months: {
shorthand: [
"Tammi",
"Helmi",
"Maalis",
"Huhti",
"Touko",
"Kesä",
"Heinä",
"Elo",
"Syys",
"Loka",
"Marras",
"Joulu",
],
longhand: [
"Tammikuu",
"Helmikuu",
"Maaliskuu",
"Huhtikuu",
"Toukokuu",
"Kesäkuu",
"Heinäkuu",
"Elokuu",
"Syyskuu",
"Lokakuu",
"Marraskuu",
"Joulukuu",
],
},
ordinal: function () {
return ".";
},
};
fp.l10ns.fi = Finnish;
var fi = fp.l10ns;
exports.Finnish = Finnish;
exports['default'] = fi;
Object.defineProperty(exports, '__esModule', { value: true });
})));
|
sashberd/cdnjs
|
ajax/libs/flatpickr/4.0.8/l10n/fi.js
|
JavaScript
|
mit
| 1,659
|
var B = require('../').Buffer
var test = require('tape')
if (process.env.OBJECT_IMPL) B.TYPED_ARRAY_SUPPORT = false
test('detect utf16 surrogate pairs', function(t) {
var text = '\uD83D\uDE38' + '\uD83D\uDCAD' + '\uD83D\uDC4D'
var buf = new B(text)
t.equal(text, buf.toString())
t.end()
})
test('throw on orphaned utf16 surrogate lead code point', function(t) {
var text = '\uD83D\uDE38' + '\uD83D' + '\uD83D\uDC4D'
var err
try {
var buf = new B(text)
} catch (e) {
err = e
}
t.equal(err instanceof URIError, true)
t.end()
})
test('throw on orphaned utf16 surrogate trail code point', function(t) {
var text = '\uD83D\uDE38' + '\uDCAD' + '\uD83D\uDC4D'
var err
try {
var buf = new B(text)
} catch (e) {
err = e
}
t.equal(err instanceof URIError, true)
t.end()
})
|
sekys/ivda
|
web/libs/vis/node_modules/webpack/node_modules/node-libs-browser/node_modules/buffer/test/utf16.js
|
JavaScript
|
mit
| 819
|
/*
* This file is part of Invenio.
* Copyright (C) 2012 CERN.
*
* Invenio is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* Invenio is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Invenio; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
/*
* Module with all functions related to refextract and BibEdit
*/
var refextract = (function() {
var dialogReferences;
function updateDialogLoading(title) {
/* Creates a loading dialog
@param title: title to be displayed on the dialog
*/
if (typeof dialogReferences !== "undefined") {
dialogReferences.dialogDiv.remove();
}
dialogReferences = createDialog(title, "Loading...", 750, 700, true);
}
function updateDialogRefextractResult(json) {
/* Receives JSON from the server and either:
- Shows an error dialog with the error message
- Updates the client representation of the record, updates the cache
file on the server and displays the new record on the interface
*/
var bibrecord = json['ref_bibrecord'];
var textmarc = json['ref_textmarc'];
var xmlrecord = json['ref_xmlrecord'];
if (!xmlrecord) {
dialogReferences.dialogDiv.remove();
dialogReferences = createDialog("Error", json["ref_msg"]);
dialogReferences.dialogDiv.dialog({
buttons: {
"Accept" : function() {
$( this ).remove();
}
}
});
}
/* References were extracted */
else {
addContentToDialog(dialogReferences, textmarc, "Do you want to apply the following references?");
dialogReferences.dialogDiv.dialog({
title: "Apply references",
buttons: {
"Apply references": function() {
/* Update global record with the updated version */
gRecord = bibrecord;
/* Update cache in the server to have the updated record */
createReq({recID: gRecID, recXML: xmlrecord, requestType: 'updateCacheRef'});
/* Redraw whole content table and enable submit button */
$('#bibEditTable').remove();
var unmarked_tags = getUnmarkedTags();
displayRecord();
setUnmarkedTags(unmarked_tags);
activateSubmitButton();
$( this ).remove();
},
Cancel: function() {
$( this ).remove();
}
}
});
}
}
function request_extract_from_url(url) {
/* create a request to extract references from the given URL
return: promise object to be resolved when request completes
*/
var requestExtractPromise = new $.Deferred();
createReq({ recID: gRecID,
url: url,
requestType: 'refextracturl'},
function(json) { requestExtractPromise.resolve(json); });
return requestExtractPromise;
}
function request_extract_from_text(txt) {
/* create a request to extract references from the given text
return: promise object to be resolved when request completes
*/
var requestExtractPromise = new $.Deferred();
createReq({ recID: gRecID,
requestType: 'refextract',
txt: txt },
function(json) { requestExtractPromise.resolve(json); });
return requestExtractPromise;
}
function request_extract_from_pdf() {
/* create a request to extract references from the PDF attached to the
record
return: promise object to be resolved when request completes
*/
var requestExtractPromise = new $.Deferred();
createReq({ recID: gRecID,
requestType: 'refextract'},
function(json) { requestExtractPromise.resolve(json); });
return requestExtractPromise;
}
function onRefExtractClick() {
/*
* Handle click on refextract from PDF button
*
*/
log_action("onRefExtractClick");
save_changes().done(function() {
var loading_title = "Extracting references from PDF";
updateDialogLoading(loading_title);
var extract_from_pdf_promise = request_extract_from_pdf();
extract_from_pdf_promise.done(updateDialogRefextractResult);
});
}
function onRefExtractURLClick() {
/*
* Handle click on refextract from URL button
*
*/
log_action("onRefExtractURLClick");
save_changes().done(function() {
var dialogContent = '<input type="text" id="input_extract_url" class="bibedit_input" placeholder="URL to extract references">';
dialogReferences = createDialog("Extract references from URL", dialogContent, 200, 500);
dialogReferences.contentParagraph.addClass('dialog-box-centered-no-margin');
dialogReferences.dialogDiv.dialog({
buttons: {
"Extract references": function() {
url = $("#input_extract_url").val();
if (url === "") {
return;
}
var loading_title = "Extracting references from URL";
updateDialogLoading(loading_title);
var extract_from_url_promise = request_extract_from_url(url);
extract_from_url_promise.done(updateDialogRefextractResult);
},
Cancel: function() {
$( this ).remove();
}
}});
});
}
function onRefExtractFreeTextClick() {
/*
* Handler for free text refextract button. Allows to paste references
* and process them using refextract on the server side.
*/
log_action("onRefExtractFreeTextClick");
save_changes().done(function() {
/* Create the modal dialog that will contain the references */
var dialogContent = "Paste your references:<br/><textarea id='reffreetext' class='bibedit_input'></textarea>"
dialogReferences = createDialog("Paste references", dialogContent, 750, 700);
dialogReferences.dialogDiv.dialog({
buttons: {
"Extract references": function() {
var textReferences = $('#reffreetext').val();
if (textReferences === "") {
return;
}
var loading_title = "Extracting references from text";
updateDialogLoading(loading_title);
var extract_from_text_promise = request_extract_from_text(textReferences);
extract_from_text_promise.done(updateDialogRefextractResult);
},
Cancel: function() {
$( this ).remove();
}
}
});
});
}
/* Public methods */
return {
onRefExtractURLClick: onRefExtractURLClick,
onRefExtractFreeTextClick: onRefExtractFreeTextClick,
onRefExtractClick: onRefExtractClick
};
})();
|
kaplun/invenio
|
modules/bibedit/lib/bibedit_refextract.js
|
JavaScript
|
gpl-2.0
| 6,559
|
/*!
* bootstrap-tokenfield
* https://github.com/sliptree/bootstrap-tokenfield
* Copyright 2013-2014 Sliptree and other contributors; Licensed MIT
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// For CommonJS and CommonJS-like environments where a window with jQuery
// is present, execute the factory with the jQuery instance from the window object
// For environments that do not inherently posses a window with a document
// (such as Node.js), expose a Tokenfield-making factory as module.exports
// This accentuates the need for the creation of a real window or passing in a jQuery instance
// e.g. require("bootstrap-tokenfield")(window); or require("bootstrap-tokenfield")($);
module.exports = global.window && global.window.$ ?
factory( global.window.$ ) :
function( input ) {
if ( !input.$ && !input.fn ) {
throw new Error( "Tokenfield requires a window object with jQuery or a jQuery instance" );
}
return factory( input.$ || input );
};
} else {
// Browser globals
factory(jQuery, window);
}
}(function ($, window) {
"use strict"; // jshint ;_;
/* TOKENFIELD PUBLIC CLASS DEFINITION
* ============================== */
var Tokenfield = function (element, options) {
var _self = this
this.$element = $(element)
this.textDirection = this.$element.css('direction');
// Extend options
this.options = $.extend(true, {}, $.fn.tokenfield.defaults, { tokens: this.$element.val() }, this.$element.data(), options)
// Setup delimiters and trigger keys
this._delimiters = (typeof this.options.delimiter === 'string') ? [this.options.delimiter] : this.options.delimiter
this._triggerKeys = $.map(this._delimiters, function (delimiter) {
return delimiter.charCodeAt(0);
});
this._firstDelimiter = this._delimiters[0];
// Check for whitespace, dash and special characters
var whitespace = $.inArray(' ', this._delimiters)
, dash = $.inArray('-', this._delimiters)
if (whitespace >= 0)
this._delimiters[whitespace] = '\\s'
if (dash >= 0) {
delete this._delimiters[dash]
this._delimiters.unshift('-')
}
var specialCharacters = ['\\', '$', '[', '{', '^', '.', '|', '?', '*', '+', '(', ')']
$.each(this._delimiters, function (index, character) {
var pos = $.inArray(character, specialCharacters)
if (pos >= 0) _self._delimiters[index] = '\\' + character;
});
// Store original input width
var elRules = (window && typeof window.getMatchedCSSRules === 'function') ? window.getMatchedCSSRules( element ) : null
, elStyleWidth = element.style.width
, elCSSWidth
, elWidth = this.$element.width()
if (elRules) {
$.each( elRules, function (i, rule) {
if (rule.style.width) {
elCSSWidth = rule.style.width;
}
});
}
// Move original input out of the way
var hidingPosition = $('body').css('direction') === 'rtl' ? 'right' : 'left',
originalStyles = { position: this.$element.css('position') };
originalStyles[hidingPosition] = this.$element.css(hidingPosition);
this.$element
.data('original-styles', originalStyles)
.data('original-tabindex', this.$element.prop('tabindex'))
.css('position', 'absolute')
.css(hidingPosition, '-10000px')
.prop('tabindex', -1)
// Create a wrapper
this.$wrapper = $('<div class="tokenfield form-control" />')
if (this.$element.hasClass('input-lg')) this.$wrapper.addClass('input-lg')
if (this.$element.hasClass('input-sm')) this.$wrapper.addClass('input-sm')
if (this.textDirection === 'rtl') this.$wrapper.addClass('rtl')
// Create a new input
var id = this.$element.prop('id') || new Date().getTime() + '' + Math.floor((1 + Math.random()) * 100)
this.$input = $('<input type="'+this.options.inputType+'" class="token-input" autocomplete="off" />')
.appendTo( this.$wrapper )
.prop( 'placeholder', this.$element.prop('placeholder') )
.prop( 'id', id + '-tokenfield' )
.prop( 'tabindex', this.$element.data('original-tabindex') )
// Re-route original input label to new input
var $label = $( 'label[for="' + this.$element.prop('id') + '"]' )
if ( $label.length ) {
$label.prop( 'for', this.$input.prop('id') )
}
// Set up a copy helper to handle copy & paste
this.$copyHelper = $('<input type="text" />').css('position', 'absolute').css(hidingPosition, '-10000px').prop('tabindex', -1).prependTo( this.$wrapper )
// Set wrapper width
if (elStyleWidth) {
this.$wrapper.css('width', elStyleWidth);
}
else if (elCSSWidth) {
this.$wrapper.css('width', elCSSWidth);
}
// If input is inside inline-form with no width set, set fixed width
else if (this.$element.parents('.form-inline').length) {
this.$wrapper.width( elWidth )
}
// Set tokenfield disabled, if original or fieldset input is disabled
if (this.$element.prop('disabled') || this.$element.parents('fieldset[disabled]').length) {
this.disable();
}
// Set tokenfield readonly, if original input is readonly
if (this.$element.prop('readonly')) {
this.readonly();
}
// Set up mirror for input auto-sizing
this.$mirror = $('<span style="position:absolute; top:-999px; left:0; white-space:pre;"/>');
this.$input.css('min-width', this.options.minWidth + 'px')
$.each([
'fontFamily',
'fontSize',
'fontWeight',
'fontStyle',
'letterSpacing',
'textTransform',
'wordSpacing',
'textIndent'
], function (i, val) {
_self.$mirror[0].style[val] = _self.$input.css(val);
});
this.$mirror.appendTo( 'body' )
// Insert tokenfield to HTML
this.$wrapper.insertBefore( this.$element )
this.$element.prependTo( this.$wrapper )
// Calculate inner input width
this.update()
// Create initial tokens, if any
this.setTokens(this.options.tokens, false, ! this.$element.val() && this.options.tokens )
// Start listening to events
this.listen()
// Initialize autocomplete, if necessary
if ( ! $.isEmptyObject( this.options.autocomplete ) ) {
var side = this.textDirection === 'rtl' ? 'right' : 'left'
, autocompleteOptions = $.extend({
minLength: this.options.showAutocompleteOnFocus ? 0 : null,
position: { my: side + " top", at: side + " bottom", of: this.$wrapper }
}, this.options.autocomplete )
this.$input.autocomplete( autocompleteOptions )
}
// Initialize typeahead, if necessary
if ( ! $.isEmptyObject( this.options.typeahead ) ) {
var typeaheadOptions = this.options.typeahead
, defaults = {
minLength: this.options.showAutocompleteOnFocus ? 0 : null
}
, args = $.isArray( typeaheadOptions ) ? typeaheadOptions : [typeaheadOptions, typeaheadOptions]
args[0] = $.extend( {}, defaults, args[0] )
this.$input.typeahead.apply( this.$input, args )
this.typeahead = true
}
}
Tokenfield.prototype = {
constructor: Tokenfield
, createToken: function (attrs, triggerChange) {
var _self = this
if (typeof attrs === 'string') {
attrs = { value: attrs, label: attrs }
} else {
// Copy objects to prevent contamination of data sources.
attrs = $.extend( {}, attrs )
}
if (typeof triggerChange === 'undefined') {
triggerChange = true
}
// Normalize label and value
attrs.value = $.trim(attrs.value.toString());
attrs.label = attrs.label && attrs.label.length ? $.trim(attrs.label) : attrs.value
// Bail out if has no value or label, or label is too short
if (!attrs.value.length || !attrs.label.length || attrs.label.length <= this.options.minLength) return
// Bail out if maximum number of tokens is reached
if (this.options.limit && this.getTokens().length >= this.options.limit) return
// Allow changing token data before creating it
var createEvent = $.Event('tokenfield:createtoken', { attrs: attrs })
this.$element.trigger(createEvent)
// Bail out if there if attributes are empty or event was defaultPrevented
if (!createEvent.attrs || createEvent.isDefaultPrevented()) return
var $token = $('<div class="token" />')
.append('<span class="token-label" />')
.append('<a href="#" class="close" tabindex="-1">×</a>')
.data('attrs', attrs)
// Insert token into HTML
if (this.$input.hasClass('tt-input')) {
// If the input has typeahead enabled, insert token before it's parent
this.$input.parent().before( $token )
} else {
this.$input.before( $token )
}
// Temporarily set input width to minimum
this.$input.css('width', this.options.minWidth + 'px')
var $tokenLabel = $token.find('.token-label')
, $closeButton = $token.find('.close')
// Determine maximum possible token label width
if (!this.maxTokenWidth) {
this.maxTokenWidth =
this.$wrapper.width() - $closeButton.outerWidth() -
parseInt($closeButton.css('margin-left'), 10) -
parseInt($closeButton.css('margin-right'), 10) -
parseInt($token.css('border-left-width'), 10) -
parseInt($token.css('border-right-width'), 10) -
parseInt($token.css('padding-left'), 10) -
parseInt($token.css('padding-right'), 10)
parseInt($tokenLabel.css('border-left-width'), 10) -
parseInt($tokenLabel.css('border-right-width'), 10) -
parseInt($tokenLabel.css('padding-left'), 10) -
parseInt($tokenLabel.css('padding-right'), 10)
parseInt($tokenLabel.css('margin-left'), 10) -
parseInt($tokenLabel.css('margin-right'), 10)
}
//$tokenLabel.css('max-width', this.maxTokenWidth)
if (this.options.html)
$tokenLabel.html(attrs.label)
else
$tokenLabel.text(attrs.label)
// Listen to events on token
$token
.on('mousedown', function (e) {
if (_self._disabled || _self._readonly) return false
_self.preventDeactivation = true
})
.on('click', function (e) {
if (_self._disabled || _self._readonly) return false
_self.preventDeactivation = false
if (e.ctrlKey || e.metaKey) {
e.preventDefault()
return _self.toggle( $token )
}
_self.activate( $token, e.shiftKey, e.shiftKey )
})
.on('dblclick', function (e) {
if (_self._disabled || _self._readonly || !_self.options.allowEditing ) return false
_self.edit( $token )
})
$closeButton
.on('click', $.proxy(this.remove, this))
// Trigger createdtoken event on the original field
// indicating that the token is now in the DOM
this.$element.trigger($.Event('tokenfield:createdtoken', {
attrs: attrs,
relatedTarget: $token.get(0)
}))
// Trigger change event on the original field
if (triggerChange) {
this.$element.val( this.getTokensList() ).trigger( $.Event('change', { initiator: 'tokenfield' }) )
}
// Update tokenfield dimensions
this.update()
// Return original element
return this.$element.get(0)
}
, setTokens: function (tokens, add, triggerChange) {
if (!tokens) return
if (!add) this.$wrapper.find('.token').remove()
if (typeof triggerChange === 'undefined') {
triggerChange = true
}
if (typeof tokens === 'string') {
if (this._delimiters.length) {
// Split based on delimiters
tokens = tokens.split( new RegExp( '[' + this._delimiters.join('') + ']' ) )
} else {
tokens = [tokens];
}
}
var _self = this
$.each(tokens, function (i, attrs) {
_self.createToken(attrs, triggerChange)
})
return this.$element.get(0)
}
, getTokenData: function($token) {
var data = $token.map(function() {
var $token = $(this);
return $token.data('attrs')
}).get();
if (data.length == 1) {
data = data[0];
}
return data;
}
, getTokens: function(active) {
var self = this
, tokens = []
, activeClass = active ? '.active' : '' // get active tokens only
this.$wrapper.find( '.token' + activeClass ).each( function() {
tokens.push( self.getTokenData( $(this) ) )
})
return tokens
}
, getTokensList: function(delimiter, beautify, active) {
delimiter = delimiter || this._firstDelimiter
beautify = ( typeof beautify !== 'undefined' && beautify !== null ) ? beautify : this.options.beautify
var separator = delimiter + ( beautify && delimiter !== ' ' ? ' ' : '')
return $.map( this.getTokens(active), function (token) {
return token.value
}).join(separator)
}
, getInput: function() {
return this.$input.val()
}
, listen: function () {
var _self = this
this.$element
.on('change', $.proxy(this.change, this))
this.$wrapper
.on('mousedown',$.proxy(this.focusInput, this))
this.$input
.on('focus', $.proxy(this.focus, this))
.on('blur', $.proxy(this.blur, this))
.on('paste', $.proxy(this.paste, this))
.on('keydown', $.proxy(this.keydown, this))
.on('keypress', $.proxy(this.keypress, this))
.on('keyup', $.proxy(this.keyup, this))
this.$copyHelper
.on('focus', $.proxy(this.focus, this))
.on('blur', $.proxy(this.blur, this))
.on('keydown', $.proxy(this.keydown, this))
.on('keyup', $.proxy(this.keyup, this))
// Secondary listeners for input width calculation
this.$input
.on('keypress', $.proxy(this.update, this))
.on('keyup', $.proxy(this.update, this))
this.$input
.on('autocompletecreate', function() {
// Set minimum autocomplete menu width
var $_menuElement = $(this).data('ui-autocomplete').menu.element
var minWidth = _self.$wrapper.outerWidth() -
parseInt( $_menuElement.css('border-left-width'), 10 ) -
parseInt( $_menuElement.css('border-right-width'), 10 )
$_menuElement.css( 'min-width', minWidth + 'px' )
})
.on('autocompleteselect', function (e, ui) {
if (_self.createToken( ui.item )) {
_self.$input.val('')
if (_self.$input.data( 'edit' )) {
_self.unedit(true)
}
}
return false
})
.on('typeahead:selected typeahead:autocompleted', function (e, datum, dataset) {
// Create token
if (_self.createToken( datum )) {
_self.$input.typeahead('val', '')
if (_self.$input.data( 'edit' )) {
_self.unedit(true)
}
}
})
// Listen to window resize
$(window).on('resize', $.proxy(this.update, this ))
}
, keydown: function (e) {
if (!this.focused) return
var _self = this
switch(e.keyCode) {
case 8: // backspace
if (!this.$input.is(document.activeElement)) break
this.lastInputValue = this.$input.val()
break
case 37: // left arrow
leftRight( this.textDirection === 'rtl' ? 'next': 'prev' )
break
case 38: // up arrow
upDown('prev')
break
case 39: // right arrow
leftRight( this.textDirection === 'rtl' ? 'prev': 'next' )
break
case 40: // down arrow
upDown('next')
break
case 65: // a (to handle ctrl + a)
if (this.$input.val().length > 0 || !(e.ctrlKey || e.metaKey)) break
this.activateAll()
e.preventDefault()
break
case 9: // tab
case 13: // enter
// We will handle creating tokens from autocomplete in autocomplete events
if (this.$input.data('ui-autocomplete') && this.$input.data('ui-autocomplete').menu.element.find("li:has(a.ui-state-focus), li.ui-state-focus").length) break
// We will handle creating tokens from typeahead in typeahead events
if (this.$input.hasClass('tt-input') && this.$wrapper.find('.tt-cursor').length ) break
if (this.$input.hasClass('tt-input') && this.$wrapper.find('.tt-hint').val() && this.$wrapper.find('.tt-hint').val().length) break
// Create token
if (this.$input.is(document.activeElement) && this.$input.val().length || this.$input.data('edit')) {
return this.createTokensFromInput(e, this.$input.data('edit'));
}
// Edit token
if (e.keyCode === 13) {
if (!this.$copyHelper.is(document.activeElement) || this.$wrapper.find('.token.active').length !== 1) break
if (!_self.options.allowEditing) break
this.edit( this.$wrapper.find('.token.active') )
}
}
function leftRight(direction) {
if (_self.$input.is(document.activeElement)) {
if (_self.$input.val().length > 0) return
direction += 'All'
var $token = _self.$input.hasClass('tt-input') ? _self.$input.parent()[direction]('.token:first') : _self.$input[direction]('.token:first')
if (!$token.length) return
_self.preventInputFocus = true
_self.preventDeactivation = true
_self.activate( $token )
e.preventDefault()
} else {
_self[direction]( e.shiftKey )
e.preventDefault()
}
}
function upDown(direction) {
if (!e.shiftKey) return
if (_self.$input.is(document.activeElement)) {
if (_self.$input.val().length > 0) return
var $token = _self.$input.hasClass('tt-input') ? _self.$input.parent()[direction + 'All']('.token:first') : _self.$input[direction + 'All']('.token:first')
if (!$token.length) return
_self.activate( $token )
}
var opposite = direction === 'prev' ? 'next' : 'prev'
, position = direction === 'prev' ? 'first' : 'last'
_self.$firstActiveToken[opposite + 'All']('.token').each(function() {
_self.deactivate( $(this) )
})
_self.activate( _self.$wrapper.find('.token:' + position), true, true )
e.preventDefault()
}
this.lastKeyDown = e.keyCode
}
, keypress: function(e) {
// Comma
if ($.inArray( e.which, this._triggerKeys) !== -1 && this.$input.is(document.activeElement)) {
if (this.$input.val()) {
this.createTokensFromInput(e)
}
return false;
}
}
, keyup: function (e) {
this.preventInputFocus = false
if (!this.focused) return
switch(e.keyCode) {
case 8: // backspace
if (this.$input.is(document.activeElement)) {
if (this.$input.val().length || this.lastInputValue.length && this.lastKeyDown === 8) break
this.preventDeactivation = true
var $prevToken = this.$input.hasClass('tt-input') ? this.$input.parent().prevAll('.token:first') : this.$input.prevAll('.token:first')
if (!$prevToken.length) break
this.activate( $prevToken )
} else {
this.remove(e)
}
break
case 46: // delete
this.remove(e, 'next')
break
}
this.lastKeyUp = e.keyCode
}
, focus: function (e) {
this.focused = true
this.$wrapper.addClass('focus')
if (this.$input.is(document.activeElement)) {
this.$wrapper.find('.active').removeClass('active')
this.$firstActiveToken = null
if (this.options.showAutocompleteOnFocus) {
this.search()
}
}
}
, blur: function (e) {
this.focused = false
this.$wrapper.removeClass('focus')
if (!this.preventDeactivation && !this.$element.is(document.activeElement)) {
this.$wrapper.find('.active').removeClass('active')
this.$firstActiveToken = null
}
if (!this.preventCreateTokens && (this.$input.data('edit') && !this.$input.is(document.activeElement) || this.options.createTokensOnBlur )) {
this.createTokensFromInput(e)
}
this.preventDeactivation = false
this.preventCreateTokens = false
}
, paste: function (e) {
var _self = this
// Add tokens to existing ones
if (_self.options.allowPasting) {
setTimeout(function () {
_self.createTokensFromInput(e)
}, 1)
}
}
, change: function (e) {
if ( e.initiator === 'tokenfield' ) return // Prevent loops
this.setTokens( this.$element.val() )
}
, createTokensFromInput: function (e, focus) {
if (this.$input.val().length < this.options.minLength)
return // No input, simply return
var tokensBefore = this.getTokensList()
this.setTokens( this.$input.val(), true )
if (tokensBefore == this.getTokensList() && this.$input.val().length)
return false // No tokens were added, do nothing (prevent form submit)
if (this.$input.hasClass('tt-input')) {
// Typeahead acts weird when simply setting input value to empty,
// so we set the query to empty instead
this.$input.typeahead('val', '')
} else {
this.$input.val('')
}
if (this.$input.data( 'edit' )) {
this.unedit(focus)
}
return false // Prevent form being submitted
}
, next: function (add) {
if (add) {
var $firstActiveToken = this.$wrapper.find('.active:first')
, deactivate = $firstActiveToken && this.$firstActiveToken ? $firstActiveToken.index() < this.$firstActiveToken.index() : false
if (deactivate) return this.deactivate( $firstActiveToken )
}
var $lastActiveToken = this.$wrapper.find('.active:last')
, $nextToken = $lastActiveToken.nextAll('.token:first')
if (!$nextToken.length) {
this.$input.focus()
return
}
this.activate($nextToken, add)
}
, prev: function (add) {
if (add) {
var $lastActiveToken = this.$wrapper.find('.active:last')
, deactivate = $lastActiveToken && this.$firstActiveToken ? $lastActiveToken.index() > this.$firstActiveToken.index() : false
if (deactivate) return this.deactivate( $lastActiveToken )
}
var $firstActiveToken = this.$wrapper.find('.active:first')
, $prevToken = $firstActiveToken.prevAll('.token:first')
if (!$prevToken.length) {
$prevToken = this.$wrapper.find('.token:first')
}
if (!$prevToken.length && !add) {
this.$input.focus()
return
}
this.activate( $prevToken, add )
}
, activate: function ($token, add, multi, remember) {
if (!$token) return
if (typeof remember === 'undefined') var remember = true
if (multi) var add = true
this.$copyHelper.focus()
if (!add) {
this.$wrapper.find('.active').removeClass('active')
if (remember) {
this.$firstActiveToken = $token
} else {
delete this.$firstActiveToken
}
}
if (multi && this.$firstActiveToken) {
// Determine first active token and the current tokens indicies
// Account for the 1 hidden textarea by subtracting 1 from both
var i = this.$firstActiveToken.index() - 2
, a = $token.index() - 2
, _self = this
this.$wrapper.find('.token').slice( Math.min(i, a) + 1, Math.max(i, a) ).each( function() {
_self.activate( $(this), true )
})
}
$token.addClass('active')
this.$copyHelper.val( this.getTokensList( null, null, true ) ).select()
}
, activateAll: function() {
var _self = this
this.$wrapper.find('.token').each( function (i) {
_self.activate($(this), i !== 0, false, false)
})
}
, deactivate: function($token) {
if (!$token) return
$token.removeClass('active')
this.$copyHelper.val( this.getTokensList( null, null, true ) ).select()
}
, toggle: function($token) {
if (!$token) return
$token.toggleClass('active')
this.$copyHelper.val( this.getTokensList( null, null, true ) ).select()
}
, edit: function ($token) {
if (!$token) return
var attrs = $token.data('attrs')
// Allow changing input value before editing
var options = { attrs: attrs, relatedTarget: $token.get(0) }
var editEvent = $.Event('tokenfield:edittoken', options)
this.$element.trigger( editEvent )
// Edit event can be cancelled if default is prevented
if (editEvent.isDefaultPrevented()) return
$token.find('.token-label').text(attrs.value)
var tokenWidth = $token.outerWidth()
var $_input = this.$input.hasClass('tt-input') ? this.$input.parent() : this.$input
$token.replaceWith( $_input )
this.preventCreateTokens = true
this.$input.val( attrs.value )
.select()
.data( 'edit', true )
.width( tokenWidth )
this.update();
// Indicate that token is now being edited, and is replaced with an input field in the DOM
this.$element.trigger($.Event('tokenfield:editedtoken', options ))
}
, unedit: function (focus) {
var $_input = this.$input.hasClass('tt-input') ? this.$input.parent() : this.$input
$_input.appendTo( this.$wrapper )
this.$input.data('edit', false)
this.$mirror.text('')
this.update()
// Because moving the input element around in DOM
// will cause it to lose focus, we provide an option
// to re-focus the input after appending it to the wrapper
if (focus) {
var _self = this
setTimeout(function () {
_self.$input.focus()
}, 1)
}
}
, remove: function (e, direction) {
if (this.$input.is(document.activeElement) || this._disabled || this._readonly) return
var $token = (e.type === 'click') ? $(e.target).closest('.token') : this.$wrapper.find('.token.active')
if (e.type !== 'click') {
if (!direction) var direction = 'prev'
this[direction]()
// Was it the first token?
if (direction === 'prev') var firstToken = $token.first().prevAll('.token:first').length === 0
}
// Prepare events and their options
var options = { attrs: this.getTokenData( $token ), relatedTarget: $token.get(0) }
, removeEvent = $.Event('tokenfield:removetoken', options)
this.$element.trigger(removeEvent);
// Remove event can be intercepted and cancelled
if (removeEvent.isDefaultPrevented()) return
var removedEvent = $.Event('tokenfield:removedtoken', options)
, changeEvent = $.Event('change', { initiator: 'tokenfield' })
// Remove token from DOM
$token.remove()
// Trigger events
this.$element.val( this.getTokensList() ).trigger( removedEvent ).trigger( changeEvent )
// Focus, when necessary:
// When there are no more tokens, or if this was the first token
// and it was removed with backspace or it was clicked on
if (!this.$wrapper.find('.token').length || e.type === 'click' || firstToken) this.$input.focus()
// Adjust input width
this.$input.css('width', this.options.minWidth + 'px')
this.update()
// Cancel original event handlers
e.preventDefault()
e.stopPropagation()
}
/**
* Update tokenfield dimensions
*/
, update: function (e) {
var value = this.$input.val()
, inputPaddingLeft = parseInt(this.$input.css('padding-left'), 10)
, inputPaddingRight = parseInt(this.$input.css('padding-right'), 10)
, inputPadding = inputPaddingLeft + inputPaddingRight
if (this.$input.data('edit')) {
if (!value) {
value = this.$input.prop("placeholder")
}
if (value === this.$mirror.text()) return
this.$mirror.text(value)
var mirrorWidth = this.$mirror.width() + 10;
if ( mirrorWidth > this.$wrapper.width() ) {
return this.$input.width( this.$wrapper.width() )
}
this.$input.width( mirrorWidth )
}
else {
var w = (this.textDirection === 'rtl')
? this.$input.offset().left + this.$input.outerWidth() - this.$wrapper.offset().left - parseInt(this.$wrapper.css('padding-left'), 10) - inputPadding - 1
: this.$wrapper.offset().left + this.$wrapper.width() + parseInt(this.$wrapper.css('padding-left'), 10) - this.$input.offset().left - inputPadding;
//
// some usecases pre-render widget before attaching to DOM,
// dimensions returned by jquery will be NaN -> we default to 100%
// so placeholder won't be cut off.
isNaN(w) ? this.$input.width('100%') : this.$input.width(w);
}
}
, focusInput: function (e) {
if ( $(e.target).closest('.token').length || $(e.target).closest('.token-input').length || $(e.target).closest('.tt-dropdown-menu').length ) return
// Focus only after the current call stack has cleared,
// otherwise has no effect.
// Reason: mousedown is too early - input will lose focus
// after mousedown. However, since the input may be moved
// in DOM, there may be no click or mouseup event triggered.
var _self = this
setTimeout(function() {
_self.$input.focus()
}, 0)
}
, search: function () {
if ( this.$input.data('ui-autocomplete') ) {
this.$input.autocomplete('search')
}
}
, disable: function () {
this.setProperty('disabled', true);
}
, enable: function () {
this.setProperty('disabled', false);
}
, readonly: function () {
this.setProperty('readonly', true);
}
, writeable: function () {
this.setProperty('readonly', false);
}
, setProperty: function(property, value) {
this['_' + property] = value;
this.$input.prop(property, value);
this.$element.prop(property, value);
this.$wrapper[ value ? 'addClass' : 'removeClass' ](property);
}
, destroy: function() {
// Set field value
this.$element.val( this.getTokensList() );
// Restore styles and properties
this.$element.css( this.$element.data('original-styles') );
this.$element.prop( 'tabindex', this.$element.data('original-tabindex') );
// Re-route tokenfield label to original input
var $label = $( 'label[for="' + this.$input.prop('id') + '"]' )
if ( $label.length ) {
$label.prop( 'for', this.$element.prop('id') )
}
// Move original element outside of tokenfield wrapper
this.$element.insertBefore( this.$wrapper );
// Remove tokenfield-related data
this.$element.removeData('original-styles')
.removeData('original-tabindex')
.removeData('bs.tokenfield');
// Remove tokenfield from DOM
this.$wrapper.remove();
this.$mirror.remove();
var $_element = this.$element;
return $_element;
}
}
/* TOKENFIELD PLUGIN DEFINITION
* ======================== */
var old = $.fn.tokenfield
$.fn.tokenfield = function (option, param) {
var value
, args = []
Array.prototype.push.apply( args, arguments );
var elements = this.each(function () {
var $this = $(this)
, data = $this.data('bs.tokenfield')
, options = typeof option == 'object' && option
if (typeof option === 'string' && data && data[option]) {
args.shift()
value = data[option].apply(data, args)
} else {
if (!data && typeof option !== 'string' && !param) {
$this.data('bs.tokenfield', (data = new Tokenfield(this, options)))
$this.trigger('tokenfield:initialize')
}
}
})
return typeof value !== 'undefined' ? value : elements;
}
$.fn.tokenfield.defaults = {
minWidth: 60,
minLength: 0,
html: true,
allowEditing: true,
allowPasting: true,
limit: 0,
autocomplete: {},
typeahead: {},
showAutocompleteOnFocus: false,
createTokensOnBlur: false,
delimiter: ',',
beautify: true,
inputType: 'text'
}
$.fn.tokenfield.Constructor = Tokenfield
/* TOKENFIELD NO CONFLICT
* ================== */
$.fn.tokenfield.noConflict = function () {
$.fn.tokenfield = old
return this
}
return Tokenfield;
}));
|
EcoAlternative/noosfero-ecosol
|
public/javascripts/vendor/bootstrap-tokenfield.js
|
JavaScript
|
agpl-3.0
| 33,215
|
'use strict';
/**
* @ngdoc function
* @name openshiftConsole.controller:ProjectsController
* @description
* # ProjectsController
* Controller of the openshiftConsole
*/
angular.module('openshiftConsole')
.controller('ProjectsController', function ($scope, $route, DataService, AuthService, Logger) {
$scope.projects = {};
$scope.alerts = $scope.alerts || {};
$scope.emptyMessage = "Loading...";
$scope.canCreate = undefined;
$('#openshift-logo').on('click.projectsPage', function() {
// Force a reload. Angular doesn't reload the view when the URL doesn't change.
$route.reload();
});
$scope.$on('$destroy', function(){
// The click handler is only necessary on the projects page.
$('#openshift-logo').off('click.projectsPage');
});
AuthService.withUser().then(function() {
DataService.list("projects", $scope, function(projects) {
$scope.projects = projects.by("metadata.name");
$scope.emptyMessage = "No projects to show.";
});
});
// Test if the user can submit project requests. Handle error notifications
// ourselves because 403 responses are expected.
DataService.get("projectrequests", null, $scope, { errorNotification: false})
.then(function() {
$scope.canCreate = true;
}, function(result) {
$scope.canCreate = false;
var data = result.data || {};
// 403 Forbidden indicates the user doesn't have authority.
// Any other failure status is an unexpected error.
if (result.status !== 403) {
var msg = 'Failed to determine create project permission';
if (result.status !== 0) {
msg += " (" + result.status + ")";
}
Logger.warn(msg);
return;
}
// Check if there are detailed messages. If there are, show them instead of our default message.
if (data.details) {
var messages = [];
_.forEach(data.details.causes || [], function(cause) {
if (cause.message) { messages.push(cause.message); }
});
if (messages.length > 0) {
$scope.newProjectMessage = messages.join("\n");
}
}
});
});
|
dkorn/origin
|
assets/app/scripts/controllers/projects.js
|
JavaScript
|
apache-2.0
| 2,190
|
YUI.add('array-extras', function(Y) {
/**
* Collection utilities beyond what is provided in the YUI core
* @module collection
* @submodule array-extras
*/
var L = Y.Lang, Native = Array.prototype, A = Y.Array;
/**
* Adds the following array utilities to the YUI instance
* (Y.Array). This is in addition to the methods provided
* in the core.
* @class YUI~array~extras
*/
/**
* Returns the index of the last item in the array
* that contains the specified value, -1 if the
* value isn't found.
* method Array.lastIndexOf
* @static
* @param a {Array} the array to search
* @param val the value to search for
* @return {int} the index of hte item that contains the value or -1
*/
A.lastIndexOf = (Native.lastIndexOf) ?
function(a ,val) {
return a.lastIndexOf(val);
} :
function(a, val) {
for (var i=a.length-1; i>=0; i=i-1) {
if (a[i] === val) {
break;
}
}
return i;
};
/**
* Returns a copy of the array with the duplicate entries removed
* @method Array.unique
* @static
* @param a {Array} the array to find the subset of uniques for
* @param sort {bool} flag to denote if the array is sorted or not. Defaults to false, the more general operation
* @return {Array} a copy of the array with duplicate entries removed
*/
A.unique = function(a, sort) {
var b = a.slice(), i = 0, n = -1, item = null;
while (i < b.length) {
item = b[i];
while ((n = A.lastIndexOf(b, item)) !== i) {
b.splice(n, 1);
}
i += 1;
}
// Note: the sort option doesn't really belong here... I think it was added
// because there was a way to fast path the two operations together. That
// implementation was not working, so I replaced it with the following.
// Leaving it in so that the API doesn't get broken.
if (sort) {
if (L.isNumber(b[0])) {
b.sort(A.numericSort);
} else {
b.sort();
}
}
return b;
};
/**
* Executes the supplied function on each item in the array.
* Returns a new array containing the items that the supplied
* function returned true for.
* @method Array.filter
* @param a {Array} the array to iterate
* @param f {Function} the function to execute on each item
* @param o Optional context object
* @static
* @return {Array} The items on which the supplied function
* returned true. If no items matched an empty array is
* returned.
*/
A.filter = (Native.filter) ?
function(a, f, o) {
return Native.filter.call(a, f, o);
} :
function(a, f, o) {
var results = [];
A.each(a, function(item, i, a) {
if (f.call(o, item, i, a)) {
results.push(item);
}
});
return results;
};
/**
* The inverse of filter. Executes the supplied function on each item.
* Returns a new array containing the items that the supplied
* function returned *false* for.
* @method Array.reject
* @param a {Array} the array to iterate
* @param f {Function} the function to execute on each item
* @param o Optional context object
* @static
* @return {Array} The items on which the supplied function
* returned false.
*/
A.reject = function(a, f, o) {
return A.filter(a, function(item, i, a) {
return !f.call(o, item, i, a);
});
};
/**
* Executes the supplied function on each item in the array.
* @method Array.every
* @param a {Array} the array to iterate
* @param f {Function} the function to execute on each item
* @param o Optional context object
* @static
* @return {boolean} true if every item in the array returns true
* from the supplied function.
*/
A.every = (Native.every) ?
function(a, f, o) {
return Native.every.call(a,f,o);
} :
function(a, f, o) {
for (var i = 0, l = a.length; i < l; i=i+1) {
if (!f.call(o, a[i], i, a)) {
return false;
}
}
return true;
};
/**
* Executes the supplied function on each item in the array.
* @method Array.map
* @param a {Array} the array to iterate
* @param f {Function} the function to execute on each item
* @param o Optional context object
* @static
* @return {Array} A new array containing the return value
* of the supplied function for each item in the original
* array.
*/
A.map = (Native.map) ?
function(a, f, o) {
return Native.map.call(a, f, o);
} :
function(a, f, o) {
var results = [];
A.each(a, function(item, i, a) {
results.push(f.call(o, item, i, a));
});
return results;
};
/**
* Executes the supplied function on each item in the array.
* Reduce "folds" the array into a single value.
* @method Array.reduce
* @param a {Array} the array to iterate
* @param init The initial value to start from
* @param f {Function} the function to execute on each item. It
* is responsible for returning the updated value of the
* computation.
* @param o Optional context object
* @static
* @return A value that results from iteratively applying the
* supplied function to each element in the array.
*/
A.reduce = (Native.reduce) ?
function(a, init, f, o) {
//Firefox's Array.reduce does not allow inclusion of a
// thisObject, so we need to implement it manually
return Native.reduce.call(a, function(init, item, i, a) {
return f.call(o, init, item, i, a);
}, init);
} :
function(a, init, f, o) {
var r = init;
A.each(a, function (item, i, a) {
r = f.call(o, r, item, i, a);
});
return r;
};
/**
* Executes the supplied function on each item in the array,
* searching for the first item that matches the supplied
* function.
* @method Array.find
* @param a {Array} the array to search
* @param f {Function} the function to execute on each item.
* Iteration is stopped as soon as this function returns true
* on an item.
* @param o Optional context object
* @static
* @return {object} the first item that the supplied function
* returns true for, or null if it never returns true
*/
A.find = function(a, f, o) {
for(var i=0, l = a.length; i < l; i++) {
if (f.call(o, a[i], i, a)) {
return a[i];
}
}
return null;
};
/**
* Iterates over an array, returning a new array of all the elements
* that match the supplied regular expression
* @method Array.grep
* @param a {Array} a collection to iterate over
* @param pattern {RegExp} The regular expression to test against
* each item
* @static
* @return {Array} All the items in the collection that
* produce a match against the supplied regular expression.
* If no items match, an empty array is returned.
*/
A.grep = function (a, pattern) {
return A.filter(a, function (item, index) {
return pattern.test(item);
});
};
/**
* Partitions an array into two new arrays, one with the items
* that match the supplied function, and one with the items that
* do not.
* @method Array.partition
* @param a {Array} a collection to iterate over
* @paran f {Function} a function that will receive each item
* in the collection and its index.
* @param o Optional execution context of f.
* @static
* @return An object with two members, 'matches' and 'rejects',
* that are arrays containing the items that were selected or
* rejected by the test function (or an empty array).
*/
A.partition = function (a, f, o) {
var results = {
matches: [],
rejects: []
};
A.each(a, function (item, index) {
var set = f.call(o, item, index, a) ? results.matches : results.rejects;
set.push(item);
});
return results;
};
/**
* Creates an array of arrays by pairing the corresponding
* elements of two arrays together into a new array.
* @method Array.zip
* @param a {Array} a collection to iterate over
* @param a2 {Array} another collection whose members will be
* paired with members of the first parameter
* @static
* @return An array of arrays formed by pairing each element
* of the first collection with an item in the second collection
* having the corresponding index.
*/
A.zip = function (a, a2) {
var results = [];
A.each(a, function (item, index) {
results.push([item, a2[index]]);
});
return results;
};
A.forEach = A.each;
}, '@VERSION@' );
|
joeyparrish/cdnjs
|
ajax/libs/yui/3.1.0pr1/collection/array-extras.js
|
JavaScript
|
mit
| 8,369
|
(function () {
'use strict';
/**
* Create a cached version of a pure function.
*/
function cached (fn) {
var cache = Object.create(null);
return function cachedFn (str) {
var hit = cache[str];
return hit || (cache[str] = fn(str))
}
}
/**
* Hyphenate a camelCase string.
*/
var hyphenate = cached(function (str) {
return str.replace(/([A-Z])/g, function (m) { return '-' + m.toLowerCase(); })
});
/**
* Simple Object.assign polyfill
*/
var merge = Object.assign || function (to) {
var arguments$1 = arguments;
var hasOwn = Object.prototype.hasOwnProperty;
for (var i = 1; i < arguments.length; i++) {
var from = Object(arguments$1[i]);
for (var key in from) {
if (hasOwn.call(from, key)) {
to[key] = from[key];
}
}
}
return to
};
/**
* Check if value is primitive
*/
function isPrimitive (value) {
return typeof value === 'string' || typeof value === 'number'
}
/**
* Perform no operation.
*/
function noop () {}
/**
* Check if value is function
*/
function isFn (obj) {
return typeof obj === 'function'
}
var config = merge({
el: '#app',
repo: '',
maxLevel: 6,
subMaxLevel: 0,
loadSidebar: null,
loadNavbar: null,
homepage: 'README.md',
coverpage: '',
basePath: '',
auto2top: false,
name: '',
themeColor: '',
nameLink: window.location.pathname,
autoHeader: false,
executeScript: null,
ga: ''
}, window.$docsify);
var script = document.currentScript ||
[].slice.call(document.getElementsByTagName('script'))
.filter(function (n) { return /docsify\./.test(n.src); })[0];
if (script) {
for (var prop in config) {
var val = script.getAttribute('data-' + hyphenate(prop));
if (isPrimitive(val)) {
config[prop] = val === '' ? true : val;
}
}
if (config.loadSidebar === true) { config.loadSidebar = '_sidebar.md'; }
if (config.loadNavbar === true) { config.loadNavbar = '_navbar.md'; }
if (config.coverpage === true) { config.coverpage = '_coverpage.md'; }
if (config.repo === true) { config.repo = ''; }
if (config.name === true) { config.name = ''; }
}
window.$docsify = config;
function initLifecycle (vm) {
var hooks = [
'init',
'mounted',
'beforeEach',
'afterEach',
'doneEach',
'ready'
];
vm._hooks = {};
vm._lifecycle = {};
hooks.forEach(function (hook) {
var arr = vm._hooks[hook] = [];
vm._lifecycle[hook] = function (fn) { return arr.push(fn); };
});
}
function callHook (vm, hook, data, next) {
if ( next === void 0 ) next = noop;
var newData = data;
var queue = vm._hooks[hook];
var step = function (index) {
var hook = queue[index];
if (index >= queue.length) {
next(newData);
} else {
if (typeof hook === 'function') {
if (hook.length === 2) {
hook(data, function (result) {
newData = result;
step(index + 1);
});
} else {
var result = hook(data);
newData = result !== undefined ? result : newData;
step(index + 1);
}
} else {
step(index + 1);
}
}
};
step(0);
}
var cacheNode = {};
/**
* Get Node
* @param {String|Element} el
* @param {Boolean} noCache
* @return {Element}
*/
function getNode (el, noCache) {
if ( noCache === void 0 ) noCache = false;
if (typeof el === 'string') {
el = noCache ? find(el) : (cacheNode[el] || find(el));
}
return el
}
var $ = document;
var body = $.body;
var head = $.head;
/**
* Find element
* @example
* find('nav') => document.querySelector('nav')
* find(nav, 'a') => nav.querySelector('a')
*/
function find (el, node) {
return node ? el.querySelector(node) : $.querySelector(el)
}
/**
* Find all elements
* @example
* findAll('a') => [].slice.call(document.querySelectorAll('a'))
* findAll(nav, 'a') => [].slice.call(nav.querySelectorAll('a'))
*/
function findAll (el, node) {
return [].slice.call(node ? el.querySelectorAll(node) : $.querySelectorAll(el))
}
function create (node, tpl) {
node = $.createElement(node);
if (tpl) { node.innerHTML = tpl; }
return node
}
function appendTo (target, el) {
return target.appendChild(el)
}
function before (target, el) {
return target.insertBefore(el, target.children[0])
}
function on (el, type, handler) {
isFn(type)
? window.addEventListener(el, type)
: el.addEventListener(type, handler);
}
function off (el, type, handler) {
isFn(type)
? window.removeEventListener(el, type)
: el.removeEventListener(type, handler);
}
/**
* Toggle class
*
* @example
* toggleClass(el, 'active') => el.classList.toggle('active')
* toggleClass(el, 'add', 'active') => el.classList.add('active')
*/
function toggleClass (el, type, val) {
el && el.classList[val ? type : 'toggle'](val || type);
}
var dom = Object.freeze({
getNode: getNode,
$: $,
body: body,
head: head,
find: find,
findAll: findAll,
create: create,
appendTo: appendTo,
before: before,
on: on,
off: off,
toggleClass: toggleClass
});
var UA = window.navigator.userAgent.toLowerCase();
var isIE = UA && /msie|trident/.test(UA);
var isMobile = document.body.clientWidth <= 600;
var decode = decodeURIComponent;
var encode = encodeURIComponent;
function parseQuery (query) {
var res = {};
query = query.trim().replace(/^(\?|#|&)/, '');
if (!query) {
return res
}
// Simple parse
query.split('&').forEach(function (param) {
var parts = param.replace(/\+/g, ' ').split('=');
res[parts[0]] = decode(parts[1]);
});
return res
}
function stringifyQuery (obj) {
var qs = [];
for (var key in obj) {
qs.push(((encode(key)) + "=" + (encode(obj[key]))).toLowerCase());
}
return qs.length ? ("?" + (qs.join('&'))) : ''
}
var getBasePath = cached(function (base) {
return /^(\/|https?:)/g.test(base)
? base
: cleanPath(window.location.pathname + '/' + base)
});
function getPath () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return cleanPath(args.join('/'))
}
var isAbsolutePath = cached(function (path) {
return /(:|(\/{2}))/.test(path)
});
var getRoot = cached(function (path) {
return /\/$/g.test(path) ? path : path.match(/(\S*\/)[^\/]+$/)[1]
});
var cleanPath = cached(function (path) {
return path.replace(/\/+/g, '/')
});
function replaceHash (path) {
var i = window.location.href.indexOf('#');
window.location.replace(
window.location.href.slice(0, i >= 0 ? i : 0) + '#' + path
);
}
var replaceSlug = cached(function (path) {
return path
.replace('#', '?id=')
.replace(/\?(\w+)=/g, function (_, slug) { return slug === 'id' ? '?id=' : ("&" + slug + "="); })
});
/**
* Normalize the current url
*
* @example
* domain.com/docs/ => domain.com/docs/#/
* domain.com/docs/#/#slug => domain.com/docs/#/?id=slug
*/
function normalize () {
var path = getHash();
path = replaceSlug(path);
if (path.charAt(0) === '/') { return replaceHash(path) }
replaceHash('/' + path);
}
function getHash () {
// We can't use window.location.hash here because it's not
// consistent across browsers - Firefox will pre-decode it!
var href = window.location.href;
var index = href.indexOf('#');
return index === -1 ? '' : href.slice(index + 1)
}
/**
* Parse the url
* @param {string} [path=window.location.herf]
* @return {object} { path, query }
*/
function parse (path) {
if ( path === void 0 ) path = window.location.href;
var query = '';
var queryIndex = path.indexOf('?');
if (queryIndex >= 0) {
query = path.slice(queryIndex + 1);
path = path.slice(0, queryIndex);
}
var hashIndex = path.indexOf('#');
if (hashIndex) {
path = path.slice(hashIndex + 1);
}
return { path: path, query: parseQuery(query) }
}
/**
* to URL
* @param {string} path
* @param {object} qs query params
*/
function toURL (path, params) {
var route = parse(replaceSlug(path));
route.query = merge({}, route.query, params);
path = route.path + stringifyQuery(route.query);
return cleanPath('#/' + path)
}
var route = Object.freeze({
normalize: normalize,
getHash: getHash,
parse: parse,
toURL: toURL,
parseQuery: parseQuery,
stringifyQuery: stringifyQuery,
getBasePath: getBasePath,
getPath: getPath,
isAbsolutePath: isAbsolutePath,
getRoot: getRoot,
cleanPath: cleanPath
});
var title = $.title;
/**
* Toggle button
*/
function btn (el) {
var toggle = function () { return body.classList.toggle('close'); };
el = getNode(el);
on(el, 'click', toggle);
var sidebar = getNode('.sidebar');
on(sidebar, 'click', function () {
isMobile && toggle();
setTimeout(function () { return getAndActive(sidebar, true, true); }, 0);
});
}
function sticky () {
var cover = getNode('section.cover');
if (!cover) { return }
var coverHeight = cover.getBoundingClientRect().height;
if (window.pageYOffset >= coverHeight || cover.classList.contains('hidden')) {
toggleClass(body, 'add', 'sticky');
} else {
toggleClass(body, 'remove', 'sticky');
}
}
/**
* Get and active link
* @param {string|element} el
* @param {Boolean} isParent acitve parent
* @param {Boolean} autoTitle auto set title
* @return {element}
*/
function getAndActive (el, isParent, autoTitle) {
el = getNode(el);
var links = findAll(el, 'a');
var hash = '#' + getHash();
var target;
links
.sort(function (a, b) { return b.href.length - a.href.length; })
.forEach(function (a) {
var href = a.getAttribute('href');
var node = isParent ? a.parentNode : a;
if (hash.indexOf(href) === 0 && !target) {
target = a;
toggleClass(node, 'add', 'active');
} else {
toggleClass(node, 'remove', 'active');
}
});
if (autoTitle) {
$.title = target ? ((target.innerText) + " - " + title) : title;
}
return target
}
var nav = {};
var hoverOver = false;
function highlight () {
var sidebar = getNode('.sidebar');
var anchors = findAll('.anchor');
var wrap = find(sidebar, '.sidebar-nav');
var active = find(sidebar, 'li.active');
var top = body.scrollTop;
var last;
for (var i = 0, len = anchors.length; i < len; i += 1) {
var node = anchors[i];
if (node.offsetTop > top) {
if (!last) { last = node; }
break
} else {
last = node;
}
}
if (!last) { return }
var li = nav[last.getAttribute('data-id')];
if (!li || li === active) { return }
active && active.classList.remove('active');
li.classList.add('active');
active = li;
// scroll into view
// https://github.com/vuejs/vuejs.org/blob/master/themes/vue/source/js/common.js#L282-L297
if (!hoverOver && body.classList.contains('sticky')) {
var height = sidebar.clientHeight;
var curOffset = 0;
var cur = active.offsetTop + active.clientHeight + 40;
var isInView = (
active.offsetTop >= wrap.scrollTop &&
cur <= wrap.scrollTop + height
);
var notThan = cur - curOffset < height;
var top$1 = isInView
? wrap.scrollTop
: notThan
? curOffset
: cur - height;
sidebar.scrollTop = top$1;
}
}
function scrollActiveSidebar () {
if (isMobile) { return }
var sidebar = getNode('.sidebar');
var lis = findAll(sidebar, 'li');
for (var i = 0, len = lis.length; i < len; i += 1) {
var li = lis[i];
var a = li.querySelector('a');
if (!a) { continue }
var href = a.getAttribute('href');
if (href !== '/') {
href = parse(href).query.id;
}
nav[decodeURIComponent(href)] = li;
}
off('scroll', highlight);
on('scroll', highlight);
on(sidebar, 'mouseover', function () { hoverOver = true; });
on(sidebar, 'mouseleave', function () { hoverOver = false; });
}
function scrollIntoView (id) {
var section = find('#' + id);
section && section.scrollIntoView();
}
var scrollEl = $.scrollingElement || $.documentElement;
function scroll2Top (offset) {
if ( offset === void 0 ) offset = 0;
scrollEl.scrollTop = offset === true ? 0 : Number(offset);
}
var barEl;
var timeId;
/**
* Init progress component
*/
function init () {
var div = create('div');
div.classList.add('progress');
appendTo(body, div);
barEl = div;
}
/**
* Render progress bar
*/
var progressbar = function (ref) {
var loaded = ref.loaded;
var total = ref.total;
var step = ref.step;
var num;
!barEl && init();
if (step) {
num = parseInt(barEl.style.width || 0, 10) + step;
num = num > 80 ? 80 : num;
} else {
num = Math.floor(loaded / total * 100);
}
barEl.style.opacity = 1;
barEl.style.width = num >= 95 ? '100%' : num + '%';
if (num >= 95) {
clearTimeout(timeId);
timeId = setTimeout(function (_) {
barEl.style.opacity = 0;
barEl.style.width = '0%';
}, 200);
}
};
var cache = {};
/**
* Simple ajax get
* @param {string} url
* @param {boolean} [hasBar=false] has progress bar
* @return { then(resolve, reject), abort }
*/
function get (url, hasBar) {
if ( hasBar === void 0 ) hasBar = false;
var xhr = new XMLHttpRequest();
var on = function () {
xhr.addEventListener.apply(xhr, arguments);
};
if (cache[url]) {
return { then: function (cb) { return cb(cache[url]); }, abort: noop }
}
xhr.open('GET', url);
xhr.send();
return {
then: function (success, error) {
if ( error === void 0 ) error = noop;
if (hasBar) {
var id = setInterval(function (_) { return progressbar({
step: Math.floor(Math.random() * 5 + 1)
}); }, 500);
on('progress', progressbar);
on('loadend', function (evt) {
progressbar(evt);
clearInterval(id);
});
}
on('error', error);
on('load', function (ref) {
var target = ref.target;
if (target.status >= 400) {
error(target);
} else {
cache[url] = target.response;
success(target.response);
}
});
},
abort: function (_) { return xhr.readyState !== 4 && xhr.abort(); }
}
}
function replaceVar (block, color) {
block.innerHTML = block.innerHTML
.replace(/var\(\s*--theme-color.*?\)/g, color);
}
var cssVars = function (color) {
// Variable support
if (window.CSS &&
window.CSS.supports &&
window.CSS.supports('(--v:red)')) { return }
var styleBlocks = findAll('style:not(.inserted),link');[].forEach.call(styleBlocks, function (block) {
if (block.nodeName === 'STYLE') {
replaceVar(block, color);
} else if (block.nodeName === 'LINK') {
var href = block.getAttribute('href');
if (!/\.css$/.test(href)) { return }
get(href).then(function (res) {
var style = create('style', res);
head.appendChild(style);
replaceVar(style, color);
});
}
});
};
/**
* Render github corner
* @param {Object} data
* @return {String}
*/
function corner (data) {
if (!data) { return '' }
if (!/\/\//.test(data)) { data = 'https://github.com/' + data; }
data = data.replace(/^git\+/, '');
return (
"<a href=\"" + data + "\" class=\"github-corner\" aria-label=\"View source on Github\">" +
'<svg viewBox="0 0 250 250" aria-hidden="true">' +
'<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>' +
'<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>' +
'<path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path>' +
'</svg>' +
'</a>`')
}
/**
* Render main content
*/
function main (config) {
var aside = (
'<button class="sidebar-toggle">' +
'<div class="sidebar-toggle-button">' +
'<span></span><span></span><span></span>' +
'</div>' +
'</button>' +
'<aside class="sidebar">' +
(config.name
? ("<h1><a href=\"" + (config.nameLink) + "\">" + (config.name) + "</a></h1>")
: '') +
'<div class="sidebar-nav"></div>' +
'</aside>');
return (isMobile ? (aside + "<main>") : ("<main>" + aside)) +
'<section class="content">' +
'<article class="markdown-section" id="main"></article>' +
'</section>' +
'</main>'
}
/**
* Cover Page
*/
function cover () {
var SL = ', 100%, 85%';
var bgc = 'linear-gradient(to left bottom, ' +
"hsl(" + (Math.floor(Math.random() * 255) + SL) + ") 0%," +
"hsl(" + (Math.floor(Math.random() * 255) + SL) + ") 100%)";
return "<section class=\"cover\" style=\"background: " + bgc + "\">" +
'<div class="cover-main"></div>' +
'<div class="mask"></div>' +
'</section>'
}
/**
* Render tree
* @param {Array} tree
* @param {String} tpl
* @return {String}
*/
function tree (toc, tpl) {
if ( tpl === void 0 ) tpl = '';
if (!toc || !toc.length) { return '' }
toc.forEach(function (node) {
tpl += "<li><a class=\"section-link\" href=\"" + (node.slug) + "\">" + (node.title) + "</a></li>";
if (node.children) {
tpl += "<li><ul class=\"children\">" + (tree(node.children)) + "</li></ul>";
}
});
return tpl
}
function helper (className, content) {
return ("<p class=\"" + className + "\">" + (content.slice(5).trim()) + "</p>")
}
function theme (color) {
return ("<style>:root{--theme-color: " + color + ";}</style>")
}
var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var marked = createCommonjsModule(function (module, exports) {
/**
* marked - a markdown parser
* Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
* https://github.com/chjj/marked
*/
(function() {
/**
* Block-Level Grammar
*/
var block = {
newline: /^\n+/,
code: /^( {4}[^\n]+\n*)+/,
fences: noop,
hr: /^( *[-*_]){3,} *(?:\n+|$)/,
heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
nptable: noop,
lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
table: noop,
paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
text: /^[^\n]+/
};
block.bullet = /(?:[*+-]|\d+\.)/;
block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
block.item = replace(block.item, 'gm')
(/bull/g, block.bullet)
();
block.list = replace(block.list)
(/bull/g, block.bullet)
('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
('def', '\\n+(?=' + block.def.source + ')')
();
block.blockquote = replace(block.blockquote)
('def', block.def)
();
block._tag = '(?!(?:'
+ 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
+ '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
+ '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
block.html = replace(block.html)
('comment', /<!--[\s\S]*?-->/)
('closed', /<(tag)[\s\S]+?<\/\1>/)
('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
(/tag/g, block._tag)
();
block.paragraph = replace(block.paragraph)
('hr', block.hr)
('heading', block.heading)
('lheading', block.lheading)
('blockquote', block.blockquote)
('tag', '<' + block._tag)
('def', block.def)
();
/**
* Normal Block Grammar
*/
block.normal = merge({}, block);
/**
* GFM Block Grammar
*/
block.gfm = merge({}, block.normal, {
fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
paragraph: /^/,
heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
});
block.gfm.paragraph = replace(block.paragraph)
('(?!', '(?!'
+ block.gfm.fences.source.replace('\\1', '\\2') + '|'
+ block.list.source.replace('\\1', '\\3') + '|')
();
/**
* GFM + Tables Block Grammar
*/
block.tables = merge({}, block.gfm, {
nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
});
/**
* Block Lexer
*/
function Lexer(options) {
this.tokens = [];
this.tokens.links = {};
this.options = options || marked.defaults;
this.rules = block.normal;
if (this.options.gfm) {
if (this.options.tables) {
this.rules = block.tables;
} else {
this.rules = block.gfm;
}
}
}
/**
* Expose Block Rules
*/
Lexer.rules = block;
/**
* Static Lex Method
*/
Lexer.lex = function(src, options) {
var lexer = new Lexer(options);
return lexer.lex(src);
};
/**
* Preprocessing
*/
Lexer.prototype.lex = function(src) {
src = src
.replace(/\r\n|\r/g, '\n')
.replace(/\t/g, ' ')
.replace(/\u00a0/g, ' ')
.replace(/\u2424/g, '\n');
return this.token(src, true);
};
/**
* Lexing
*/
Lexer.prototype.token = function(src, top, bq) {
var this$1 = this;
var src = src.replace(/^ +$/gm, '')
, next
, loose
, cap
, bull
, b
, item
, space
, i
, l;
while (src) {
// newline
if (cap = this$1.rules.newline.exec(src)) {
src = src.substring(cap[0].length);
if (cap[0].length > 1) {
this$1.tokens.push({
type: 'space'
});
}
}
// code
if (cap = this$1.rules.code.exec(src)) {
src = src.substring(cap[0].length);
cap = cap[0].replace(/^ {4}/gm, '');
this$1.tokens.push({
type: 'code',
text: !this$1.options.pedantic
? cap.replace(/\n+$/, '')
: cap
});
continue;
}
// fences (gfm)
if (cap = this$1.rules.fences.exec(src)) {
src = src.substring(cap[0].length);
this$1.tokens.push({
type: 'code',
lang: cap[2],
text: cap[3] || ''
});
continue;
}
// heading
if (cap = this$1.rules.heading.exec(src)) {
src = src.substring(cap[0].length);
this$1.tokens.push({
type: 'heading',
depth: cap[1].length,
text: cap[2]
});
continue;
}
// table no leading pipe (gfm)
if (top && (cap = this$1.rules.nptable.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/\n$/, '').split('\n')
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i].split(/ *\| */);
}
this$1.tokens.push(item);
continue;
}
// lheading
if (cap = this$1.rules.lheading.exec(src)) {
src = src.substring(cap[0].length);
this$1.tokens.push({
type: 'heading',
depth: cap[2] === '=' ? 1 : 2,
text: cap[1]
});
continue;
}
// hr
if (cap = this$1.rules.hr.exec(src)) {
src = src.substring(cap[0].length);
this$1.tokens.push({
type: 'hr'
});
continue;
}
// blockquote
if (cap = this$1.rules.blockquote.exec(src)) {
src = src.substring(cap[0].length);
this$1.tokens.push({
type: 'blockquote_start'
});
cap = cap[0].replace(/^ *> ?/gm, '');
// Pass `top` to keep the current
// "toplevel" state. This is exactly
// how markdown.pl works.
this$1.token(cap, top, true);
this$1.tokens.push({
type: 'blockquote_end'
});
continue;
}
// list
if (cap = this$1.rules.list.exec(src)) {
src = src.substring(cap[0].length);
bull = cap[2];
this$1.tokens.push({
type: 'list_start',
ordered: bull.length > 1
});
// Get each top-level item.
cap = cap[0].match(this$1.rules.item);
next = false;
l = cap.length;
i = 0;
for (; i < l; i++) {
item = cap[i];
// Remove the list item's bullet
// so it is seen as the next token.
space = item.length;
item = item.replace(/^ *([*+-]|\d+\.) +/, '');
// Outdent whatever the
// list item contains. Hacky.
if (~item.indexOf('\n ')) {
space -= item.length;
item = !this$1.options.pedantic
? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
: item.replace(/^ {1,4}/gm, '');
}
// Determine whether the next list item belongs here.
// Backpedal if it does not belong in this list.
if (this$1.options.smartLists && i !== l - 1) {
b = block.bullet.exec(cap[i + 1])[0];
if (bull !== b && !(bull.length > 1 && b.length > 1)) {
src = cap.slice(i + 1).join('\n') + src;
i = l - 1;
}
}
// Determine whether item is loose or not.
// Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
// for discount behavior.
loose = next || /\n\n(?!\s*$)/.test(item);
if (i !== l - 1) {
next = item.charAt(item.length - 1) === '\n';
if (!loose) { loose = next; }
}
this$1.tokens.push({
type: loose
? 'loose_item_start'
: 'list_item_start'
});
// Recurse.
this$1.token(item, false, bq);
this$1.tokens.push({
type: 'list_item_end'
});
}
this$1.tokens.push({
type: 'list_end'
});
continue;
}
// html
if (cap = this$1.rules.html.exec(src)) {
src = src.substring(cap[0].length);
this$1.tokens.push({
type: this$1.options.sanitize
? 'paragraph'
: 'html',
pre: !this$1.options.sanitizer
&& (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
text: cap[0]
});
continue;
}
// def
if ((!bq && top) && (cap = this$1.rules.def.exec(src))) {
src = src.substring(cap[0].length);
this$1.tokens.links[cap[1].toLowerCase()] = {
href: cap[2],
title: cap[3]
};
continue;
}
// table (gfm)
if (top && (cap = this$1.rules.table.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i]
.replace(/^ *\| *| *\| *$/g, '')
.split(/ *\| */);
}
this$1.tokens.push(item);
continue;
}
// top-level paragraph
if (top && (cap = this$1.rules.paragraph.exec(src))) {
src = src.substring(cap[0].length);
this$1.tokens.push({
type: 'paragraph',
text: cap[1].charAt(cap[1].length - 1) === '\n'
? cap[1].slice(0, -1)
: cap[1]
});
continue;
}
// text
if (cap = this$1.rules.text.exec(src)) {
// Top-level should never reach here.
src = src.substring(cap[0].length);
this$1.tokens.push({
type: 'text',
text: cap[0]
});
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return this.tokens;
};
/**
* Inline-Level Grammar
*/
var inline = {
escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
url: noop,
tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
link: /^!?\[(inside)\]\(href\)/,
reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
br: /^ {2,}\n(?!\s*$)/,
del: noop,
text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
};
inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
inline.link = replace(inline.link)
('inside', inline._inside)
('href', inline._href)
();
inline.reflink = replace(inline.reflink)
('inside', inline._inside)
();
/**
* Normal Inline Grammar
*/
inline.normal = merge({}, inline);
/**
* Pedantic Inline Grammar
*/
inline.pedantic = merge({}, inline.normal, {
strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
});
/**
* GFM Inline Grammar
*/
inline.gfm = merge({}, inline.normal, {
escape: replace(inline.escape)('])', '~|])')(),
url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
del: /^~~(?=\S)([\s\S]*?\S)~~/,
text: replace(inline.text)
(']|', '~]|')
('|', '|https?://|')
()
});
/**
* GFM + Line Breaks Inline Grammar
*/
inline.breaks = merge({}, inline.gfm, {
br: replace(inline.br)('{2,}', '*')(),
text: replace(inline.gfm.text)('{2,}', '*')()
});
/**
* Inline Lexer & Compiler
*/
function InlineLexer(links, options) {
this.options = options || marked.defaults;
this.links = links;
this.rules = inline.normal;
this.renderer = this.options.renderer || new Renderer;
this.renderer.options = this.options;
if (!this.links) {
throw new
Error('Tokens array requires a `links` property.');
}
if (this.options.gfm) {
if (this.options.breaks) {
this.rules = inline.breaks;
} else {
this.rules = inline.gfm;
}
} else if (this.options.pedantic) {
this.rules = inline.pedantic;
}
}
/**
* Expose Inline Rules
*/
InlineLexer.rules = inline;
/**
* Static Lexing/Compiling Method
*/
InlineLexer.output = function(src, links, options) {
var inline = new InlineLexer(links, options);
return inline.output(src);
};
/**
* Lexing/Compiling
*/
InlineLexer.prototype.output = function(src) {
var this$1 = this;
var out = ''
, link
, text
, href
, cap;
while (src) {
// escape
if (cap = this$1.rules.escape.exec(src)) {
src = src.substring(cap[0].length);
out += cap[1];
continue;
}
// autolink
if (cap = this$1.rules.autolink.exec(src)) {
src = src.substring(cap[0].length);
if (cap[2] === '@') {
text = cap[1].charAt(6) === ':'
? this$1.mangle(cap[1].substring(7))
: this$1.mangle(cap[1]);
href = this$1.mangle('mailto:') + text;
} else {
text = escape(cap[1]);
href = text;
}
out += this$1.renderer.link(href, null, text);
continue;
}
// url (gfm)
if (!this$1.inLink && (cap = this$1.rules.url.exec(src))) {
src = src.substring(cap[0].length);
text = escape(cap[1]);
href = text;
out += this$1.renderer.link(href, null, text);
continue;
}
// tag
if (cap = this$1.rules.tag.exec(src)) {
if (!this$1.inLink && /^<a /i.test(cap[0])) {
this$1.inLink = true;
} else if (this$1.inLink && /^<\/a>/i.test(cap[0])) {
this$1.inLink = false;
}
src = src.substring(cap[0].length);
out += this$1.options.sanitize
? this$1.options.sanitizer
? this$1.options.sanitizer(cap[0])
: escape(cap[0])
: cap[0];
continue;
}
// link
if (cap = this$1.rules.link.exec(src)) {
src = src.substring(cap[0].length);
this$1.inLink = true;
out += this$1.outputLink(cap, {
href: cap[2],
title: cap[3]
});
this$1.inLink = false;
continue;
}
// reflink, nolink
if ((cap = this$1.rules.reflink.exec(src))
|| (cap = this$1.rules.nolink.exec(src))) {
src = src.substring(cap[0].length);
link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
link = this$1.links[link.toLowerCase()];
if (!link || !link.href) {
out += cap[0].charAt(0);
src = cap[0].substring(1) + src;
continue;
}
this$1.inLink = true;
out += this$1.outputLink(cap, link);
this$1.inLink = false;
continue;
}
// strong
if (cap = this$1.rules.strong.exec(src)) {
src = src.substring(cap[0].length);
out += this$1.renderer.strong(this$1.output(cap[2] || cap[1]));
continue;
}
// em
if (cap = this$1.rules.em.exec(src)) {
src = src.substring(cap[0].length);
out += this$1.renderer.em(this$1.output(cap[2] || cap[1]));
continue;
}
// code
if (cap = this$1.rules.code.exec(src)) {
src = src.substring(cap[0].length);
out += this$1.renderer.codespan(escape(cap[2], true));
continue;
}
// br
if (cap = this$1.rules.br.exec(src)) {
src = src.substring(cap[0].length);
out += this$1.renderer.br();
continue;
}
// del (gfm)
if (cap = this$1.rules.del.exec(src)) {
src = src.substring(cap[0].length);
out += this$1.renderer.del(this$1.output(cap[1]));
continue;
}
// text
if (cap = this$1.rules.text.exec(src)) {
src = src.substring(cap[0].length);
out += this$1.renderer.text(escape(this$1.smartypants(cap[0])));
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return out;
};
/**
* Compile Link
*/
InlineLexer.prototype.outputLink = function(cap, link) {
var href = escape(link.href)
, title = link.title ? escape(link.title) : null;
return cap[0].charAt(0) !== '!'
? this.renderer.link(href, title, this.output(cap[1]))
: this.renderer.image(href, title, escape(cap[1]));
};
/**
* Smartypants Transformations
*/
InlineLexer.prototype.smartypants = function(text) {
if (!this.options.smartypants) { return text; }
return text
// em-dashes
.replace(/---/g, '\u2014')
// en-dashes
.replace(/--/g, '\u2013')
// opening singles
.replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
// closing singles & apostrophes
.replace(/'/g, '\u2019')
// opening doubles
.replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
// closing doubles
.replace(/"/g, '\u201d')
// ellipses
.replace(/\.{3}/g, '\u2026');
};
/**
* Mangle Links
*/
InlineLexer.prototype.mangle = function(text) {
if (!this.options.mangle) { return text; }
var out = ''
, l = text.length
, i = 0
, ch;
for (; i < l; i++) {
ch = text.charCodeAt(i);
if (Math.random() > 0.5) {
ch = 'x' + ch.toString(16);
}
out += '&#' + ch + ';';
}
return out;
};
/**
* Renderer
*/
function Renderer(options) {
this.options = options || {};
}
Renderer.prototype.code = function(code, lang, escaped) {
if (this.options.highlight) {
var out = this.options.highlight(code, lang);
if (out != null && out !== code) {
escaped = true;
code = out;
}
}
if (!lang) {
return '<pre><code>'
+ (escaped ? code : escape(code, true))
+ '\n</code></pre>';
}
return '<pre><code class="'
+ this.options.langPrefix
+ escape(lang, true)
+ '">'
+ (escaped ? code : escape(code, true))
+ '\n</code></pre>\n';
};
Renderer.prototype.blockquote = function(quote) {
return '<blockquote>\n' + quote + '</blockquote>\n';
};
Renderer.prototype.html = function(html) {
return html;
};
Renderer.prototype.heading = function(text, level, raw) {
return '<h'
+ level
+ ' id="'
+ this.options.headerPrefix
+ raw.toLowerCase().replace(/[^\w]+/g, '-')
+ '">'
+ text
+ '</h'
+ level
+ '>\n';
};
Renderer.prototype.hr = function() {
return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
};
Renderer.prototype.list = function(body, ordered) {
var type = ordered ? 'ol' : 'ul';
return '<' + type + '>\n' + body + '</' + type + '>\n';
};
Renderer.prototype.listitem = function(text) {
return '<li>' + text + '</li>\n';
};
Renderer.prototype.paragraph = function(text) {
return '<p>' + text + '</p>\n';
};
Renderer.prototype.table = function(header, body) {
return '<table>\n'
+ '<thead>\n'
+ header
+ '</thead>\n'
+ '<tbody>\n'
+ body
+ '</tbody>\n'
+ '</table>\n';
};
Renderer.prototype.tablerow = function(content) {
return '<tr>\n' + content + '</tr>\n';
};
Renderer.prototype.tablecell = function(content, flags) {
var type = flags.header ? 'th' : 'td';
var tag = flags.align
? '<' + type + ' style="text-align:' + flags.align + '">'
: '<' + type + '>';
return tag + content + '</' + type + '>\n';
};
// span level renderer
Renderer.prototype.strong = function(text) {
return '<strong>' + text + '</strong>';
};
Renderer.prototype.em = function(text) {
return '<em>' + text + '</em>';
};
Renderer.prototype.codespan = function(text) {
return '<code>' + text + '</code>';
};
Renderer.prototype.br = function() {
return this.options.xhtml ? '<br/>' : '<br>';
};
Renderer.prototype.del = function(text) {
return '<del>' + text + '</del>';
};
Renderer.prototype.link = function(href, title, text) {
if (this.options.sanitize) {
try {
var prot = decodeURIComponent(unescape(href))
.replace(/[^\w:]/g, '')
.toLowerCase();
} catch (e) {
return '';
}
if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
return '';
}
}
var out = '<a href="' + href + '"';
if (title) {
out += ' title="' + title + '"';
}
out += '>' + text + '</a>';
return out;
};
Renderer.prototype.image = function(href, title, text) {
var out = '<img src="' + href + '" alt="' + text + '"';
if (title) {
out += ' title="' + title + '"';
}
out += this.options.xhtml ? '/>' : '>';
return out;
};
Renderer.prototype.text = function(text) {
return text;
};
/**
* Parsing & Compiling
*/
function Parser(options) {
this.tokens = [];
this.token = null;
this.options = options || marked.defaults;
this.options.renderer = this.options.renderer || new Renderer;
this.renderer = this.options.renderer;
this.renderer.options = this.options;
}
/**
* Static Parse Method
*/
Parser.parse = function(src, options, renderer) {
var parser = new Parser(options, renderer);
return parser.parse(src);
};
/**
* Parse Loop
*/
Parser.prototype.parse = function(src) {
var this$1 = this;
this.inline = new InlineLexer(src.links, this.options, this.renderer);
this.tokens = src.reverse();
var out = '';
while (this.next()) {
out += this$1.tok();
}
return out;
};
/**
* Next Token
*/
Parser.prototype.next = function() {
return this.token = this.tokens.pop();
};
/**
* Preview Next Token
*/
Parser.prototype.peek = function() {
return this.tokens[this.tokens.length - 1] || 0;
};
/**
* Parse Text Tokens
*/
Parser.prototype.parseText = function() {
var this$1 = this;
var body = this.token.text;
while (this.peek().type === 'text') {
body += '\n' + this$1.next().text;
}
return this.inline.output(body);
};
/**
* Parse Current Token
*/
Parser.prototype.tok = function() {
var this$1 = this;
switch (this.token.type) {
case 'space': {
return '';
}
case 'hr': {
return this.renderer.hr();
}
case 'heading': {
return this.renderer.heading(
this.inline.output(this.token.text),
this.token.depth,
this.token.text);
}
case 'code': {
return this.renderer.code(this.token.text,
this.token.lang,
this.token.escaped);
}
case 'table': {
var header = ''
, body = ''
, i
, row
, cell
, flags
, j;
// header
cell = '';
for (i = 0; i < this.token.header.length; i++) {
flags = { header: true, align: this$1.token.align[i] };
cell += this$1.renderer.tablecell(
this$1.inline.output(this$1.token.header[i]),
{ header: true, align: this$1.token.align[i] }
);
}
header += this.renderer.tablerow(cell);
for (i = 0; i < this.token.cells.length; i++) {
row = this$1.token.cells[i];
cell = '';
for (j = 0; j < row.length; j++) {
cell += this$1.renderer.tablecell(
this$1.inline.output(row[j]),
{ header: false, align: this$1.token.align[j] }
);
}
body += this$1.renderer.tablerow(cell);
}
return this.renderer.table(header, body);
}
case 'blockquote_start': {
var body = '';
while (this.next().type !== 'blockquote_end') {
body += this$1.tok();
}
return this.renderer.blockquote(body);
}
case 'list_start': {
var body = ''
, ordered = this.token.ordered;
while (this.next().type !== 'list_end') {
body += this$1.tok();
}
return this.renderer.list(body, ordered);
}
case 'list_item_start': {
var body = '';
while (this.next().type !== 'list_item_end') {
body += this$1.token.type === 'text'
? this$1.parseText()
: this$1.tok();
}
return this.renderer.listitem(body);
}
case 'loose_item_start': {
var body = '';
while (this.next().type !== 'list_item_end') {
body += this$1.tok();
}
return this.renderer.listitem(body);
}
case 'html': {
var html = !this.token.pre && !this.options.pedantic
? this.inline.output(this.token.text)
: this.token.text;
return this.renderer.html(html);
}
case 'paragraph': {
return this.renderer.paragraph(this.inline.output(this.token.text));
}
case 'text': {
return this.renderer.paragraph(this.parseText());
}
}
};
/**
* Helpers
*/
function escape(html, encode) {
return html
.replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function unescape(html) {
// explicitly match decimal, hex, and named HTML entities
return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
n = n.toLowerCase();
if (n === 'colon') { return ':'; }
if (n.charAt(0) === '#') {
return n.charAt(1) === 'x'
? String.fromCharCode(parseInt(n.substring(2), 16))
: String.fromCharCode(+n.substring(1));
}
return '';
});
}
function replace(regex, opt) {
regex = regex.source;
opt = opt || '';
return function self(name, val) {
if (!name) { return new RegExp(regex, opt); }
val = val.source || val;
val = val.replace(/(^|[^\[])\^/g, '$1');
regex = regex.replace(name, val);
return self;
};
}
function noop() {}
noop.exec = noop;
function merge(obj) {
var arguments$1 = arguments;
var i = 1
, target
, key;
for (; i < arguments.length; i++) {
target = arguments$1[i];
for (key in target) {
if (Object.prototype.hasOwnProperty.call(target, key)) {
obj[key] = target[key];
}
}
}
return obj;
}
/**
* Marked
*/
function marked(src, opt, callback) {
if (callback || typeof opt === 'function') {
if (!callback) {
callback = opt;
opt = null;
}
opt = merge({}, marked.defaults, opt || {});
var highlight = opt.highlight
, tokens
, pending
, i = 0;
try {
tokens = Lexer.lex(src, opt);
} catch (e) {
return callback(e);
}
pending = tokens.length;
var done = function(err) {
if (err) {
opt.highlight = highlight;
return callback(err);
}
var out;
try {
out = Parser.parse(tokens, opt);
} catch (e) {
err = e;
}
opt.highlight = highlight;
return err
? callback(err)
: callback(null, out);
};
if (!highlight || highlight.length < 3) {
return done();
}
delete opt.highlight;
if (!pending) { return done(); }
for (; i < tokens.length; i++) {
(function(token) {
if (token.type !== 'code') {
return --pending || done();
}
return highlight(token.text, token.lang, function(err, code) {
if (err) { return done(err); }
if (code == null || code === token.text) {
return --pending || done();
}
token.text = code;
token.escaped = true;
--pending || done();
});
})(tokens[i]);
}
return;
}
try {
if (opt) { opt = merge({}, marked.defaults, opt); }
return Parser.parse(Lexer.lex(src, opt), opt);
} catch (e) {
e.message += '\nPlease report this to https://github.com/chjj/marked.';
if ((opt || marked.defaults).silent) {
return '<p>An error occured:</p><pre>'
+ escape(e.message + '', true)
+ '</pre>';
}
throw e;
}
}
/**
* Options
*/
marked.options =
marked.setOptions = function(opt) {
merge(marked.defaults, opt);
return marked;
};
marked.defaults = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
sanitizer: null,
mangle: true,
smartLists: false,
silent: false,
highlight: null,
langPrefix: 'lang-',
smartypants: false,
headerPrefix: '',
renderer: new Renderer,
xhtml: false
};
/**
* Expose
*/
marked.Parser = Parser;
marked.parser = Parser.parse;
marked.Renderer = Renderer;
marked.Lexer = Lexer;
marked.lexer = Lexer.lex;
marked.InlineLexer = InlineLexer;
marked.inlineLexer = InlineLexer.output;
marked.parse = marked;
{
module.exports = marked;
}
}).call(function() {
return this || (typeof window !== 'undefined' ? window : commonjsGlobal);
}());
});
var prism = createCommonjsModule(function (module) {
/* **********************************************
Begin prism-core.js
********************************************** */
var _self = (typeof window !== 'undefined')
? window // if in browser
: (
(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope)
? self // if in worker
: {} // if in node js
);
/**
* Prism: Lightweight, robust, elegant syntax highlighting
* MIT license http://www.opensource.org/licenses/mit-license.php/
* @author Lea Verou http://lea.verou.me
*/
var Prism = (function(){
// Private helper vars
var lang = /\blang(?:uage)?-(\w+)\b/i;
var uniqueId = 0;
var _ = _self.Prism = {
util: {
encode: function (tokens) {
if (tokens instanceof Token) {
return new Token(tokens.type, _.util.encode(tokens.content), tokens.alias);
} else if (_.util.type(tokens) === 'Array') {
return tokens.map(_.util.encode);
} else {
return tokens.replace(/&/g, '&').replace(/</g, '<').replace(/\u00a0/g, ' ');
}
},
type: function (o) {
return Object.prototype.toString.call(o).match(/\[object (\w+)\]/)[1];
},
objId: function (obj) {
if (!obj['__id']) {
Object.defineProperty(obj, '__id', { value: ++uniqueId });
}
return obj['__id'];
},
// Deep clone a language definition (e.g. to extend it)
clone: function (o) {
var type = _.util.type(o);
switch (type) {
case 'Object':
var clone = {};
for (var key in o) {
if (o.hasOwnProperty(key)) {
clone[key] = _.util.clone(o[key]);
}
}
return clone;
case 'Array':
// Check for existence for IE8
return o.map && o.map(function(v) { return _.util.clone(v); });
}
return o;
}
},
languages: {
extend: function (id, redef) {
var lang = _.util.clone(_.languages[id]);
for (var key in redef) {
lang[key] = redef[key];
}
return lang;
},
/**
* Insert a token before another token in a language literal
* As this needs to recreate the object (we cannot actually insert before keys in object literals),
* we cannot just provide an object, we need anobject and a key.
* @param inside The key (or language id) of the parent
* @param before The key to insert before. If not provided, the function appends instead.
* @param insert Object with the key/value pairs to insert
* @param root The object that contains `inside`. If equal to Prism.languages, it can be omitted.
*/
insertBefore: function (inside, before, insert, root) {
root = root || _.languages;
var grammar = root[inside];
if (arguments.length == 2) {
insert = arguments[1];
for (var newToken in insert) {
if (insert.hasOwnProperty(newToken)) {
grammar[newToken] = insert[newToken];
}
}
return grammar;
}
var ret = {};
for (var token in grammar) {
if (grammar.hasOwnProperty(token)) {
if (token == before) {
for (var newToken in insert) {
if (insert.hasOwnProperty(newToken)) {
ret[newToken] = insert[newToken];
}
}
}
ret[token] = grammar[token];
}
}
// Update references in other language definitions
_.languages.DFS(_.languages, function(key, value) {
if (value === root[inside] && key != inside) {
this[key] = ret;
}
});
return root[inside] = ret;
},
// Traverse a language definition with Depth First Search
DFS: function(o, callback, type, visited) {
visited = visited || {};
for (var i in o) {
if (o.hasOwnProperty(i)) {
callback.call(o, i, o[i], type || i);
if (_.util.type(o[i]) === 'Object' && !visited[_.util.objId(o[i])]) {
visited[_.util.objId(o[i])] = true;
_.languages.DFS(o[i], callback, null, visited);
}
else if (_.util.type(o[i]) === 'Array' && !visited[_.util.objId(o[i])]) {
visited[_.util.objId(o[i])] = true;
_.languages.DFS(o[i], callback, i, visited);
}
}
}
}
},
plugins: {},
highlightAll: function(async, callback) {
var env = {
callback: callback,
selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'
};
_.hooks.run("before-highlightall", env);
var elements = env.elements || document.querySelectorAll(env.selector);
for (var i=0, element; element = elements[i++];) {
_.highlightElement(element, async === true, env.callback);
}
},
highlightElement: function(element, async, callback) {
// Find language
var language, grammar, parent = element;
while (parent && !lang.test(parent.className)) {
parent = parent.parentNode;
}
if (parent) {
language = (parent.className.match(lang) || [,''])[1].toLowerCase();
grammar = _.languages[language];
}
// Set language on the element, if not present
element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
// Set language on the parent, for styling
parent = element.parentNode;
if (/pre/i.test(parent.nodeName)) {
parent.className = parent.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
}
var code = element.textContent;
var env = {
element: element,
language: language,
grammar: grammar,
code: code
};
_.hooks.run('before-sanity-check', env);
if (!env.code || !env.grammar) {
if (env.code) {
env.element.textContent = env.code;
}
_.hooks.run('complete', env);
return;
}
_.hooks.run('before-highlight', env);
if (async && _self.Worker) {
var worker = new Worker(_.filename);
worker.onmessage = function(evt) {
env.highlightedCode = evt.data;
_.hooks.run('before-insert', env);
env.element.innerHTML = env.highlightedCode;
callback && callback.call(env.element);
_.hooks.run('after-highlight', env);
_.hooks.run('complete', env);
};
worker.postMessage(JSON.stringify({
language: env.language,
code: env.code,
immediateClose: true
}));
}
else {
env.highlightedCode = _.highlight(env.code, env.grammar, env.language);
_.hooks.run('before-insert', env);
env.element.innerHTML = env.highlightedCode;
callback && callback.call(element);
_.hooks.run('after-highlight', env);
_.hooks.run('complete', env);
}
},
highlight: function (text, grammar, language) {
var tokens = _.tokenize(text, grammar);
return Token.stringify(_.util.encode(tokens), language);
},
tokenize: function(text, grammar, language) {
var Token = _.Token;
var strarr = [text];
var rest = grammar.rest;
if (rest) {
for (var token in rest) {
grammar[token] = rest[token];
}
delete grammar.rest;
}
tokenloop: for (var token in grammar) {
if(!grammar.hasOwnProperty(token) || !grammar[token]) {
continue;
}
var patterns = grammar[token];
patterns = (_.util.type(patterns) === "Array") ? patterns : [patterns];
for (var j = 0; j < patterns.length; ++j) {
var pattern = patterns[j],
inside = pattern.inside,
lookbehind = !!pattern.lookbehind,
greedy = !!pattern.greedy,
lookbehindLength = 0,
alias = pattern.alias;
if (greedy && !pattern.pattern.global) {
// Without the global flag, lastIndex won't work
var flags = pattern.pattern.toString().match(/[imuy]*$/)[0];
pattern.pattern = RegExp(pattern.pattern.source, flags + "g");
}
pattern = pattern.pattern || pattern;
// Don’t cache length as it changes during the loop
for (var i=0, pos = 0; i<strarr.length; pos += strarr[i].length, ++i) {
var str = strarr[i];
if (strarr.length > text.length) {
// Something went terribly wrong, ABORT, ABORT!
break tokenloop;
}
if (str instanceof Token) {
continue;
}
pattern.lastIndex = 0;
var match = pattern.exec(str),
delNum = 1;
// Greedy patterns can override/remove up to two previously matched tokens
if (!match && greedy && i != strarr.length - 1) {
pattern.lastIndex = pos;
match = pattern.exec(text);
if (!match) {
break;
}
var from = match.index + (lookbehind ? match[1].length : 0),
to = match.index + match[0].length,
k = i,
p = pos;
for (var len = strarr.length; k < len && p < to; ++k) {
p += strarr[k].length;
// Move the index i to the element in strarr that is closest to from
if (from >= p) {
++i;
pos = p;
}
}
/*
* If strarr[i] is a Token, then the match starts inside another Token, which is invalid
* If strarr[k - 1] is greedy we are in conflict with another greedy pattern
*/
if (strarr[i] instanceof Token || strarr[k - 1].greedy) {
continue;
}
// Number of tokens to delete and replace with the new match
delNum = k - i;
str = text.slice(pos, p);
match.index -= pos;
}
if (!match) {
continue;
}
if(lookbehind) {
lookbehindLength = match[1].length;
}
var from = match.index + lookbehindLength,
match = match[0].slice(lookbehindLength),
to = from + match.length,
before = str.slice(0, from),
after = str.slice(to);
var args = [i, delNum];
if (before) {
args.push(before);
}
var wrapped = new Token(token, inside? _.tokenize(match, inside) : match, alias, match, greedy);
args.push(wrapped);
if (after) {
args.push(after);
}
Array.prototype.splice.apply(strarr, args);
}
}
}
return strarr;
},
hooks: {
all: {},
add: function (name, callback) {
var hooks = _.hooks.all;
hooks[name] = hooks[name] || [];
hooks[name].push(callback);
},
run: function (name, env) {
var callbacks = _.hooks.all[name];
if (!callbacks || !callbacks.length) {
return;
}
for (var i=0, callback; callback = callbacks[i++];) {
callback(env);
}
}
}
};
var Token = _.Token = function(type, content, alias, matchedStr, greedy) {
this.type = type;
this.content = content;
this.alias = alias;
// Copy of the full string this token was created from
this.length = (matchedStr || "").length|0;
this.greedy = !!greedy;
};
Token.stringify = function(o, language, parent) {
if (typeof o == 'string') {
return o;
}
if (_.util.type(o) === 'Array') {
return o.map(function(element) {
return Token.stringify(element, language, o);
}).join('');
}
var env = {
type: o.type,
content: Token.stringify(o.content, language, parent),
tag: 'span',
classes: ['token', o.type],
attributes: {},
language: language,
parent: parent
};
if (env.type == 'comment') {
env.attributes['spellcheck'] = 'true';
}
if (o.alias) {
var aliases = _.util.type(o.alias) === 'Array' ? o.alias : [o.alias];
Array.prototype.push.apply(env.classes, aliases);
}
_.hooks.run('wrap', env);
var attributes = Object.keys(env.attributes).map(function(name) {
return name + '="' + (env.attributes[name] || '').replace(/"/g, '"') + '"';
}).join(' ');
return '<' + env.tag + ' class="' + env.classes.join(' ') + '"' + (attributes ? ' ' + attributes : '') + '>' + env.content + '</' + env.tag + '>';
};
if (!_self.document) {
if (!_self.addEventListener) {
// in Node.js
return _self.Prism;
}
// In worker
_self.addEventListener('message', function(evt) {
var message = JSON.parse(evt.data),
lang = message.language,
code = message.code,
immediateClose = message.immediateClose;
_self.postMessage(_.highlight(code, _.languages[lang], lang));
if (immediateClose) {
_self.close();
}
}, false);
return _self.Prism;
}
//Get current script and highlight
var script = document.currentScript || [].slice.call(document.getElementsByTagName("script")).pop();
if (script) {
_.filename = script.src;
if (document.addEventListener && !script.hasAttribute('data-manual')) {
if(document.readyState !== "loading") {
if (window.requestAnimationFrame) {
window.requestAnimationFrame(_.highlightAll);
} else {
window.setTimeout(_.highlightAll, 16);
}
}
else {
document.addEventListener('DOMContentLoaded', _.highlightAll);
}
}
}
return _self.Prism;
})();
if ('object' !== 'undefined' && module.exports) {
module.exports = Prism;
}
// hack for components to work correctly in node.js
if (typeof commonjsGlobal !== 'undefined') {
commonjsGlobal.Prism = Prism;
}
/* **********************************************
Begin prism-markup.js
********************************************** */
Prism.languages.markup = {
'comment': /<!--[\w\W]*?-->/,
'prolog': /<\?[\w\W]+?\?>/,
'doctype': /<!DOCTYPE[\w\W]+?>/i,
'cdata': /<!\[CDATA\[[\w\W]*?]]>/i,
'tag': {
pattern: /<\/?(?!\d)[^\s>\/=$<]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\\1|\\?(?!\1)[\w\W])*\1|[^\s'">=]+))?)*\s*\/?>/i,
inside: {
'tag': {
pattern: /^<\/?[^\s>\/]+/i,
inside: {
'punctuation': /^<\/?/,
'namespace': /^[^\s>\/:]+:/
}
},
'attr-value': {
pattern: /=(?:('|")[\w\W]*?(\1)|[^\s>]+)/i,
inside: {
'punctuation': /[=>"']/
}
},
'punctuation': /\/?>/,
'attr-name': {
pattern: /[^\s>\/]+/,
inside: {
'namespace': /^[^\s>\/:]+:/
}
}
}
},
'entity': /&#?[\da-z]{1,8};/i
};
// Plugin to make entity title show the real entity, idea by Roman Komarov
Prism.hooks.add('wrap', function(env) {
if (env.type === 'entity') {
env.attributes['title'] = env.content.replace(/&/, '&');
}
});
Prism.languages.xml = Prism.languages.markup;
Prism.languages.html = Prism.languages.markup;
Prism.languages.mathml = Prism.languages.markup;
Prism.languages.svg = Prism.languages.markup;
/* **********************************************
Begin prism-css.js
********************************************** */
Prism.languages.css = {
'comment': /\/\*[\w\W]*?\*\//,
'atrule': {
pattern: /@[\w-]+?.*?(;|(?=\s*\{))/i,
inside: {
'rule': /@[\w-]+/
// See rest below
}
},
'url': /url\((?:(["'])(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1|.*?)\)/i,
'selector': /[^\{\}\s][^\{\};]*?(?=\s*\{)/,
'string': {
pattern: /("|')(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1/,
greedy: true
},
'property': /(\b|\B)[\w-]+(?=\s*:)/i,
'important': /\B!important\b/i,
'function': /[-a-z0-9]+(?=\()/i,
'punctuation': /[(){};:]/
};
Prism.languages.css['atrule'].inside.rest = Prism.util.clone(Prism.languages.css);
if (Prism.languages.markup) {
Prism.languages.insertBefore('markup', 'tag', {
'style': {
pattern: /(<style[\w\W]*?>)[\w\W]*?(?=<\/style>)/i,
lookbehind: true,
inside: Prism.languages.css,
alias: 'language-css'
}
});
Prism.languages.insertBefore('inside', 'attr-value', {
'style-attr': {
pattern: /\s*style=("|').*?\1/i,
inside: {
'attr-name': {
pattern: /^\s*style/i,
inside: Prism.languages.markup.tag.inside
},
'punctuation': /^\s*=\s*['"]|['"]\s*$/,
'attr-value': {
pattern: /.+/i,
inside: Prism.languages.css
}
},
alias: 'language-css'
}
}, Prism.languages.markup.tag);
}
/* **********************************************
Begin prism-clike.js
********************************************** */
Prism.languages.clike = {
'comment': [
{
pattern: /(^|[^\\])\/\*[\w\W]*?\*\//,
lookbehind: true
},
{
pattern: /(^|[^\\:])\/\/.*/,
lookbehind: true
}
],
'string': {
pattern: /(["'])(\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
greedy: true
},
'class-name': {
pattern: /((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/i,
lookbehind: true,
inside: {
punctuation: /(\.|\\)/
}
},
'keyword': /\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,
'boolean': /\b(true|false)\b/,
'function': /[a-z0-9_]+(?=\()/i,
'number': /\b-?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)\b/i,
'operator': /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/,
'punctuation': /[{}[\];(),.:]/
};
/* **********************************************
Begin prism-javascript.js
********************************************** */
Prism.languages.javascript = Prism.languages.extend('clike', {
'keyword': /\b(as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)\b/,
'number': /\b-?(0x[\dA-Fa-f]+|0b[01]+|0o[0-7]+|\d*\.?\d+([Ee][+-]?\d+)?|NaN|Infinity)\b/,
// Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
'function': /[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*(?=\()/i,
'operator': /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*\*?|\/|~|\^|%|\.{3}/
});
Prism.languages.insertBefore('javascript', 'keyword', {
'regex': {
pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\\\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})]))/,
lookbehind: true,
greedy: true
}
});
Prism.languages.insertBefore('javascript', 'string', {
'template-string': {
pattern: /`(?:\\\\|\\?[^\\])*?`/,
greedy: true,
inside: {
'interpolation': {
pattern: /\$\{[^}]+\}/,
inside: {
'interpolation-punctuation': {
pattern: /^\$\{|\}$/,
alias: 'punctuation'
},
rest: Prism.languages.javascript
}
},
'string': /[\s\S]+/
}
}
});
if (Prism.languages.markup) {
Prism.languages.insertBefore('markup', 'tag', {
'script': {
pattern: /(<script[\w\W]*?>)[\w\W]*?(?=<\/script>)/i,
lookbehind: true,
inside: Prism.languages.javascript,
alias: 'language-javascript'
}
});
}
Prism.languages.js = Prism.languages.javascript;
/* **********************************************
Begin prism-file-highlight.js
********************************************** */
(function () {
if (typeof self === 'undefined' || !self.Prism || !self.document || !document.querySelector) {
return;
}
self.Prism.fileHighlight = function() {
var Extensions = {
'js': 'javascript',
'py': 'python',
'rb': 'ruby',
'ps1': 'powershell',
'psm1': 'powershell',
'sh': 'bash',
'bat': 'batch',
'h': 'c',
'tex': 'latex'
};
if(Array.prototype.forEach) { // Check to prevent error in IE8
Array.prototype.slice.call(document.querySelectorAll('pre[data-src]')).forEach(function (pre) {
var src = pre.getAttribute('data-src');
var language, parent = pre;
var lang = /\blang(?:uage)?-(?!\*)(\w+)\b/i;
while (parent && !lang.test(parent.className)) {
parent = parent.parentNode;
}
if (parent) {
language = (pre.className.match(lang) || [, ''])[1];
}
if (!language) {
var extension = (src.match(/\.(\w+)$/) || [, ''])[1];
language = Extensions[extension] || extension;
}
var code = document.createElement('code');
code.className = 'language-' + language;
pre.textContent = '';
code.textContent = 'Loading…';
pre.appendChild(code);
var xhr = new XMLHttpRequest();
xhr.open('GET', src, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status < 400 && xhr.responseText) {
code.textContent = xhr.responseText;
Prism.highlightElement(code);
}
else if (xhr.status >= 400) {
code.textContent = '✖ Error ' + xhr.status + ' while fetching file: ' + xhr.statusText;
}
else {
code.textContent = '✖ Error: File does not exist or is empty';
}
}
};
xhr.send(null);
});
}
};
document.addEventListener('DOMContentLoaded', self.Prism.fileHighlight);
})();
});
/**
* gen toc tree
* @link https://github.com/killercup/grock/blob/5280ae63e16c5739e9233d9009bc235ed7d79a50/styles/solarized/assets/js/behavior.coffee#L54-L81
* @param {Array} toc
* @param {Number} maxLevel
* @return {Array}
*/
function genTree (toc, maxLevel) {
var headlines = [];
var last = {};
toc.forEach(function (headline) {
var level = headline.level || 1;
var len = level - 1;
if (level > maxLevel) { return }
if (last[len]) {
last[len].children = (last[len].children || []).concat(headline);
} else {
headlines.push(headline);
}
last[level] = headline;
});
return headlines
}
var cache$1 = {};
var re = /[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,.\/:;<=>?@\[\]^`{|}~]/g;
function slugify (str) {
if (typeof str !== 'string') { return '' }
var slug = str.toLowerCase().trim()
.replace(/<[^>\d]+>/g, '')
.replace(re, '')
.replace(/\s/g, '-')
.replace(/-+/g, '-')
.replace(/^(\d)/, '_$1');
var count = cache$1[slug];
count = cache$1.hasOwnProperty(slug) ? (count + 1) : 0;
cache$1[slug] = count;
if (count) {
slug = slug + '-' + count;
}
return slug
}
slugify.clear = function () {
cache$1 = {};
};
function replace (m, $1) {
return '<img class="emoji" src="https://assets-cdn.github.com/images/icons/emoji/' + $1 + '.png" alt="' + $1 + '" />'
}
function emojify (text) {
return text
.replace(/<(pre|template|code)[^>]*?>[\s\S]+?<\/(pre|template|code)>/g, function (m) { return m.replace(/:/g, '__colon__'); })
.replace(/:(\w+?):/ig, window.emojify || replace)
.replace(/__colon__/g, ':')
}
var markdownCompiler = marked;
var contentBase = '';
var currentPath = '';
var renderer = new marked.Renderer();
var cacheTree = {};
var toc = [];
/**
* Compile markdown content
*/
var markdown = cached(function (text) {
var html = '';
if (!text) { return text }
html = markdownCompiler(text);
html = emojify(html);
slugify.clear();
return html
});
markdown.renderer = renderer;
markdown.init = function (config, base) {
if ( config === void 0 ) config = {};
if ( base === void 0 ) base = window.location.pathname;
contentBase = getBasePath(base);
currentPath = parse().path;
if (isFn(config)) {
markdownCompiler = config(marked, renderer);
} else {
renderer = merge(renderer, config.renderer);
marked.setOptions(merge(config, { renderer: renderer }));
}
};
markdown.update = function () {
currentPath = parse().path;
};
/**
* render anchor tag
* @link https://github.com/chjj/marked#overriding-renderer-methods
*/
renderer.heading = function (text, level) {
var slug = slugify(text);
var url = toURL(currentPath, { id: slug });
toc.push({ level: level, slug: url, title: text });
return ("<h" + level + " id=\"" + slug + "\"><a href=\"" + url + "\" data-id=\"" + slug + "\" class=\"anchor\"><span>" + text + "</span></a></h" + level + ">")
};
// highlight code
renderer.code = function (code, lang) {
if ( lang === void 0 ) lang = '';
var hl = prism.highlight(code, prism.languages[lang] || prism.languages.markup);
return ("<pre v-pre data-lang=\"" + lang + "\"><code class=\"lang-" + lang + "\">" + hl + "</code></pre>")
};
renderer.link = function (href, title, text) {
var blank = '';
if (!/:|(\/{2})/.test(href)) {
href = toURL(href);
} else {
blank = ' target="_blank"';
}
if (title) {
title = " title=\"" + title + "\"";
}
return ("<a href=\"" + href + "\"" + title + blank + ">" + text + "</a>")
};
renderer.paragraph = function (text) {
if (/^!>/.test(text)) {
return helper('tip', text)
} else if (/^\?>/.test(text)) {
return helper('warn', text)
}
return ("<p>" + text + "</p>")
};
renderer.image = function (href, title, text) {
var url = href;
var titleHTML = title ? (" title=\"" + title + "\"") : '';
if (!isAbsolutePath(href)) {
url = getPath(contentBase, href);
}
return ("<img src=\"" + url + "\" data-origin=\"" + href + "\" alt=\"" + text + "\"" + titleHTML + ">")
};
/**
* Compile sidebar
*/
function sidebar (text, level) {
var html = '';
if (text) {
html = markdown(text);
html = html.match(/<ul[^>]*>([\s\S]+)<\/ul>/g)[0];
} else {
var tree$$1 = genTree(toc, level);
html = tree(tree$$1, '<ul>');
}
return html
}
/**
* Compile sub sidebar
*/
function subSidebar (el, level) {
if (el) {
toc[0] && toc[0].level === 1 && toc.shift();
var tree$$1 = cacheTree[currentPath] || genTree(toc, level);
el.parentNode.innerHTML += tree(tree$$1, '<ul class="app-sub-sidebar">');
cacheTree[currentPath] = tree$$1;
}
toc = [];
}
/**
* Compile cover page
*/
function cover$1 (text) {
var cacheToc = toc.slice();
var html = markdown(text);
toc = cacheToc.slice();
return html
}
var render = Object.freeze({
markdown: markdown,
sidebar: sidebar,
subSidebar: subSidebar,
cover: cover$1
});
function executeScript () {
var script = findAll('.markdown-section>script')
.filter(function (s) { return !/template/.test(s.type); })[0];
if (!script) { return false }
var code = script.innerText.trim();
if (!code) { return false }
setTimeout(function (_) {
window.__EXECUTE_RESULT__ = new Function(code)();
}, 0);
}
function renderMain (html) {
if (!html) {
// TODO: Custom 404 page
html = 'not found';
}
this._renderTo('.markdown-section', html);
// Render sidebar with the TOC
!this.config.loadSidebar && this._renderSidebar();
// execute script
if (this.config.executeScript !== false &&
typeof window.Vue !== 'undefined' &&
!executeScript()) {
setTimeout(function (_) {
var vueVM = window.__EXECUTE_RESULT__;
vueVM && vueVM.$destroy && vueVM.$destroy();
window.__EXECUTE_RESULT__ = new window.Vue().$mount('#main');
}, 0);
} else {
this.config.executeScript && executeScript();
}
if (this.config.auto2top) {
scroll2Top(this.config.auto2top);
}
}
function renderMixin (proto) {
proto._renderTo = function (el, content, replace) {
var node = getNode(el);
if (node) { node[replace ? 'outerHTML' : 'innerHTML'] = content; }
};
proto._renderSidebar = function (text) {
var ref = this.config;
var maxLevel = ref.maxLevel;
var subMaxLevel = ref.subMaxLevel;
var autoHeader = ref.autoHeader;
var loadSidebar = ref.loadSidebar;
this._renderTo('.sidebar-nav', sidebar(text, maxLevel));
var active = getAndActive('.sidebar-nav', true, true);
loadSidebar && subSidebar(active, subMaxLevel);
// bind event
this.activeLink = active;
scrollActiveSidebar();
if (autoHeader && active) {
var main$$1 = getNode('#main');
var firstNode = main$$1.children[0];
if (firstNode && firstNode.tagName !== 'H1') {
var h1 = create('h1');
h1.innerText = active.innerText;
before(main$$1, h1);
}
}
};
proto._renderNav = function (text) {
text && this._renderTo('nav', markdown(text));
getAndActive('nav');
};
proto._renderMain = function (text) {
var this$1 = this;
callHook(this, 'beforeEach', text, function (result) {
var html = this$1.isHTML ? result : markdown(result);
callHook(this$1, 'afterEach', html, function (text) { return renderMain.call(this$1, text); });
});
};
proto._renderCover = function (text) {
var el = getNode('.cover');
if (!text) {
toggleClass(el, 'remove', 'show');
return
}
toggleClass(el, 'add', 'show');
var html = this.coverIsHTML ? text : cover$1(text);
var m = html.trim().match('<p><img.*?data-origin="(.*?)"[^a]+alt="(.*?)">([^<]*?)</p>$');
if (m) {
if (m[2] === 'color') {
el.style.background = m[1] + (m[3] || '');
} else {
var path = m[1];
toggleClass(el, 'add', 'has-mask');
if (isAbsolutePath(m[1])) {
path = getPath(getBasePath(this.config.basePath), m[1]);
}
el.style.backgroundImage = "url(" + path + ")";
}
html = html.replace(m[0], '');
}
this._renderTo('.cover-main', html);
sticky();
};
proto._updateRender = function () {
markdown.update();
};
}
function initRender (vm) {
var config = vm.config;
// Init markdown compiler
markdown.init(config.markdown, config.basePath);
var id = config.el || '#app';
var navEl = find('nav') || create('nav');
var el = find(id);
var html = '';
navEl.classList.add('app-nav');
if (!config.repo) {
navEl.classList.add('no-badge');
}
if (!el) {
el = create(id);
appendTo(body, el);
}
if (config.repo) {
html += corner(config.repo);
}
if (config.coverpage) {
html += cover();
}
html += main(config);
// Render main app
vm._renderTo(el, html, true);
// Add nav
before(body, navEl);
if (config.themeColor) {
$.head.innerHTML += theme(config.themeColor);
// Polyfll
cssVars(config.themeColor);
}
toggleClass(body, 'ready');
}
function getAlias (path, alias) {
return alias[path] ? getAlias(alias[path], alias) : path
}
function getFileName (path) {
return /\.(md|html)$/g.test(path)
? path
: /\/$/g.test(path)
? (path + "README.md")
: (path + ".md")
}
function routeMixin (proto) {
proto.route = {};
proto.$getFile = function (path) {
var ref = this;
var config = ref.config;
var base = getBasePath(config.basePath);
path = config.alias ? getAlias(path, config.alias) : path;
path = getFileName(path);
path = path === '/README.md' ? (config.homepage || path) : path;
path = isAbsolutePath(path) ? path : getPath(base, path);
return path
};
}
var lastRoute = {};
function initRoute (vm) {
normalize();
lastRoute = vm.route = parse();
on('hashchange', function (_) {
normalize();
vm.route = parse();
vm._updateRender();
if (lastRoute.path === vm.route.path) {
vm.$resetEvents();
return
}
vm.$fetch();
lastRoute = vm.route;
});
}
function eventMixin (proto) {
proto.$resetEvents = function () {
scrollIntoView(this.route.query.id);
getAndActive('nav');
};
}
function initEvent (vm) {
// Bind toggle button
btn('button.sidebar-toggle');
// Bind sticky effect
if (vm.config.coverpage) {
!isMobile && on('scroll', sticky);
} else {
body.classList.add('sticky');
}
}
function fetchMixin (proto) {
var last;
proto._fetch = function (cb) {
var this$1 = this;
if ( cb === void 0 ) cb = noop;
var ref = this.route;
var path = ref.path;
var ref$1 = this.config;
var loadNavbar = ref$1.loadNavbar;
var loadSidebar = ref$1.loadSidebar;
var root = getRoot(path);
// Abort last request
last && last.abort && last.abort();
last = get(this.$getFile(path), true);
// Current page is html
this.isHTML = /\.html$/g.test(path);
// Load main content
last.then(function (text) {
this$1._renderMain(text);
if (!loadSidebar) { return cb() }
var fn = function (result) { this$1._renderSidebar(result); cb(); };
// Load sidebar
get(this$1.$getFile(root + loadSidebar))
// fallback root navbar when fail
.then(fn, function (_) { return get(loadSidebar).then(fn); });
},
function (_) { return this$1._renderMain(null); });
// Load nav
loadNavbar &&
get(this.$getFile(root + loadNavbar))
.then(
function (text) { return this$1._renderNav(text); },
// fallback root navbar when fail
function (_) { return get(loadNavbar).then(function (text) { return this$1._renderNav(text); }); }
);
};
proto._fetchCover = function () {
var this$1 = this;
var ref = this.config;
var coverpage = ref.coverpage;
var root = getRoot(this.route.path);
var path = this.$getFile(root + coverpage);
if (this.route.path !== '/' || !coverpage) {
this._renderCover();
return
}
this.coverIsHTML = /\.html$/g.test(path);
get(path)
.then(function (text) { return this$1._renderCover(text); });
};
proto.$fetch = function (cb) {
var this$1 = this;
if ( cb === void 0 ) cb = noop;
this._fetchCover();
this._fetch(function (result) {
this$1.$resetEvents();
callHook(this$1, 'doneEach');
cb();
});
};
}
function initFetch (vm) {
vm.$fetch(function (_) { return callHook(vm, 'ready'); });
}
function initMixin (proto) {
proto._init = function () {
var vm = this;
vm.config = config || {};
initLifecycle(vm); // Init hooks
initPlugin(vm); // Install plugins
callHook(vm, 'init');
initRender(vm); // Render base DOM
initEvent(vm); // Bind events
initRoute(vm); // Add hashchange eventListener
initFetch(vm); // Fetch data
callHook(vm, 'mounted');
};
}
function initPlugin (vm) {
[].concat(vm.config.plugins).forEach(function (fn) { return isFn(fn) && fn(vm._lifecycle, vm); });
}
var util = Object.freeze({
cached: cached,
hyphenate: hyphenate,
merge: merge,
isPrimitive: isPrimitive,
noop: noop,
isFn: isFn,
UA: UA,
isIE: isIE,
isMobile: isMobile
});
var initGlobalAPI = function () {
window.Docsify = { util: util, dom: dom, render: render, route: route, get: get, slugify: slugify };
window.marked = marked;
window.Prism = prism;
};
function Docsify () {
this._init();
}
var proto = Docsify.prototype;
initMixin(proto);
routeMixin(proto);
renderMixin(proto);
fetchMixin(proto);
eventMixin(proto);
/**
* Global API
*/
initGlobalAPI();
/**
* Run Docsify
*/
setTimeout(function (_) { return new Docsify(); }, 0);
}());
|
Asaf-S/jsdelivr
|
files/docsify/3.1.0/lib/docsify.js
|
JavaScript
|
mit
| 80,623
|
"use strict";
var fs = require('fs');
var os = require('os');
var path = require('path');
var q = require('q');
var binaries_1 = require('../binaries');
var downloaded_binary_1 = require('./downloaded_binary');
var downloader_1 = require('./downloader');
var cli_1 = require('../cli');
var gecko_driver_1 = require('../binaries/gecko_driver');
var logger = new cli_1.Logger('file_manager');
/**
* The File Manager class is where the webdriver manager will compile a list of
* binaries that could be downloaded and get a list of previously downloaded
* file versions.
*/
var FileManager = (function () {
function FileManager() {
}
/**
* Create a directory if it does not exist.
* @param outputDir The directory to create.
*/
FileManager.makeOutputDirectory = function (outputDir) {
try {
fs.statSync(outputDir);
}
catch (e) {
logger.info('creating folder ' + outputDir);
fs.mkdirSync(outputDir);
}
};
/**
* For the operating system, check against the list of operating systems that the
* binary is available for.
* @param osType The operating system.
* @param binary The class type to have access to the static properties.
* @returns If the binary is available for the operating system.
*/
FileManager.checkOS_ = function (osType, binary) {
for (var os_1 in binary.os) {
if (binaries_1.OS[os_1] == osType) {
return true;
}
}
return false;
};
/**
* For the operating system, create a list that includes the binaries
* for selenium standalone, chrome, and internet explorer.
* @param osType The operating system.
* @param alternateCDN URL of the alternative CDN to be used instead of the default ones.
* @returns A binary map that are available for the operating system.
*/
FileManager.compileBinaries_ = function (osType, alternateCDN) {
var binaries = {};
if (FileManager.checkOS_(osType, binaries_1.StandAlone)) {
binaries[binaries_1.StandAlone.id] = new binaries_1.StandAlone(alternateCDN);
}
if (FileManager.checkOS_(osType, binaries_1.ChromeDriver)) {
binaries[binaries_1.ChromeDriver.id] = new binaries_1.ChromeDriver(alternateCDN);
}
if (FileManager.checkOS_(osType, gecko_driver_1.GeckoDriver)) {
binaries[gecko_driver_1.GeckoDriver.id] = new gecko_driver_1.GeckoDriver(alternateCDN);
}
if (FileManager.checkOS_(osType, binaries_1.IEDriver)) {
binaries[binaries_1.IEDriver.id] = new binaries_1.IEDriver(alternateCDN);
}
if (FileManager.checkOS_(osType, binaries_1.AndroidSDK)) {
binaries[binaries_1.AndroidSDK.id] = new binaries_1.AndroidSDK(alternateCDN);
}
if (FileManager.checkOS_(osType, binaries_1.Appium)) {
binaries[binaries_1.Appium.id] = new binaries_1.Appium(alternateCDN);
}
return binaries;
};
/**
* Look up the operating system and compile a list of binaries that are available
* for the system.
* @param alternateCDN URL of the alternative CDN to be used instead of the default ones.
* @returns A binary map that is available for the operating system.
*/
FileManager.setupBinaries = function (alternateCDN) {
return FileManager.compileBinaries_(os.type(), alternateCDN);
};
/**
* Get the list of existing files from the output directory
* @param outputDir The directory where binaries are saved
* @returns A list of existing files.
*/
FileManager.getExistingFiles = function (outputDir) {
try {
return fs.readdirSync(outputDir);
}
catch (e) {
return [];
}
};
/**
* For the binary, operating system, and system architecture, look through
* the existing files and the downloaded binary
* @param binary The binary of interest
* @param osType The operating system.
* @param existingFiles A list of existing files.
* @returns The downloaded binary with all the versions found.
*/
FileManager.downloadedVersions_ = function (binary, osType, arch, existingFiles) {
var versions = [];
for (var existPos in existingFiles) {
var existFile = existingFiles[existPos];
// use only files that have a prefix and suffix that we care about
if (existFile.indexOf(binary.prefix()) === 0) {
var editExistFile = existFile.replace(binary.prefix(), '');
// if the suffix matches the executable suffix, add it
if (binary.suffix(osType, arch) === binary.executableSuffix(osType)) {
versions.push(editExistFile.replace(binary.suffix(osType, arch), ''));
}
else if (existFile.indexOf(binary.suffix(osType, arch)) === -1) {
editExistFile = editExistFile.replace(binary.executableSuffix(osType), '');
editExistFile = editExistFile.indexOf('_') === 0 ?
editExistFile.substring(1, editExistFile.length) :
editExistFile;
versions.push(editExistFile);
}
}
}
if (versions.length === 0) {
return null;
}
var downloadedBinary = new downloaded_binary_1.DownloadedBinary(binary);
downloadedBinary.versions = versions;
return downloadedBinary;
};
/**
* Finds all the downloaded binary versions stored in the output directory.
* @param outputDir The directory where files are downloaded and stored.
* @returns An dictionary map of all the downloaded binaries found in the output folder.
*/
FileManager.downloadedBinaries = function (outputDir) {
var ostype = os.type();
var arch = os.arch();
var binaries = FileManager.setupBinaries();
var existingFiles = FileManager.getExistingFiles(outputDir);
var downloaded = {};
for (var bin in binaries) {
var binary = FileManager.downloadedVersions_(binaries[bin], ostype, arch, existingFiles);
if (binary != null) {
downloaded[binary.id()] = binary;
}
}
return downloaded;
};
/**
* Check to see if the binary version should be downloaded.
* @param binary The binary of interest.
* @param outputDir The directory where files are downloaded and stored.
* @returns If the file should be downloaded.
*/
FileManager.toDownload = function (binary, outputDir, proxy, ignoreSSL) {
var osType = os.type();
var osArch = os.arch();
var filePath;
var readData;
var deferred = q.defer();
var downloaded = FileManager.downloadedBinaries(outputDir);
if (downloaded[binary.id()]) {
var downloadedBinary = downloaded[binary.id()];
var versions = downloadedBinary.versions;
var version = binary.version();
for (var index in versions) {
var v = versions[index];
if (v === version) {
filePath = path.resolve(outputDir, binary.filename(osType, osArch));
readData = fs.readFileSync(filePath);
// we have the version, verify it is the correct file size
var contentLength = downloader_1.Downloader.httpHeadContentLength(binary.url(osType, osArch), proxy, ignoreSSL);
return contentLength.then(function (value) {
if (value == readData.length) {
return false;
}
else {
logger.warn(path.basename(filePath) + ' expected length ' + value + ', found ' +
readData.length);
logger.warn('removing file: ' + filePath);
return true;
}
});
}
}
}
deferred.resolve(true);
return deferred.promise;
};
/**
* Removes the existing files found in the output directory that match the
* binary prefix names.
* @param outputDir The directory where files are downloaded and stored.
*/
FileManager.removeExistingFiles = function (outputDir) {
try {
fs.statSync(outputDir);
}
catch (e) {
logger.warn('path does not exist ' + outputDir);
return;
}
var existingFiles = FileManager.getExistingFiles(outputDir);
if (existingFiles.length === 0) {
logger.warn('no files found in path ' + outputDir);
return;
}
var binaries = FileManager.setupBinaries();
existingFiles.forEach(function (file) {
for (var binPos in binaries) {
var bin = binaries[binPos];
if (file.indexOf(bin.prefix()) !== -1) {
bin.remove(path.join(outputDir, file));
logger.info('removed ' + file);
}
}
});
};
return FileManager;
}());
exports.FileManager = FileManager;
//# sourceMappingURL=file_manager.js.map
|
sbraaten95/angular_tour_of_heroes
|
node_modules/webdriver-manager/built/lib/files/file_manager.js
|
JavaScript
|
mit
| 9,433
|
/*************************************************************
*
* MathJax/jax/output/SVG/fonts/TeX/svg/AMS/Regular/LatinExtendedA.js
*
* Copyright (c) 2011-2013 The MathJax Consortium
*
* Licensed 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.
*
*/
MathJax.Hub.Insert(
MathJax.OutputJax.SVG.FONTDATA.FONTS['MathJax_AMS'],
{
// LATIN SMALL LETTER H WITH STROKE
0x127: [695,13,540,42,562,'182 599Q182 611 174 615T133 619Q118 619 114 621T109 630Q109 636 114 656T122 681Q125 685 202 688Q272 695 286 695Q304 695 304 684Q304 682 295 644T282 597Q282 592 360 592H399Q430 592 445 587T460 563Q460 552 451 541L442 535H266L251 468Q247 453 243 436T236 409T233 399Q233 395 244 404Q295 441 357 441Q405 441 445 417T485 333Q485 284 449 178T412 58T426 44Q447 44 466 68Q485 87 500 130L509 152H531H543Q562 152 562 144Q562 128 546 93T494 23T415 -13Q385 -13 359 3T322 44Q318 52 318 77Q318 99 352 196T386 337Q386 386 346 386Q318 386 286 370Q267 361 245 338T211 292Q207 287 193 235T162 113T138 21Q128 7 122 4Q105 -12 83 -12Q66 -12 54 -2T42 26L166 530Q166 534 161 534T129 535Q127 535 122 535T112 534Q74 534 74 562Q74 570 77 576T84 585T96 589T109 591T124 592T138 592L182 595V599']
}
);
MathJax.Ajax.loadComplete(MathJax.OutputJax.SVG.fontDir+"/AMS/Regular/LatinExtendedA.js");
|
shayzluf/lazoozweb
|
wiki/extensions/Math/modules/MathJax/unpacked/jax/output/SVG/fonts/TeX/AMS/Regular/LatinExtendedA.js
|
JavaScript
|
gpl-2.0
| 1,782
|
var NAVTREEINDEX0 =
{
"index.html":[],
"md__benchmarks.html":[8],
"md__building.html":[0],
"md__compiler.html":[1],
"md__cpp_usage.html":[3],
"md__go_usage.html":[4],
"md__grammar.html":[11],
"md__internals.html":[10],
"md__java_usage.html":[5],
"md__python_usage.html":[6],
"md__schemas.html":[2],
"md__support.html":[7],
"md__white_paper.html":[9],
"pages.html":[]
};
|
yaolinz/flatbuffers
|
docs/html/navtreeindex0.js
|
JavaScript
|
apache-2.0
| 370
|
(function(){
if (typeof self === 'undefined' || !self.Prism || !self.document) {
return;
}
if (!Prism.plugins.toolbar) {
console.warn('Copy to Clipboard plugin loaded before Toolbar plugin.');
return;
}
var Clipboard = window.Clipboard || undefined;
if (Clipboard && /(native code)/.test(Clipboard.toString())) {
Clipboard = undefined;
}
if (!Clipboard && typeof require === 'function') {
Clipboard = require('clipboard');
}
var callbacks = [];
if (!Clipboard) {
var script = document.createElement('script');
var head = document.querySelector('head');
script.onload = function() {
Clipboard = window.Clipboard;
if (Clipboard) {
while (callbacks.length) {
callbacks.pop()();
}
}
};
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.7.1/clipboard.min.js';
head.appendChild(script);
}
Prism.plugins.toolbar.registerButton('copy-to-clipboard', function (env) {
var linkCopy = document.createElement('a');
linkCopy.textContent = 'Copy';
if (!Clipboard) {
callbacks.push(registerClipboard);
} else {
registerClipboard();
}
return linkCopy;
function registerClipboard() {
var clip = new Clipboard(linkCopy, {
'text': function () {
return env.code;
}
});
clip.on('success', function() {
linkCopy.textContent = 'Copied!';
resetText();
});
clip.on('error', function () {
linkCopy.textContent = 'Press Ctrl+C to copy';
resetText();
});
}
function resetText() {
setTimeout(function () {
linkCopy.textContent = 'Copy';
}, 5000);
}
});
})();
|
uvalib/staff-directory
|
bower_components/prism/plugins/copy-to-clipboard/prism-copy-to-clipboard.js
|
JavaScript
|
apache-2.0
| 1,606
|
/* =========================================================
* composer-atts.js v0.2.1
* =========================================================
* Copyright 2013 Wpbakery
*
* Visual composer backbone/underscore shortcodes attributes
* form field and parsing controls
* ========================================================= */
var vc = {
filters: {templates: []}, addTemplateFilter: function (callback) {
if (_.isFunction(callback)) this.filters.templates.push(callback);
}
};
(function ($) {
var wpb_change_tab_title, wpb_change_accordion_tab_title, vc_activeMce;
wpb_change_tab_title = function ($element, field) {
$('.tabs_controls a[href=#tab-' + $(field).val() + ']').text($('.wpb-edit-form [name=title].wpb_vc_param_value').val());
};
wpb_change_accordion_tab_title = function ($element, field) {
var $section_title = $element.prev();
$section_title.find('a').text($(field).val());
};
window.init_textarea_html = function ($element) {
var $wp_link, textfield_id, $form_line, $content_holder
/*
Simple version without all this buttons from Wordpress
tinyMCE.init({
mode : "textareas",
theme: 'advanced',
editor_selector: $element.attr('name') + '_tinymce'
});
*/
$wp_link = $('#wp-link');
if ($wp_link.parent().hasClass('wp-dialog')) $wp_link.wpdialog('destroy');
textfield_id = $element.attr("id");
$form_line = $element.closest('.edit_form_line');
$content_holder = $form_line.find('.vc_textarea_html_content');
try {
// Init Quicktag
if (_.isUndefined(tinyMCEPreInit.qtInit[textfield_id])) {
window.tinyMCEPreInit.qtInit[textfield_id] = _.extend({}, window.tinyMCEPreInit.qtInit[window.wpActiveEditor], {id: textfield_id})
}
// Init tinymce
if (window.tinyMCEPreInit && window.tinyMCEPreInit.mceInit[window.wpActiveEditor]) {
window.tinyMCEPreInit.mceInit[textfield_id] = _.extend({}, window.tinyMCEPreInit.mceInit[window.wpActiveEditor], {
resize: 'vertical',
height: 200,
id: textfield_id,
setup: function (ed) {
if (typeof(ed.on) != 'undefined') {
ed.on('init', function (ed) {
ed.target.focus();
window.wpActiveEditor = textfield_id;
});
} else {
ed.onInit.add(function (ed) {
ed.focus();
window.wpActiveEditor = textfield_id;
});
}
}
});
window.tinyMCEPreInit.mceInit[textfield_id].plugins = window.tinyMCEPreInit.mceInit[textfield_id].plugins.replace(/,?wpfullscreen/, '');
window.tinyMCEPreInit.mceInit[textfield_id].wp_autoresize_on = false;
}
$element.val($content_holder.val());
quicktags(window.tinyMCEPreInit.qtInit[textfield_id]);
QTags._buttonsInit();
if (window.tinymce) {
window.switchEditors && window.switchEditors.go(textfield_id, 'tmce');
if (tinymce.majorVersion === "4") tinymce.execCommand('mceAddEditor', true, textfield_id);
}
vc_activeMce = textfield_id;
window.wpActiveEditor = textfield_id;
} catch (e) {
$element.data('vcTinyMceDisabled', true).appendTo($form_line);
$('#wp-' + textfield_id + '-wrap').remove();
if (console && console.error) {
console.error('VC: Tinymce error! Compatibility problem with other plugins.');
console.error(e);
}
}
};
function init_textarea_html_old($element) {
var textfield_id = $element.attr("id"),
$form_line = $element.closest('.edit_form_line'),
$content_holder = $form_line.find('.vc_textarea_html_content');
$('#' + textfield_id + '-html').trigger('click');
var $tmce = $('.switch-tmce');
$tmce.trigger('click');
$form_line.find('.wp-switch-editor').removeAttr("onclick");
$tmce.trigger('click');
$element.closest('.edit_form_line').find('.switch-tmce').click(function () {
window.tinyMCE.execCommand("mceAddControl", true, textfield_id);
window.switchEditors.go(textfield_id, 'tmce');
$element.closest('.edit_form_line').find('.wp-editor-wrap').removeClass('html-active').addClass('tmce-active');
var val = window.switchEditors.wpautop($(this).closest('.edit_form_line').find("textarea.visual_composer_tinymce").val());
$("textarea.visual_composer_tinymce").val(val);
// Add tinymce
window.tinyMCE.execCommand("mceAddControl", true, textfield_id);
});
$element.closest('.edit_form_line').find('.switch-html').click(function () {
$element.closest('.edit_form_line').find('.wp-editor-wrap').removeClass('tmce-active').addClass('html-active');
window.tinyMCE.execCommand("mceRemoveControl", true, textfield_id);
});
$('#wpb_tinymce_content-html').trigger('click');
$('#wpb_tinymce_content-tmce').trigger('click'); // Fix hidden toolbar
}
// TODO: unsecure. Think about it
Color.prototype.toString = function () {
if (this._alpha < 1) {
return this.toCSS('rgba', this._alpha).replace(/\s+/g, '');
}
var hex = parseInt(this._color, 10).toString(16);
if (this.error)
return '';
// maybe left pad it
if (hex.length < 6) {
for (var i = 6 - hex.length - 1; i >= 0; i--) {
hex = '0' + hex;
}
}
return '#' + hex;
};
var template_options = {
evaluate: /<#([\s\S]+?)#>/g,
interpolate: /\{\{\{([\s\S]+?)\}\}\}/g,
escape: /\{\{([^\}]+?)\}\}(?!\})/g
};
/**
* Loop param for shortcode with magic query posts constructor.
* ====================================
*/
vc.loop_partial = function (template_name, key, loop, settings) {
var data = _.isObject(loop) && !_.isUndefined(loop[key]) ? loop[key] : '';
return _.template($('#_vcl-' + template_name).html(), {
name: key,
data: data,
settings: settings
}, template_options);
};
vc.loop_field_not_hidden = function (key, loop) {
return !(_.isObject(loop[key]) && _.isBoolean(loop[key].hidden) && loop[key].hidden === true);
};
vc.is_locked = function (data) {
return _.isObject(data) && _.isBoolean(data.locked) && data.locked === true;
};
var Suggester = function (element, options) {
this.el = element;
this.$el = $(this.el);
this.$el_wrap = '';
this.$block = '';
this.suggester = '';
this.selected_items = [];
this.options = _.isObject(options) ? options : {};
_.defaults(this.options, {
css_class: 'vc_suggester',
limit: false,
source: {},
predefined: [],
locked: false,
select_callback: function (label, data) {
},
remove_callback: function (label, data) {
},
update_callback: function (label, data) {
},
check_locked_callback: function (el, data) {
return false;
}
});
this.init();
};
Suggester.prototype = {
constructor: Suggester,
init: function () {
_.bindAll(this, 'buildSource', 'itemSelected', 'labelClick', 'setFocus', 'resize');
var that = this;
this.$el.wrap('<ul class="' + this.options.css_class + '"><li class="input"/></ul>');
this.$el_wrap = this.$el.parent();
this.$block = this.$el_wrap.closest('ul').append($('<li class="clear"/>'));
this.$el.focus(this.resize).blur(function () {
$(this).parent().width(170);
$(this).val('');
});
this.$block.click(this.setFocus);
this.suggester = this.$el.data('suggest'); // Remove form here
this.$el.autocomplete({
source: this.buildSource,
select: this.itemSelected,
minLength: 2,
focus: function (event, ui) {
return false;
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $('<li data-value="' + item.value + '">')
.append("<a>" + item.name + "</a>")
.appendTo(ul);
};
this.$el.autocomplete("widget").addClass('vc_ui-front')
if (_.isArray(this.options.predefined)) {
_.each(this.options.predefined, function (item) {
this.create(item);
}, this);
}
},
resize: function () {
var position = this.$el_wrap.position(),
block_position = this.$block.position();
this.$el_wrap.width(parseFloat(this.$block.width()) - (parseFloat(position.left) - parseFloat(block_position.left) + 4));
},
setFocus: function (e) {
e.preventDefault();
var $target = $(e.target);
if ($target.hasClass(this.options.css_class)) {
this.$el.trigger('focus');
}
},
itemSelected: function (event, ui) {
this.$el.blur();
this.create(ui.item);
this.$el.focus();
return false;
},
create: function (item) {
var index = (this.selected_items.push(item) - 1),
remove = this.options.check_locked_callback(this.$el, item) === true ? '' : ' <a class="remove">×</a>',
$label,
exclude_css = '';
if (_.isUndefined(this.selected_items[index].action)) this.selected_items[index].action = '+';
exclude_css = this.selected_items[index].action === '-' ? ' exclude' : ' include';
$label = $('<li class="vc_suggest-label' + exclude_css + '" data-index="' + index + '" data-value="' + item.value + '"><span class="label">' + item.name + '</span>' + remove + '</li>');
$label.insertBefore(this.$el_wrap);
if (!_.isEmpty(remove)) $label.click(this.labelClick);
this.options.select_callback($label, this.selected_items);
},
labelClick: function (e) {
e.preventDefault();
var $label = $(e.currentTarget),
index = parseInt($label.data('index'), 10),
$target = $(e.target);
if ($target.is('.remove')) {
delete this.selected_items[index];
this.options.remove_callback($label, this.selected_items);
$label.remove();
return false;
}
this.selected_items[index].action = this.selected_items[index].action === '+' ? '-' : '+';
if (this.selected_items[index].action == '+') {
$label.removeClass('exclude').addClass('include');
} else {
$label.removeClass('include').addClass('exclude');
}
this.options.update_callback($label, this.selected_items);
},
buildSource: function (request, response) {
var exclude = _.map(this.selected_items, function (item) {
return item.value;
}).join(',');
$.ajax({
type: 'POST',
dataType: 'json',
url: window.ajaxurl,
data: {
action: 'wpb_get_loop_suggestion',
field: this.suggester,
exclude: exclude,
query: request.term
}
}).done(function (data) {
response(data);
});
}
};
$.fn.suggester = function (option) {
return this.each(function () {
var $this = $(this),
data = $this.data('suggester'),
options = _.isObject(option) ? option : {};
if (!data) $this.data('suggester', (data = new Suggester(this, option)));
if (typeof option == 'string') data[option]();
});
};
var VcLoopEditorView = Backbone.View.extend({
className: 'loop_params_holder',
events: {
'click input, select': 'save',
'change input, select': 'save',
'change :checkbox[data-input]': 'updateCheckbox'
},
query_options: {},
return_array: {},
controller: '',
initialize: function () {
_.bindAll(this, 'save', 'updateSuggestion', 'suggestionLocked');
},
render: function (controller) {
var that = this,
template = _.template($('#vcl-loop-frame').html(), this.model, _.extend({}, template_options, {variable: 'loop'}));
this.controller = controller;
this.$el.html(template);
this.controller.$el.append(this.$el);
_.each($('[data-suggest]'), function (object) {
var $field = $(object),
current_value = window.decodeURIComponent($('[data-suggest-prefill=' + $field.data('suggest') + ']').val());
$field.suggester({
predefined: $.parseJSON(current_value),
select_callback: this.updateSuggestion,
update_callback: this.updateSuggestion,
remove_callback: this.updateSuggestion,
check_locked_callback: this.suggestionLocked
});
}, this);
return this;
},
show: function () {
this.$el.slideDown();
},
save: function (e) {
this.return_array = {};
_.each(this.model, function (value, key) {
var value = this.getValue(key, value);
if (_.isString(value) && !_.isEmpty(value)) this.return_array[key] = value;
}, this);
this.controller.setInputValue(this.return_array);
},
getValue: function (key, default_value) {
var value = $('[name=' + key + ']', this.$el).val();
return value;
},
hide: function () {
this.$el.slideUp();
},
toggle: function () {
if (!this.$el.is(':animated')) this.$el.slideToggle();
},
updateCheckbox: function (e) {
var $checkbox = $(e.currentTarget),
input_name = $checkbox.data('input'),
$input = $('[data-name=' + input_name + ']', this.$el),
value = [];
$('[data-input=' + input_name + ']:checked').each(function () {
value.push($(this).val());
});
$input.val(value);
this.save();
},
updateSuggestion: function ($elem, data) {
var value,
$suggestion_block = $elem.closest('[data-block=suggestion]');
value = _.reduce(data, function (memo, label) {
if (!_.isEmpty(label)) {
return memo + (_.isEmpty(memo) ? '' : ',') + (label.action === '-' ? '-' : '') + label.value;
}
}, '');
$suggestion_block.find('[data-suggest-value]').val(value).trigger('change');
},
suggestionLocked: function ($elem, data) {
var value = data.value,
field = $elem.closest('[data-block=suggestion]').find('[data-suggest-value]').data('suggest-value');
return this.controller.settings[field]
&& _.isBoolean(this.controller.settings[field].locked)
&& this.controller.settings[field].locked == true
&& _.isString(this.controller.settings[field].value)
&& _.indexOf(this.controller.settings[field].value.replace('-', '').split(/\,/), '' + value) >= 0;
}
});
var VcLoop = Backbone.View.extend({
events: {
'click .vc_loop-build': 'showEditor'
},
initialize: function () {
_.bindAll(this, 'createEditor');
this.$input = $('.wpb_vc_param_value', this.$el);
this.$button = this.$el.find('.vc_loop-build');
this.data = this.$input.val();
this.settings = $.parseJSON(window.decodeURIComponent(this.$button.data('settings')));
},
render: function () {
return this;
},
showEditor: function (e) {
e.preventDefault();
if (_.isObject(this.loop_editor_view)) {
this.loop_editor_view.toggle();
return false;
}
$.ajax({
type: 'POST',
dataType: 'json',
url: window.ajaxurl,
data: {
action: 'wpb_get_loop_settings',
value: this.data,
settings: this.settings,
post_id: vc.post_id
}
}).done(this.createEditor);
},
createEditor: function (data) {
this.loop_editor_view = new VcLoopEditorView({model: !_.isEmpty(data) ? data : {}});
this.loop_editor_view.render(this).show();
},
setInputValue: function (value) {
this.$input.val(_.map(value, function (value, key) {
return key + ':' + value;
}).join('|'));
}
});
var VcOptionsField = Backbone.View.extend({
events: {
'click .vc_options-edit': 'showEditor',
'click .vc_close-button': 'showEditor',
'click input, select': 'save',
'change input, select': 'save',
'keyup input': 'save'
},
data: {},
fields: {},
initialize: function () {
this.$button = this.$el.find('.vc_options-edit');
this.$form = this.$el.find('.vc_options-fields');
this.$input = this.$el.find('.wpb_vc_param_value');
this.settings = this.$form.data('settings');
this.parseData();
this.render();
},
render: function () {
var html = '';
_.each(this.settings, function (field) {
if (!_.isUndefined(this.data[field.name])) {
field.value = this.data[field.name];
} else if (!_.isUndefined(field.value)) {
field.value = field.value.toString().split(',');
this.data[field.name] = field.value;
}
this.fields[field.name] = field;
var $field = $('#vcl-options-field-' + field.type);
if ($field.is('script')) {
html += _.template(
$field.html(),
$.extend({
name: '',
label: '',
value: [],
options: '',
description: ''
}, field),
_.extend({}, template_options)
);
}
}, this);
this.$form.html(html + this.$form.html());
return this;
},
parseData: function () {
_.each(this.$input.val().split("|"), function (data) {
if (data.match(/\:/)) {
var split = data.split(':'),
name = split[0],
value = split[1];
this.data[name] = _.map(value.split(','), function (v) {
return window.decodeURIComponent(v);
});
}
}, this);
},
saveData: function () {
var data_string = _.map(this.data, function (value, key) {
return key + ':' + _.map(value, function (v) {
return window.encodeURIComponent(v);
}).join(',');
}).join('|');
this.$input.val(data_string);
},
showEditor: function () {
this.$form.slideToggle();
},
save: function (e) {
var $field = $(e.currentTarget)
if ($field.is(':checkbox')) {
var value = [];
this.$el.find('input[name=' + $field.attr('name') + ']').each(function () {
if ($(this).is(':checked')) {
value.push($(this).val());
}
});
this.data[$field.attr('name')] = value;
} else {
this.data[$field.attr('name')] = [$field.val()];
}
this.saveData();
}
});
/**
* VC_link power code.
*/
var VcSortedList = function (element, settings) {
this.el = element;
this.$el = $(this.el);
this.$data_field = this.$el.find('.wpb_vc_param_value');
this.$toolbar = this.$el.find('.vc_sorted-list-toolbar');
this.$current_control = this.$el.find('.vc_sorted-list-container');
_.defaults(this.options, {});
this.init();
};
VcSortedList.prototype = {
constructor: VcSortedList,
init: function () {
var that = this;
_.bindAll(this, 'controlEvent', 'save');
this.$toolbar.on('change', 'input', this.controlEvent);
var selected_data = this.$data_field.val().split(',');
for (var i in selected_data) {
var control_settings = selected_data[i].split('|'),
$control = control_settings.length ? this.$toolbar.find('[data-element=' + decodeURIComponent(control_settings[0]) + ']') : false;
if ($control !== false && $control.is('input')) {
$control.prop('checked', true);
this.createControl({
value: $control.val(),
label: $control.parent().text(),
sub: $control.data('subcontrol'),
sub_value: _.map(control_settings.slice(1), function (item) {
return window.decodeURIComponent(item)
})
});
}
}
this.$current_control.sortable({
stop: this.save
}).on('change', 'select', this.save);
},
createControl: function (data) {
var sub_control = '',
selected_sub_value = _.isUndefined(data.sub_value) ? [] : data.sub_value;
if (_.isArray(data.sub)) {
_.each(data.sub, function (sub, index) {
sub_control += ' <select>';
_.each(sub, function (item) {
sub_control += '<option value="' + item[0] + '"' + (_.isString(selected_sub_value[index]) && selected_sub_value[index] === item[0] ? ' selected="true"' : '') + '>' + item[1] + '</option>';
});
sub_control += '</select>';
}, this);
}
this.$current_control.append('<li class="vc_control-' + data.value + '" data-name="' + data.value + '">' + data.label + sub_control + '</li>');
},
controlEvent: function (e) {
var $control = $(e.currentTarget);
if ($control.is(':checked')) {
this.createControl({
value: $control.val(),
label: $control.parent().text(),
sub: $control.data('subcontrol')
});
} else {
this.$current_control.find('.vc_control-' + $control.val()).remove();
}
this.save();
},
save: function () {
var value = _.map(this.$current_control.find('[data-name]'), function (element) {
var return_string = encodeURIComponent($(element).data('name'));
$(element).find('select').each(function () {
var $sub_control = $(this);
if ($sub_control.is('select') && $sub_control.val() !== '') {
return_string += '|' + encodeURIComponent($sub_control.val());
}
});
return return_string;
}).join(',');
this.$data_field.val(value);
}
};
$.fn.VcSortedList = function (option) {
return this.each(function () {
var $this = $(this),
data = $this.data('vc_sorted_list'),
options = _.isObject(option) ? option : {};
if (!data) $this.data('vc_sorted_list', (data = new VcSortedList(this, option)));
if (typeof option == 'string') data[option]();
});
};
/**
* Google fonts element methods
*/
var GoogleFonts = Backbone.View.extend({
preview_el: ".vc_google_fonts_form_field-preview-container > span",
font_family_dropdown_el: ".vc_google_fonts_form_field-font_family-container > select",
font_style_dropdown_el: ".vc_google_fonts_form_field-font_style-container > select",
font_style_dropdown_el_container: ".vc_google_fonts_form_field-font_style-container",
status_el: ".vc_google_fonts_form_field-status-container > span",
events: {
'change .vc_google_fonts_form_field-font_family-container > select': 'fontFamilyDropdownChange',
'change .vc_google_fonts_form_field-font_style-container > select': 'fontStyleDropdownChange'
},
initialize: function (attr) {
_.bindAll(this, 'previewElementInactive', 'previewElementActive', 'previewElementLoading');
this.$preview_el = $(this.preview_el, this.$el);
this.$font_family_dropdown_el = $(this.font_family_dropdown_el, this.$el);
this.$font_style_dropdown_el = $(this.font_style_dropdown_el, this.$el);
this.$font_style_dropdown_el_container = $(this.font_style_dropdown_el_container, this.$el);
this.$status_el = $(this.status_el, this.$el);
this.fontFamilyDropdownRender();
},
render: function () {
return this;
},
previewElementRender: function () {
this.$preview_el.css({
"font-family": this.font_family,
"font-style": this.font_style,
"font-weight": this.font_weight
});
return this;
},
previewElementInactive: function () {
this.$status_el.text(window.i18nLocale.gfonts_loading_google_font_failed || "Loading google font failed.").css('color', '#FF0000');
},
previewElementActive: function () {
this.$preview_el.text("Grumpy wizards make toxic brew for the evil Queen and Jack.").css('color', 'inherit');
this.fontStyleDropdownRender();
},
previewElementLoading: function () {
this.$preview_el.text(window.i18nLocale.gfonts_loading_google_font || "Loading Font...");
},
fontFamilyDropdownRender: function () {
this.fontFamilyDropdownChange();
return this;
},
fontFamilyDropdownChange: function () {
var $font_family_selected = this.$font_family_dropdown_el.find(':selected');
this.font_family_url = $font_family_selected.val();
this.font_family = $font_family_selected.attr('data[font_family]');
this.font_types = $font_family_selected.attr('data[font_types]');
this.$font_style_dropdown_el_container.parent().hide();
if (this.font_family_url && this.font_family_url.length > 0) {
WebFont.load({
google: {
families: [this.font_family_url]
},
inactive: this.previewElementInactive,
active: this.previewElementActive,
loading: this.previewElementLoading
});
}
return this;
},
fontStyleDropdownRender: function () {
var str = this.font_types;
var str_arr = str.split(',');
var oel = '';
var default_f_style = this.$font_family_dropdown_el.attr('default[font_style]');
for (var str_inner in str_arr) {
var str_arr_inner = str_arr[str_inner].split(':');
var sel = "";
if (_.isString(default_f_style) && default_f_style.length > 0 && str_arr[str_inner] == default_f_style) {
sel = 'selected="selected"';
}
oel = oel + '<option ' + sel + ' value="' + str_arr[str_inner] + '" data[font_weight]="' + str_arr_inner[1] + '" data[font_style]="' + str_arr_inner[2] + '" class="' + str_arr_inner[2] + '_' + str_arr_inner[1] + '" >' + str_arr_inner[0] + '</option>';
}
this.$font_style_dropdown_el.html(oel);
this.$font_style_dropdown_el_container.parent().show();
this.fontStyleDropdownChange();
return this;
},
fontStyleDropdownChange: function () {
var $font_style_selected = this.$font_style_dropdown_el.find(':selected');
this.font_weight = $font_style_selected.attr('data[font_weight]');
this.font_style = $font_style_selected.attr('data[font_style]');
this.previewElementRender();
return this;
}
});
/**
* Auto Complete PARAMETER
*
*/
var VC_AutoComplete = Backbone.View.extend({
min_length: 2,
delay: 500,
auto_focus: true,
ajax_url: window.ajaxurl,
source_data: function () {
return {};
},
replace_values_on_select: false,
initialize: function (params) {
_.bindAll(this, 'sortableChange', 'resize', 'labelRemoveHook', 'updateItems', 'sortableCreate', 'sortableUpdate', 'source', 'select', 'labelRemoveClick', 'createBox', 'focus', 'response', 'change', 'close', 'open', 'create', 'search', '_renderItem', '_renderMenu', '_renderItemData', '_resizeMenu');
params = $.extend({
min_length: this.min_length,
delay: this.delay,
auto_focus: this.auto_focus,
replace_values_on_select: this.replace_values_on_select
}, params);
this.options = params;
this.param_name = this.options.param_name;
this.$el = this.options.$el;
this.$el_wrap = this.$el.parent();
this.$sortable_wrapper = this.$el_wrap.parent();
this.$input_param = this.options.$param_input;
this.selected_items = [];
this.isMultiple = false;
this.render();
},
resize: function () {
var position = this.$el_wrap.position(),
block_position = this.$block.position();
var widget = this.$el.autocomplete("widget");
widget.width(parseFloat(this.$block.width()) - (parseFloat(position.left) - parseFloat(block_position.left) + 4 ) + 11);
},
enableMultiple: function () {
this.isMultiple = true;
this.$el.show();
this.$el.focus();
},
enableSortable: function () {
this.sortable = this.$sortable_wrapper.sortable({
items: ".vc_data",
axis: 'y',
change: this.sortableChange,
create: this.sortableCreate,
update: this.sortableUpdate
});
},
updateItems: function () {
if (this.selected_items.length) {
this.$input_param.val(this.getSelectedItems().join(", "));
} else {
this.$input_param.val("");
}
},
sortableChange: function (event, ui) {
},
itemsCreate: function () {
var sel_items = [];
this.$block.find('.vc_data').each(function (key, item) {
sel_items.push({label: item.dataset.label, value: item.dataset.value});
});
this.selected_items = sel_items;
},
sortableCreate: function (event, ui) {
},
sortableUpdate: function (event, ui) {
var elems = this.$sortable_wrapper.sortable('toArray', {attribute: 'data-index'});
var items = [];
_.each(elems, function (index) {
items.push(this.selected_items[index]);
}, this);
var index = 0;
$('li.vc_data', this.$sortable_wrapper).each(function () {
$(this).attr('data-index', index++);
});
this.selected_items = items;
this.updateItems();
},
getWidget: function () {
return this.$el.autocomplete('widget');
},
render: function () {
this.$el.focus(this.resize);
this.data = this.$el.autocomplete({
source: this.source,
minLength: this.options.min_length,
delay: this.options.delay,
autoFocus: this.options.auto_focus,
select: this.select,
focus: this.focus,
response: this.response,
change: this.change,
close: this.close,
open: this.open,
create: this.create,
search: this.search
});
this.data.data("ui-autocomplete")._renderItem = this._renderItem;
this.data.data("ui-autocomplete")._renderMenu = this._renderMenu;
this.data.data("ui-autocomplete")._resizeMenu = this._resizeMenu;
if (this.$input_param.val().length > 0) {
if (!this.isMultiple) {
this.$el.hide();
} else {
this.$el.focus();
}
var that = this;
$('.vc_autocomplete-label.vc_data', this.$sortable_wrapper).each(function () {
that.labelRemoveHook($(this));
});
}
this.getWidget().addClass('vc_ui-front').addClass('vc_ui-auotocomplete');
this.$block = this.$el_wrap.closest('ul').append($('<li class="clear"/>'));
this.itemsCreate();
return this;
},
close: function (event, ui) {
if (this.selected && this.options.no_hide) {
this.getWidget().show();
this.selected++;
if (this.selected > 2) {
this.selected = undefined;
}
}
},
open: function (event, ui) {
var widget = this.getWidget().menu();
var widget_position = widget.position();
widget.css('left', widget_position.left - 6);
widget.css('top', widget_position.top + 2);
},
focus: function (event, ui) {
if (!this.options.replace_values_on_select) {
event.preventDefault();
return false;
}
},
create: function (event, ui) {
},
change: function (event, ui) {
},
response: function (event, ui) {
},
search: function (event, ui) {
},
select: function (event, ui) {
this.selected = 1;
if (ui.item) {
if (this.options.unique_values) {
var $li_el = this.getWidget().data('uiMenu').active;
if (this.options.groups) {
var $prev_el = $li_el.prev();
var $next_el = $li_el.next();
if ($prev_el.hasClass('vc_autocomplete-group') && !$next_el.hasClass('vc_autocomplete-item')) {
$prev_el.remove();
}
}
$li_el.remove();
var that = this;
if (!$('li.ui-menu-item', this.getWidget()).length) {
that.selected = undefined;
}
}
this.createBox(ui.item);
if (!this.isMultiple) {
this.$el.hide();
} else {
this.$el.focus();
}
}
return false;
},
createBox: function (item) {
var index = (this.selected_items.push(item) - 1),
remove = '<a class="vc_autocomplete-remove">×</a>',
$label;
this.updateItems();
$label = $('<li class="vc_autocomplete-label vc_data" data-index="' + index + '" data-value="' + item.value + '" data-label="' + item.label + '"><span class="vc_autocomplete-label"><a>' + item.label + '</a></span>' + remove + '</li>');
$label.insertBefore(this.$el_wrap);
this.labelRemoveHook($label);
},
labelRemoveHook: function ($label) {
this.$el.blur();
this.$el.val('');
$label.click(this.labelRemoveClick);
},
labelRemoveClick: function (e, ui) {
e.preventDefault();
var $label = $(e.currentTarget),
index = parseInt($label.data('index'), 10),
$target = $(e.target);
if ($target.is('.vc_autocomplete-remove')) {
delete this.selected_items[index];
$label.remove();
this.updateItems();
this.$el.show();
return false;
}
},
getSelectedItems: function () {
if (this.selected_items.length) {
var results = [];
_.each(this.selected_items, function (item) {
results.push(item['value']);
});
return results;
}
return false;
},
_renderMenu: function (ul, items) {
var that = this;
var group = null;
if (this.options.groups) {
items.sort(function (a, b) {
return a.group > b.group;
});
}
$.each(items, function (index, item) {
if (that.options.groups) {
if (item.group != group) {
group = item.group;
ul.append("<li class='ui-autocomplete-group vc_autocomplete-group' aria-label='" + group + "'>" + group + "</li>");
}
}
that._renderItemData(ul, item);
});
},
_renderItem: function (ul, item) {
return $('<li data-value="' + item.value + '" class="vc_autocomplete-item">')
.append('<a>' + item.label + '</a>')
.appendTo(ul);
},
_renderItemData: function (ul, item) {
return this._renderItem(ul, item).data("ui-autocomplete-item", item);
},
_resizeMenu: function () {
},
/**
* Used to remove all data in the list.
*/
clearValue: function () {
this.selected_items = [];
this.updateItems();
$('.vc_autocomplete-label.vc_data', this.$sortable_wrapper).remove();
},
source: function (request, response) {
var that = this;
if (this.options.values && this.options.values.length > 0) {
if (this.options.unique_values) {
response($.ui.autocomplete.filter(
_.difference(this.options.values, this.selected_items),
request.term
));
} else {
response($.ui.autocomplete.filter(
this.options.values, request.term
));
}
} else {
$.ajax({
type: 'POST',
dataType: 'json',
url: this.ajax_url,
data: $.extend({
action: 'vc_get_autocomplete_suggestion',
shortcode: vc.active_panel.model.get('shortcode'), // get current shortcode?
param: this.param_name,
query: request.term
}, this.source_data(request, response))
}).done(function (data) {
if (that.options.unique_values) {
response(
_.filter(data, function (obj) {
return !_.findWhere(that.selected_items, obj);
})
);
} else {
response(data);
}
});
}
}
});
/**
* Param initializer
*
*/
var Vc_ParamInitializer = Backbone.View.extend({
$content: {},
initialize: function () {
_.bindAll(this, 'content');
this.$content = this.$el;
this.model = vc.active_panel.model;
},
content: function () {
return this.$content;
},
render: function () {
var that = this;
$('.vc_shortcode-param', this.content()).each(function () {
var param = {};
param.type = $(this).data('param_type');
param.param_name = $(this).data('param_name');
var $field = $(this);
vc.atts.init.call(that, param, $field);
});
return this;
}
});
/**
* Param group
*/
var VC_ParamGroup = Backbone.View.extend({
max_items: 0,
items: 0,
initializer: false,
events: {
'click > .edit_form_line > .vc_param_group-list > .vc_param_group-add_content': 'addNew'
},
initialize: function () {
this.$ul = this.$el.find('> .edit_form_line > .vc_param_group-list');
var $el_param = $('> .wpb_vc_row', this.$ul);
this.initializer = new Vc_ParamInitializer({el: this.$el});
this.model = vc.active_panel.model;
var data_settings = this.$ul.data('settings');
if (data_settings && data_settings['settings'] && data_settings['settings']['max_items']) {
this.max_items = data_settings['settings']['max_items'];
}
this.items = 0;
var that = this;
if ($el_param.length) {
$el_param.each(function () {
var pg = new VC_ParamGroup_Param({
el: $(this),
parent: that
});
that.items++;
that.afterAdd();
});
}
this.$ul.sortable({
handle: '.vc_control.column_move',
items: '> .wpb_vc_row:not(vc_param_group-add_content-wrapper)'
});
},
addNew: function (ev) {
ev.preventDefault();
if (this.addAllowed()) {
var $new_el = $(JSON.parse(this.$ul.next('.vc_param_group-template').html()));
$new_el.removeClass('vc_param_group-add_content-wrapper');
$new_el.insertBefore(ev.currentTarget);
$new_el.show();
this.initializer.$content = $('> .wpb_element_wrapper', $new_el);
this.initializer.render();
this.items++;
new VC_ParamGroup_Param({el: $new_el, parent: this});
this.afterAdd();
}
},
addAllowed: function () {
return (this.max_items > 0 && this.items + 1 <= this.max_items) || this.max_items <= 0;
},
afterAdd: function () {
if (!this.addAllowed()) {
this.$ul.find('> .wpb_vc_row > .controls > .vc_row_edit_clone_delete > .vc_control.column_clone').hide();
this.$ul.find('> .vc_param_group-add_content').hide();
}
},
afterDelete: function () {
if (this.addAllowed()) {
this.$ul.find('> .wpb_vc_row > .controls > .vc_row_edit_clone_delete > .vc_control.column_clone').show();
this.$ul.find('> .vc_param_group-add_content').show();
}
}
});
var VC_ParamGroup_Param = Backbone.View.extend({
events: {
'click > .controls > .vc_row_edit_clone_delete > .vc_control.column_toggle': 'toggle',
'click > .controls > .vc_row_edit_clone_delete > .vc_control.column_delete': 'delete',
'click > .controls > .vc_row_edit_clone_delete > .vc_control.column_clone': 'clone'
},
initialize: function (options) {
this.options = options;
this.$content = this.options.parent.$ul;
this.model = vc.active_panel.model;
},
delete: function (ev) {
_.isObject(ev) && ev.preventDefault && ev.preventDefault();
var answer = confirm(i18n.press_ok_to_delete_section);
if (answer === true) {
this.options.parent.items--;
this.options.parent.afterDelete();
this.$el.remove();
//todo check memleaks everywhere
this.unbind(); // Unbind all local event bindings
this.remove(); // Remove view from DOM
}
},
content: function () {
return this.$content;
},
clone: function (ev) {
ev.preventDefault();
if (this.options.parent.addAllowed()) {
var param = this.options.parent.$ul.data('settings');
var $content = this.$content;
this.$content = this.$el;
var value = vc.atts.param_group.parseOne.call(this, param);
var $new_el;
$.ajax({
type: 'POST',
url: window.ajaxurl,
data: {
action: 'vc_param_group_clone',
param: encodeURIComponent(JSON.stringify(param)),
shortcode: vc.active_panel.model.get('shortcode'),
value: value,
vc_inline: true
},
dataType: 'html',
context: this
}).done(function (html) {
$new_el = $(html);
$new_el.insertAfter(this.$el);
this.$content = $content;
this.options.parent.initializer.$content = $('> .wpb_element_wrapper', $new_el);
this.options.parent.initializer.render();
new VC_ParamGroup_Param({
el: $new_el,
parent: this.options.parent
});
this.options.parent.items++;
this.options.parent.afterAdd();
});
}
},
toggle: function (ev) {
ev.preventDefault();
var $elem = this.$el.find('> .wpb_element_wrapper');
$elem.slideToggle();
$elem.parent().toggleClass('vc_param_group-collapsed');
}
});
var i18n = window.i18nLocale;
vc.edit_form_callbacks = [];
vc.atts = {
parse: function (param) {
var value;
var $field = this.content().find('.wpb_vc_param_value[name=' + param.param_name + ']');
if (!_.isUndefined(vc.atts[param.type]) && !_.isUndefined(vc.atts[param.type].parse)) {
value = vc.atts[param.type].parse.call(this, param);
} else {
value = $field.length ? $field.val() : null;
}
if ($field.data('js-function') !== undefined && typeof(window[$field.data('js-function')]) !== 'undefined') {
var fn = window[$field.data('js-function')];
fn(this.$el, this, param);
}
return value;
},
parseFrame: function (param) {
var value;
var $field = this.content().find('.wpb_vc_param_value[name=' + param.param_name + ']');
if (!_.isUndefined(vc.atts[param.type]) && !_.isUndefined(vc.atts[param.type].parse)) {
value = vc.atts[param.type].parse.call(this, param);
} else {
value = $field.length ? $field.val() : null;
}
if ($field.data('js-function') !== undefined && typeof(window[$field.data('js-function')]) !== 'undefined') {
var fn = window[$field.data('js-function')];
fn(this.$el, this, param);
}
return value;
},
init: function (param, $field) {
if (!_.isUndefined(vc.atts[param.type]) && !_.isUndefined(vc.atts[param.type].init)) {
vc.atts[param.type].init.call(this, param, $field);
}
}
};
// Default atts
vc.atts.textarea_html = {
parse: function (param) {
var _window = this.window(),
$field = this.content().find('.textarea_html.' + param.param_name + '');
try {
if (_window.tinyMCE && _.isArray(_window.tinyMCE.editors)) {
_.each(_window.tinyMCE.editors, function (_editor) {
if ('wpb_tinymce_content' === _editor.id) {
_editor.save();
}
});
}
} catch (e) {
console && console.error && console.error(e);
}
return $field.val();
},
render: function (param, value) {
return _.isUndefined(value) ? value : vc_wpautop(value);
}
};
vc.atts.textarea_safe = {
parse: function (param) {
var $field = this.content().find('.wpb_vc_param_value[name=' + param.param_name + ']'),
new_value = $field.val();
return new_value.match(/"/) ? '#E-8_' + base64_encode(rawurlencode(new_value)) : new_value;
},
render: function (param, value) {
return value && value.match(/^#E\-8_/) ? $("<div/>").text(rawurldecode(base64_decode(value.replace(/^#E\-8_/, '')))).html() : value;
}
};
vc.atts.checkbox = {
parse: function (param) {
var arr = [],
new_value = "";
if (_.isUndefined(param.save_always)) {
param.save_always = true; // fix #1239
}
$('input[name=' + param.param_name + ']', this.content()).each(function () {
var self = $(this);
if (self.is(':checked')) {
arr.push(self.attr("value"));
}
});
if (arr.length > 0) {
new_value = arr.join(',');
}
return new_value;
},
defaults: function (param) {
return '';
}
};
vc.atts.posttypes = {
parse: function (param) {
var posstypes_arr = [],
new_value = '';
$('input[name=' + param.param_name + ']', this.content()).each(function () {
var self = $(this);
if (self.is(':checked')) {
posstypes_arr.push(self.attr("value"));
}
});
if (posstypes_arr.length > 0) {
new_value = posstypes_arr.join(',');
}
return new_value;
}
};
vc.atts.taxonomies = {
parse: function (param) {
var posstypes_arr = [],
new_value = '';
$('input[name=' + param.param_name + ']', this.content()).each(function () {
var self = $(this);
if (self.is(':checked')) {
posstypes_arr.push(self.attr("value"));
}
});
if (posstypes_arr.length > 0) {
new_value = posstypes_arr.join(',');
}
return new_value;
}
};
vc.atts.exploded_textarea = {
parse: function (param) {
var $field = this.content().find('.wpb_vc_param_value[name=' + param.param_name + ']');
return $field.val().replace(/\n/g, ",");
}
};
vc.atts.textarea_raw_html = {
parse: function (param) {
var $field = this.content().find('.wpb_vc_param_value[name=' + param.param_name + ']'),
new_value = $field.val();
return base64_encode(rawurlencode(new_value));
},
render: function (param, value) {
return $("<div/>").text(rawurldecode(base64_decode(value))).html();
}
};
vc.atts.dropdown = {
render: function (param, value) {
return value;
},
init: function (param, $field) {
$('.wpb_vc_param_value.dropdown', $field).change(function () {
var $this = $(this),
$options = $this.find(':selected'),
prev_option_class = $this.data('option'),
option_class = $options.length ? $options.attr('class').replace(/\s/g, '_') : '';
prev_option_class != undefined && $this.removeClass(prev_option_class);
option_class != undefined && $this.data('option', option_class) && $this.addClass(option_class);
});
},
defaults: function (param) {
var values;
if (!_.isArray(param.value) && !_.isString(param.value)) {
values = _.values(param.value)[0];
return values.label ? values.value : values;
} else if (_.isArray(param.value)) {
values = param.value[0];
return _.isArray(values) && values.length ? values[0] : values;
}
return '';
}
};
vc.atts.attach_images = {
parse: function (param) {
var $field = this.content().find('.wpb_vc_param_value[name=' + param.param_name + ']'),
thumbnails_html = '';
// TODO: Check image search with Wordpress
$field.parent().find('li.added').each(function () {
thumbnails_html += '<li><img src="' + $(this).find('img').attr('src') + '" alt=""></li>';
});
$('[data-model-id=' + this.model.id + ']').data('field-' + param.param_name + '-attach-images', thumbnails_html);
return $field.length ? $field.val() : null;
},
render: function (param, value) {
var $thumbnails = this.$el.find('.attachment-thumbnails[data-name=' + param.param_name + ']'),
thumbnails_html = this.$el.data('field-' + param.param_name + '-attach-images');
if (_.isUndefined(thumbnails_html) && !_.isEmpty(value)) {
$.ajax({
type: 'POST',
url: window.ajaxurl,
data: {
action: 'wpb_gallery_html',
content: value
},
dataType: 'html',
context: this
}).done(function (html) {
vc.atts.attach_images.updateImages($thumbnails, html);
});
} else if (!_.isUndefined(thumbnails_html)) {
this.$el.removeData('field-' + param.param_name + '-attach-images');
vc.atts.attach_images.updateImages($thumbnails, thumbnails_html);
}
return value;
},
updateImages: function ($thumbnails, thumbnails_html) {
$thumbnails.html(thumbnails_html);
if (thumbnails_html.length) {
$thumbnails.removeClass('image-exists').next().addClass('image-exists');
} else {
$thumbnails.addClass('image-exists').next().removeClass('image-exists');
}
}
};
vc.atts.href = {
parse: function (param) {
var $field = this.content().find('.wpb_vc_param_value[name=' + param.param_name + ']'),
val = '';
if ($field.length && $field.val() != 'http://') val = $field.val();
return val;
}
};
vc.atts.attach_image = {
parse: function (param) {
var $field = this.content().find('.wpb_vc_param_value[name=' + param.param_name + ']'),
image_src = '';
if ($field.parent().find('li.added').length) {
image_src = $field.parent().find('li.added img').attr('src');
}
$('[data-model-id=' + this.model.id + ']').data('field-' + param.param_name + '-attach-image', image_src);
return $field.length ? $field.val() : null;
},
render: function (param, value) {
var $model = $('[data-model-id=' + this.model.id + ']');
var image_src = $model.data('field-' + param.param_name + '-attach-image');
var $thumbnail = this.$el.find('.attachment-thumbnail[data-name=' + param.param_name + ']');
if (_.isUndefined(image_src) && !_.isEmpty(value)) {
$.ajax({
type: 'POST',
url: window.ajaxurl,
data: {
action: 'wpb_single_image_src',
content: value
},
dataType: 'html',
context: this
}).done(function (src) {
vc.atts['attach_image'].updateImage($thumbnail, src);
});
} else if (!_.isUndefined(image_src)) {
$model.removeData('field-' + param.param_name + '-attach-image');
vc.atts['attach_image'].updateImage($thumbnail, image_src);
}
return value;
},
updateImage: function ($thumbnail, image_src) {
if (_.isEmpty(image_src)) {
$thumbnail.attr('src', '').hide();
$thumbnail.next().removeClass('image-exists').next().removeClass('image-exists');
} else {
$thumbnail.attr('src', image_src).show();
$thumbnail.next().addClass('image-exists').next().addClass('image-exists');
}
}
};
vc.atts.google_fonts = {
parse: function (param) {
var $field = this.content().find('.wpb_vc_param_value[name=' + param.param_name + ']');
var $block = $field.parent();
var options = {},
string_pieces,
string;
options.font_family = $block.find('.vc_google_fonts_form_field-font_family-select > option:selected').val();
options.font_style = $block.find('.vc_google_fonts_form_field-font_style-select > option:selected').val();
string_pieces = _.map(options, function (value, key) {
if (_.isString(value) && value.length > 0) {
return key + ':' + encodeURIComponent(value);
}
});
string = $.grep(string_pieces, function (value) {
return _.isString(value) && value.length > 0;
}).join('|');
return string;
},
init: function (param, $field) {
var $g_fonts = $field;
if ($g_fonts.length) {
if (typeof WebFont != "undefined") {
new GoogleFonts({el: $g_fonts});
} else {
$g_fonts.find('> .edit_form_line').html(window.i18nLocale.gfonts_unable_to_load_google_fonts || "Unable to load Google Fonts");
}
}
}
};
vc.atts.font_container = {
parse: function (param) {
var $field = this.content().find('.wpb_vc_param_value[name=' + param.param_name + ']');
var $block = $field.parent();
var options = {},
string_pieces,
string;
options.tag = $block.find('.vc_font_container_form_field-tag-select > option:selected').val();
options.font_size = $block.find('.vc_font_container_form_field-font_size-input').val();
options.text_align = $block.find('.vc_font_container_form_field-text_align-select > option:selected').val();
options.font_family = $block.find('.vc_font_container_form_field-font_family-select > option:selected').val();
options.color = $block.find('.vc_font_container_form_field-color-input').val();
options.line_height = $block.find('.vc_font_container_form_field-line_height-input').val();
options.font_style_italic = $block.find('.vc_font_container_form_field-font_style-checkbox.italic').is(':checked') ? "1" : "";
options.font_style_bold = $block.find('.vc_font_container_form_field-font_style-checkbox.bold').is(':checked') ? "1" : "";
string_pieces = _.map(options, function (value, key) {
if (_.isString(value) && value.length > 0) {
return key + ':' + encodeURIComponent(value);
}
});
string = $.grep(string_pieces, function (value) {
return _.isString(value) && value.length > 0;
}).join('|');
return string;
},
init: function (param, $field) {
vc.atts.colorpicker.init.call(this, param, $field);
}
};
vc.atts.param_group = {
parse: function (param) {
var $content = this.content();
var $this_content = this.$content;
var $block = $content.find('.wpb_el_type_param_group.vc_shortcode-param[data-param_name="' + param['param_name'] + '"]');
var $list = $block.find('> .edit_form_line > .vc_param_group-list');
var data = [];
var that = this;
$('>.wpb_vc_row:not(".vc_param_group-add_content-wrapper")', $list).each(function () {
var inner_data = {};
that.$content = $(this);
_.each(param['params'], function (par) {
var para = $.extend({}, par);
var param_data = {};
param_data['param_name'] = para['param_name'];
param_data['type'] = para['type'];
para['param_name'] = param['param_name'] + '_' + para['param_name'];
param_data['value'] = vc.atts.parse.call(that, para);
inner_data[para['param_name']] = param_data;
});
data.push(inner_data);
});
this.$content = $this_content;
return encodeURIComponent(JSON.stringify(data));
},
parseOne: function (param) {
var $content = this.content();
var $this_content = this.$content;
var data = [];
var that = this;
$content.each(function () {
var inner_data = {};
that.$content = $(this);
_.each(param['params'], function (par) {
var para = $.extend({}, par);
var param_data = {};
param_data['param_name'] = para['param_name'];
param_data['type'] = para['type'];
para['param_name'] = param['param_name'] + '_' + para['param_name'];
param_data['value'] = vc.atts.parse.call(that, para);
inner_data[para['param_name']] = param_data;
});
data.push(inner_data);
});
this.$content = $this_content;
return encodeURIComponent(JSON.stringify(data));
},
init: function (param, $field) {
new VC_ParamGroup({el: $field});
}
};
vc.atts.colorpicker = {
init: function (param, $field) {
var $content = $field;
$('.vc_color-control', $content).each(function () {
var $control = $(this),
value = $control.val().replace(/\s+/g, ''),
alpha_val = 100,
$alpha, $alpha_output;
if (value.match(/rgba\(\d+\,\d+\,\d+\,([^\)]+)\)/)) {
alpha_val = parseFloat(value.match(/rgba\(\d+\,\d+\,\d+\,([^\)]+)\)/)[1]) * 100;
}
$control.wpColorPicker({
clear: function (event, ui) {
$alpha.val(100);
$alpha_output.val(100 + '%');
}
});
$('<div class="vc_alpha-container">'
+ '<label>Alpha: <output class="rangevalue">' + alpha_val + '%</output></label>'
+ '<input type="range" min="1" max="100" value="' + alpha_val + '" name="alpha" class="vc_alpha-field">'
+ '</div>').appendTo($control.parents('.wp-picker-container:first').addClass('vc_color-picker').find('.iris-picker'));
$alpha = $control.parents('.wp-picker-container:first').find('.vc_alpha-field');
$alpha_output = $control.parents('.wp-picker-container:first').find('.vc_alpha-container output')
$alpha.bind('change keyup', function () {
var alpha_val = parseFloat($alpha.val()),
iris = $control.data('a8c-iris'),
color_picker = $control.data('wp-wpColorPicker');
$alpha_output.val($alpha.val() + '%');
iris._color._alpha = alpha_val / 100.0;
$control.val(iris._color.toString());
color_picker.toggler.css({backgroundColor: $control.val()});
}).val(alpha_val).trigger('change');
});
}
};
vc.atts.autocomplete = {
init: function (param, $field) {
var $el_type_autocomplete = $field;
if ($el_type_autocomplete.length) {
$el_type_autocomplete.each(function () {
var $param = $('.wpb_vc_param_value', this);
var param_name = $param.attr('name');
var $el = $('.vc_auto_complete_param', this);
var options = {};
options = $.extend(
{
$param_input: $param,
$el: $el,
param_name: param_name
},
$param.data('settings')
);
var ac = new VC_AutoComplete(options);
if (options.multiple) {
ac.enableMultiple();
}
if (options.sortable) {
ac.enableSortable();
}
$param.data('object', ac);
});
}
}
};
vc.atts.loop = {
init: function (param, $field) {
new VcLoop({el: $field});
}
};
vc.atts.vc_link = {
init: function (param, $field) {
$('.vc_link-build', $field).click(function (e) {
e.preventDefault();
var $self = $(this),
$block = $(this).closest('.vc_link'),
$input = $block.find('.wpb_vc_param_value'),
$url_label = $block.find('.url-label'),
$title_label = $block.find('.title-label'),
value_object = $input.data('json'),
$link_submit = $('#wp-link-submit'),
$vc_link_submit = $('<input type="submit" name="vc_link-submit" id="vc_link-submit" class="button-primary" value="Set Link">'),
dialog;
$link_submit.hide();
$("#vc_link-submit").remove();
$vc_link_submit.insertBefore($link_submit);
if (!window.wpLink && $.fn.wpdialog && $('#wp-link').length) {
dialog = {
$link: false,
open: function () {
this.$link = $('#wp-link').wpdialog({
title: wpLinkL10n.title,
width: 480,
height: 'auto',
modal: true,
dialogClass: 'wp-dialog',
zIndex: 300000
});
},
close: function () {
this.$link.wpdialog('close');
}
};
} else {
dialog = window.wpLink;
}
dialog.open(vc_activeMce);
window.wpLink.textarea = $self;
if (_.isString(value_object.url)) $('#url-field').val(value_object.url);
if (_.isString(value_object.title)) $('#link-title-field').val(value_object.title);
$('#link-target-checkbox').prop('checked', !_.isEmpty(value_object.target));
$vc_link_submit.unbind('click.vcLink').bind('click.vcLink', function (e) {
e.preventDefault();
e.stopImmediatePropagation();
var options = {},
string = '';
options.url = $('#url-field').val();
options.title = $('#link-title-field').val();
var $checkbox = $('#link-target-checkbox');
options.target = $checkbox.is(':checked') ? ' _blank' : '';
string = _.map(options, function (value, key) {
if (_.isString(value) && value.length > 0) {
return key + ':' + encodeURIComponent(value);
}
}).join('|');
$input.val(string);
$input.data('json', options);
$url_label.html(options.url + options.target);
$title_label.html(options.title);
// $dialog.wpdialog('close');
dialog.close();
$link_submit.show();
$vc_link_submit.unbind('click.vcLink');
$vc_link_submit.remove();
// remove vc_link hooks for wpLink
$('#wp-link-cancel').unbind('click.vcLink');
window.wpLink.textarea = '';
$checkbox.attr('checked', false);
return false;
});
$('#wp-link-cancel').unbind('click.vcLink').bind('click.vcLink', function (e) {
e.preventDefault();
dialog.close();
// remove vc_link hooks for wpLink
$vc_link_submit.unbind('click.vcLink');
$vc_link_submit.remove();
// remove vc_link hooks for wpLink
$('#wp-link-cancel').unbind('click.vcLink');
window.wpLink.textarea = '';
});
});
}
};
vc.atts.sorted_list = {
init: function (param, $field) {
$('.vc_sorted-list', $field).VcSortedList();
}
};
vc.atts.options = {
init: function (param, $field) {
new VcOptionsField({el: $field});
}
};
vc.atts.iconpicker = {
change: function (param, $field) {
var $select = $field.find('.vc-iconpicker');
$select.val(this.value);
$select.data('vc-no-check', true);
$select.find('[value="' + this.value + '"]').attr('selected', 'selected');
$select.data('vcFontIconPicker').loadIcons(); // this methods actualy reload "active icon" and triggers event change
},
parse: function (param) {
var $field = this.content().find('.wpb_vc_param_value[name=' + param.param_name + ']');
var $block = $field.parent();
var val = $block.find('.vc-iconpicker').val();
return val;
},
init: function (param, $field) {
var $el = $field.find('.wpb_vc_param_value');
var settings = $.extend({
iconsPerPage: 100, // default icons per page for iconpicker
iconDownClass: 'fa fa-arrow-down',
iconUpClass: 'fa fa-arrow-up',
iconLeftClass: 'fa fa-arrow-left',
iconRightClass: 'fa fa-arrow-right',
iconSearchClass: 'fa fa-search',
iconCancelClass: 'fa fa-remove',
iconBlockClass: 'fa fa-minus-circle'
}, $el.data('settings'));
$field.find('.vc-iconpicker').vcFontIconPicker(settings).on('change', function (e) {
var $select = $(this);
if (!$select.data('vc-no-check')) {
//event.extra_type = true;
$el.data('vc-no-check', true).val(this.value).trigger('change');
}
$select.data('vc-no-check', false);
});
$el.on('change', function (e) {
if (!$el.data('vc-no-check')) {
vc.atts.iconpicker.change.call(this, param, $field);
}
$el.data('vc-no-check', false);
});
}
};
vc.atts.animation_style = {
init: function (param, $field) {
var content = $field;
var $field_input = $('.wpb_vc_param_value[name=' + param.param_name + ']', content);
$('option[value="' + $field_input.val() + '"]', content).attr('selected', true);
var animation_style_test = function (el, x) {
$(el).removeClass().addClass(x + ' animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
$(this).removeClass().addClass('vc_param-animation-style-preview');
});
};
$('.vc_param-animation-style-trigger', content).click(function (e) {
e.preventDefault();
var animation = $('.vc_param-animation-style', content).val();
if (animation != 'none') {
animation_style_test(this.parentNode, 'vc_param-animation-style-preview ' + animation);
}
});
$('.vc_param-animation-style', content).change(function () {
var animation = $(this).val();
$field_input.val(animation);
if (animation != 'none') {
var el = $('.vc_param-animation-style-preview', content);
animation_style_test(el, 'vc_param-animation-style-preview ' + animation);
}
});
}
};
vc.atts.vc_grid_id = {
/**
* Called in backend when element being save by edit form
* @returns {string}
*/
parse: function () {
var value = 'vc_gid:' + (+new Date() + '-' + this.model.get('id') + '-' + Math.floor(Math.random() * 11));
return value;
}
};
/**
*
* @type {{addShortcode: Function}}
*/
vc.atts.addShortcodeIdParam = function (model) {
var params, settings;
params = model.get('params');
settings = vc.map[model.get('shortcode')];
if (_.isArray(settings.params)) {
_.each(settings.params, function (p) {
if ('tab_id' === p.type && _.isEmpty(params[p.param_name])) {
params[p.param_name] = vc_guid() + '-' + Math.floor(Math.random() * 11);
} else if ('vc_grid_id' === p.type) {
params[p.param_name] = vc.atts.vc_grid_id.parse.call({model: model});
}
});
}
model.save('params', params);
};
vc.getMapped = function (tag) {
return vc.map[tag] || {};
}
})(window.jQuery);
|
DogburnDesign/traditional
|
wp-content/plugins/js_composer/assets/js/params/composer-atts.js
|
JavaScript
|
gpl-2.0
| 59,990
|
/*
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
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 <COPYRIGHT HOLDER> 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.
*/
/*jslint browser:true evil:true */
/*global require:true */
(function (global) {
'use strict';
function id(i) {
return document.getElementById(i);
}
function traceInstrument() {
var tracer, code, signature;
if (typeof window.editor === 'undefined') {
code = document.getElementById('code').value;
} else {
code = window.editor.getText();
}
tracer = window.esmorph.Tracer.FunctionEntrance(function (fn) {
signature = 'window.TRACE.enterFunction({ ';
signature += 'name: "' + fn.name + '", ';
signature += 'lineNumber: ' + fn.loc.start.line + ', ';
signature += 'range: [' + fn.range[0] + ',' + fn.range[1] + ']';
signature += ' });';
return signature;
});
code = window.esmorph.modify(code, tracer);
// Enclose in IIFE.
code = '(function() {\n' + code + '\n}())';
return code;
}
function count(x, s, p) {
return (x === 1) ? (x + ' ' + s) : (x + ' ' + p);
}
function showResult() {
var i, histogram, entry, name, pos;
histogram = window.TRACE.getHistogram();
for (i = 0; i < histogram.length; i += 1) {
entry = histogram[i];
name = entry.name.split(':')[0];
pos = parseInt(entry.name.split(':')[1], 10);
window.editor.addErrorMarker(pos, name + ' is called ' + count(entry.count, 'time', 'times'));
}
}
function createTraceCollector() {
global.TRACE = {
hits: {},
enterFunction: function (info) {
var key = info.name + ':' + info.range[0];
if (this.hits.hasOwnProperty(key)) {
this.hits[key] = this.hits[key] + 1;
} else {
this.hits[key] = 1;
}
},
getHistogram: function () {
var entry,
sorted = [];
for (entry in this.hits) {
if (this.hits.hasOwnProperty(entry)) {
sorted.push({ name: entry, count: this.hits[entry]});
}
}
sorted.sort(function (a, b) {
return b.count - a.count;
});
return sorted;
}
};
}
global.traceRun = function () {
var code, timestamp;
try {
id('info').setAttribute('class', 'alert-box secondary');
id('info').innerHTML = 'Executing...';
window.editor.removeAllErrorMarkers();
createTraceCollector();
code = traceInstrument();
timestamp = +new Date();
eval(code);
timestamp = (+new Date()) - timestamp;
id('info').innerHTML = 'Tracing completed in ' + (1 + timestamp) + ' ms.';
showResult();
} catch (e) {
id('info').innerHTML = e.toString();
id('info').setAttribute('class', 'alert-box alert');
}
};
}(window));
window.onload = function () {
'use strict';
document.getElementById('run').onclick = window.traceRun;
try {
require(['custom/editor'], function (editor) {
window.editor = editor({ parent: 'editor', lang: 'js' });
window.editor.getModel().addEventListener("Changed", function () {
window.editor.removeAllErrorMarkers();
document.getElementById('info').setAttribute('class', 'alert-box secondary');
document.getElementById('info').innerHTML = 'Ready.';
});
});
} catch (e) {
}
};
|
saki1001/sb-2014
|
wp-content/themes/cleanslate/node_modules/grunt-contrib-jshint/node_modules/jshint/node_modules/esprima/demo/functiontrace.js
|
JavaScript
|
gpl-2.0
| 5,065
|
windowFunctions['Remove Photo Collection'] = function (evt) {
var win = createWindow();
var offset = addBackButton(win);
var button = Ti.UI.createButton({
title: 'Are you sure?',
top: offset + 10 + u, left: 10 + u, right: 10 + u, bottom: 10 + u,
height: 40 + u
});
win.add(button);
var status = Ti.UI.createLabel({
text: '', textAlign: 'center',
left: 20 + u, right: 20 + u
});
win.add(status);
button.addEventListener('click', function () {
button.hide();
status.text = 'Removing, please wait...';
Cloud.PhotoCollections.remove({
collection_id: evt.id
}, function (e) {
if (e.success) {
status.text = 'Removed!';
}
else {
status.text = '' + (e.error && e.message) || e;
}
});
});
win.open();
};
|
mgostisha/lolapp
|
modules/commonjs/ti.cloud/3.2.3/example/windows/photoCollections/remove.js
|
JavaScript
|
apache-2.0
| 915
|
/*!
* json-schema-faker library v0.3.5
* http://json-schema-faker.js.org
* @preserve
*
* Copyright (c) 2014-2016 Alvaro Cabrera & Tomasz Ducin
* Released under the MIT license
*
* Date: 2016-08-01 20:24:53.199Z
*/
(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){
"use strict";
var Registry = require('../class/Registry');
// instantiate
var registry = new Registry();
/**
* Custom format API
*
* @see https://github.com/json-schema-faker/json-schema-faker#custom-formats
* @param nameOrFormatMap
* @param callback
* @returns {any}
*/
function formatAPI(nameOrFormatMap, callback) {
if (typeof nameOrFormatMap === 'undefined') {
return registry.list();
}
else if (typeof nameOrFormatMap === 'string') {
if (typeof callback === 'function') {
registry.register(nameOrFormatMap, callback);
}
else {
return registry.get(nameOrFormatMap);
}
}
else {
registry.registerMany(nameOrFormatMap);
}
}
module.exports = formatAPI;
},{"../class/Registry":5}],2:[function(require,module,exports){
"use strict";
var OptionRegistry = require('../class/OptionRegistry');
// instantiate
var registry = new OptionRegistry();
/**
* Custom option API
*
* @param nameOrOptionMap
* @returns {any}
*/
function optionAPI(nameOrOptionMap) {
if (typeof nameOrOptionMap === 'string') {
return registry.get(nameOrOptionMap);
}
else {
return registry.registerMany(nameOrOptionMap);
}
}
module.exports = optionAPI;
},{"../class/OptionRegistry":4}],3:[function(require,module,exports){
"use strict";
var randexp = require('randexp');
/**
* Container is used to wrap external libraries (faker, chance, randexp) that are used among the whole codebase. These
* libraries might be configured, customized, etc. and each internal JSF module needs to access those instances instead
* of pure npm module instances. This class supports consistent access to these instances.
*/
var Container = (function () {
function Container() {
// static requires - handle both initial dependency load (deps will be available
// among other modules) as well as they will be included by browserify AST
this.registry = {
faker: null,
chance: null,
// randexp is required for "pattern" values
randexp: randexp
};
}
/**
* Override dependency given by name
* @param name
* @param callback
*/
Container.prototype.extend = function (name, callback) {
if (typeof this.registry[name] === 'undefined') {
throw new ReferenceError('"' + name + '" dependency is not allowed.');
}
this.registry[name] = callback(this.registry[name]);
};
/**
* Returns dependency given by name
* @param name
* @returns {Dependency}
*/
Container.prototype.get = function (name) {
if (typeof this.registry[name] === 'undefined') {
throw new ReferenceError('"' + name + '" dependency doesn\'t exist.');
}
else if (name === 'randexp') {
return this.registry['randexp'].randexp;
}
return this.registry[name];
};
/**
* Returns all dependencies
*
* @returns {Registry}
*/
Container.prototype.getAll = function () {
return {
faker: this.get('faker'),
chance: this.get('chance'),
randexp: this.get('randexp')
};
};
return Container;
}());
// TODO move instantiation somewhere else (out from class file)
// instantiate
var container = new Container();
module.exports = container;
},{"randexp":180}],4:[function(require,module,exports){
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Registry = require('./Registry');
/**
* This class defines a registry for custom formats used within JSF.
*/
var OptionRegistry = (function (_super) {
__extends(OptionRegistry, _super);
function OptionRegistry() {
_super.call(this);
this.data['failOnInvalidTypes'] = true;
this.data['defaultInvalidTypeProduct'] = null;
this.data['useDefaultValue'] = false;
}
return OptionRegistry;
}(Registry));
module.exports = OptionRegistry;
},{"./Registry":5}],5:[function(require,module,exports){
"use strict";
/**
* This class defines a registry for custom formats used within JSF.
*/
var Registry = (function () {
function Registry() {
// empty by default
this.data = {};
}
/**
* Registers custom format
*/
Registry.prototype.register = function (name, callback) {
this.data[name] = callback;
};
/**
* Register many formats at one shot
*/
Registry.prototype.registerMany = function (formats) {
for (var name in formats) {
this.data[name] = formats[name];
}
};
/**
* Returns element by registry key
*/
Registry.prototype.get = function (name) {
var format = this.data[name];
if (typeof format === 'undefined') {
throw new Error('unknown registry key ' + JSON.stringify(name));
}
return format;
};
/**
* Returns the whole registry content
*/
Registry.prototype.list = function () {
return this.data;
};
return Registry;
}());
module.exports = Registry;
},{}],6:[function(require,module,exports){
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var ParseError = (function (_super) {
__extends(ParseError, _super);
function ParseError(message, path) {
_super.call(this);
this.path = path;
Error.captureStackTrace(this, this.constructor);
this.name = 'ParseError';
this.message = message;
this.path = path;
}
return ParseError;
}(Error));
module.exports = ParseError;
},{}],7:[function(require,module,exports){
"use strict";
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}
*/
function inferType(obj, schemaPath) {
for (var typeName in inferredProperties) {
var lastElementInPath = schemaPath[schemaPath.length - 1];
if (matchesType(obj, lastElementInPath, inferredProperties[typeName])) {
return typeName;
}
}
}
module.exports = inferType;
},{}],8:[function(require,module,exports){
/// <reference path="../index.d.ts" />
"use strict";
/**
* Returns random element of a collection
*
* @param collection
* @returns {T}
*/
function pick(collection) {
return collection[Math.floor(Math.random() * collection.length)];
}
/**
* Returns shuffled collection of elements
*
* @param collection
* @returns {T[]}
*/
function shuffle(collection) {
var tmp, key, copy = collection.slice(), length = collection.length;
for (; length > 0;) {
key = Math.floor(Math.random() * length);
// swap
tmp = copy[--length];
copy[length] = copy[key];
copy[key] = tmp;
}
return copy;
}
/**
* These values determine default range for random.number function
*
* @type {number}
*/
var MIN_NUMBER = -100, MAX_NUMBER = 100;
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
* @see http://stackoverflow.com/a/1527820/769384
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
* Generates random number according to parameters passed
*
* @param min
* @param max
* @param defMin
* @param defMax
* @param hasPrecision
* @returns {number}
*/
function number(min, max, defMin, defMax, hasPrecision) {
if (hasPrecision === void 0) { hasPrecision = false; }
defMin = typeof defMin === 'undefined' ? MIN_NUMBER : defMin;
defMax = typeof defMax === 'undefined' ? MAX_NUMBER : defMax;
min = typeof min === 'undefined' ? defMin : min;
max = typeof max === 'undefined' ? defMax : max;
if (max < min) {
max += min;
}
var result = getRandomInt(min, max);
if (!hasPrecision) {
return parseInt(result + '', 10);
}
return result;
}
module.exports = {
pick: pick,
shuffle: shuffle,
number: number
};
},{}],9:[function(require,module,exports){
"use strict";
var deref = require('deref');
var traverse = require('./traverse');
var random = require('./random');
var utils = require('./utils');
function isKey(prop) {
return prop === 'enum' || prop === 'default' || prop === 'required' || prop === 'definitions';
}
// TODO provide types
function run(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.number(1, 5);
}
seen[id] -= 1;
utils.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 (schema) {
utils.merge(sub, reduce(schema));
});
}
if (Array.isArray(sub.oneOf || sub.anyOf)) {
var mix = sub.oneOf || sub.anyOf;
delete sub.anyOf;
delete sub.oneOf;
utils.merge(sub, random.pick(mix));
}
for (var prop in sub) {
if ((Array.isArray(sub[prop]) || typeof sub[prop] === 'object') && sub[prop] !== null && !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;
}
}
}
module.exports = run;
},{"./random":8,"./traverse":10,"./utils":11,"deref":29}],10:[function(require,module,exports){
"use strict";
var random = require('./random');
var ParseError = require('./error');
var inferType = require('./infer');
var types = require('../types/index');
var option = require('../api/option');
function isExternal(schema) {
return schema.faker || schema.chance;
}
function reduceExternal(schema, path) {
if (schema['x-faker']) {
schema.faker = schema['x-faker'];
}
if (schema['x-chance']) {
schema.chance = schema['x-chance'];
}
var fakerUsed = schema.faker !== undefined, chanceUsed = schema.chance !== undefined;
if (fakerUsed && chanceUsed) {
throw new ParseError('ambiguous generator when using both faker and chance: ' + JSON.stringify(schema), path);
}
return schema;
}
// TODO provide types
function traverse(schema, path, resolve) {
resolve(schema);
if (Array.isArray(schema.enum)) {
return random.pick(schema.enum);
}
if (option('useDefaultValue') && schema.default) {
return schema.default;
}
// TODO remove the ugly overcome
var type = schema.type;
if (Array.isArray(type)) {
type = random.pick(type);
}
else if (typeof type === 'undefined') {
// Attempt to infer the type
type = inferType(schema, path) || type;
}
schema = reduceExternal(schema, path);
if (isExternal(schema)) {
type = 'external';
}
if (typeof type === 'string') {
if (!types[type]) {
if (option('failOnInvalidTypes')) {
throw new ParseError('unknown primitive ' + JSON.stringify(type), path.concat(['type']));
}
else {
return option('defaultInvalidTypeProduct');
}
}
else {
try {
return types[type](schema, path, resolve, traverse);
}
catch (e) {
if (typeof e.path === 'undefined') {
throw new ParseError(e.message, path);
}
throw e;
}
}
}
var copy = {};
if (Array.isArray(schema)) {
copy = [];
}
for (var prop in schema) {
if (typeof schema[prop] === 'object' && prop !== 'definitions') {
copy[prop] = traverse(schema[prop], path.concat([prop]), resolve);
}
else {
copy[prop] = schema[prop];
}
}
return copy;
}
module.exports = traverse;
},{"../api/option":2,"../types/index":23,"./error":6,"./infer":7,"./random":8}],11:[function(require,module,exports){
"use strict";
function getSubAttribute(obj, dotSeparatedKey) {
var keyElements = dotSeparatedKey.split('.');
while (keyElements.length) {
var prop = keyElements.shift();
if (!obj[prop]) {
break;
}
obj = obj[prop];
}
return obj;
}
/**
* Returns true/false whether the object parameter has its own properties defined
*
* @param obj
* @param properties
* @returns {boolean}
*/
function hasProperties(obj) {
var properties = [];
for (var _i = 1; _i < arguments.length; _i++) {
properties[_i - 1] = arguments[_i];
}
return properties.filter(function (key) {
return typeof obj[key] !== 'undefined';
}).length > 0;
}
/**
* Returns typecasted value.
* External generators (faker, chance) may return data in non-expected formats, such as string, when you might expect an
* integer. This function is used to force the typecast.
*
* @param value
* @param targetType
* @returns {any}
*/
function typecast(value, targetType) {
switch (targetType) {
case 'integer':
return parseInt(value, 10);
case 'number':
return parseFloat(value);
case 'string':
return JSON.stringify(value);
case 'boolean':
return !!value;
default:
return value;
}
}
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;
}
// TODO refactor merge function
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 = {
getSubAttribute: getSubAttribute,
hasProperties: hasProperties,
typecast: typecast,
clone: clone,
merge: merge
};
},{}],12:[function(require,module,exports){
"use strict";
/**
* Generates randomized boolean value.
*
* @returns {boolean}
*/
function booleanGenerator() {
return Math.random() > 0.5;
}
module.exports = booleanGenerator;
},{}],13:[function(require,module,exports){
"use strict";
var container = require('../class/Container');
var randexp = container.get('randexp');
/**
* Predefined core formats
* @type {[key: string]: string}
*/
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: '[a-f\\d]{4}(:[a-f\\d]{4}){7}',
uri: '[a-zA-Z][a-zA-Z0-9+-.]*'
};
/**
* Generates randomized string basing on a built-in regex format
*
* @param coreFormat
* @returns {string}
*/
function coreFormatGenerator(coreFormat) {
return randexp(regexps[coreFormat]).replace(/\{(\w+)\}/, function (match, key) {
return randexp(regexps[key]);
});
}
module.exports = coreFormatGenerator;
},{"../class/Container":3}],14:[function(require,module,exports){
"use strict";
var random = require('../core/random');
/**
* Generates randomized date time ISO format string.
*
* @returns {string}
*/
function dateTimeGenerator() {
return new Date(random.number(0, 100000000000000)).toISOString();
}
module.exports = dateTimeGenerator;
},{"../core/random":8}],15:[function(require,module,exports){
"use strict";
var random = require('../core/random');
/**
* Generates randomized ipv4 address.
*
* @returns {string}
*/
function ipv4Generator() {
return [0, 0, 0, 0].map(function () {
return random.number(0, 255);
}).join('.');
}
module.exports = ipv4Generator;
},{"../core/random":8}],16:[function(require,module,exports){
"use strict";
/**
* Generates null value.
*
* @returns {null}
*/
function nullGenerator() {
return null;
}
module.exports = nullGenerator;
},{}],17:[function(require,module,exports){
"use strict";
var words = require('../generators/words');
var random = require('../core/random');
/**
* Helper function used by thunkGenerator to produce some words for the final result.
*
* @returns {string}
*/
function produce() {
var length = random.number(1, 5);
return words(length).join(' ');
}
/**
* Generates randomized concatenated string based on words generator.
*
* @returns {string}
*/
function thunkGenerator(min, max) {
if (min === void 0) { min = 0; }
if (max === void 0) { max = 140; }
var min = Math.max(0, min), max = random.number(min, max), result = produce();
// append until length is reached
while (result.length < min) {
result += produce();
}
// cut if needed
if (result.length > max) {
result = result.substr(0, max);
}
return result;
}
module.exports = thunkGenerator;
},{"../core/random":8,"../generators/words":18}],18:[function(require,module,exports){
"use strict";
var random = require('../core/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 length
* @returns {Array.<string>}
*/
function wordsGenerator(length) {
var words = random.shuffle(LIPSUM_WORDS);
return words.slice(0, length);
}
module.exports = wordsGenerator;
},{"../core/random":8}],19:[function(require,module,exports){
"use strict";
var container = require('./class/Container');
var format = require('./api/format');
var option = require('./api/option');
var run = require('./core/run');
var jsf = function (schema, refs) {
return run(schema, refs);
};
jsf.format = format;
jsf.option = option;
// returns itself for chaining
jsf.extend = function (name, cb) {
container.extend(name, cb);
return jsf;
};
jsf.version = '0.3.5';
module.exports = jsf;
},{"./api/format":1,"./api/option":2,"./class/Container":3,"./core/run":9}],20:[function(require,module,exports){
"use strict";
var random = require('../core/random');
var utils = require('../core/utils');
var ParseError = require('../core/error');
// TODO provide types
function unique(path, items, value, sample, resolve, traverseCallback) {
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(traverseCallback(value.items || sample, path, resolve));
if (!limit--) {
break;
}
}
return tmp;
}
// TODO provide types
var arrayType = function arrayType(value, path, resolve, traverseCallback) {
var items = [];
if (!(value.items || value.additionalItems)) {
if (utils.hasProperties(value, 'minItems', 'maxItems', 'uniqueItems')) {
throw new ParseError('missing items for ' + JSON.stringify(value), path);
}
return items;
}
// see http://stackoverflow.com/a/38355228/769384
// after type guards support subproperties (in TS 2.0) we can simplify below to (value.items instanceof Array)
// so that value.items.map becomes recognized for typescript compiler
var tmpItems = value.items;
if (tmpItems instanceof Array) {
return Array.prototype.concat.apply(items, tmpItems.map(function (item, key) {
var itemSubpath = path.concat(['items', key + '']);
return traverseCallback(item, itemSubpath, resolve);
}));
}
var length = random.number(value.minItems, value.maxItems, 1, 5),
// TODO below looks bad. Should additionalItems be copied as-is?
sample = typeof value.additionalItems === 'object' ? value.additionalItems : {};
for (var current = items.length; current < length; current++) {
var itemSubpath = path.concat(['items', current + '']);
var element = traverseCallback(value.items || sample, itemSubpath, resolve);
items.push(element);
}
if (value.uniqueItems) {
return unique(path.concat(['items']), items, value, sample, resolve, traverseCallback);
}
return items;
};
module.exports = arrayType;
},{"../core/error":6,"../core/random":8,"../core/utils":11}],21:[function(require,module,exports){
"use strict";
var booleanGenerator = require('../generators/boolean');
var booleanType = booleanGenerator;
module.exports = booleanType;
},{"../generators/boolean":12}],22:[function(require,module,exports){
"use strict";
var utils = require('../core/utils');
var container = require('../class/Container');
var externalType = function externalType(value, path) {
var libraryName = value.faker ? 'faker' : 'chance', libraryModule = value.faker ? container.get('faker') : container.get('chance'), key = value.faker || value.chance, path = key, args = [];
if (typeof path === 'object') {
path = Object.keys(path)[0];
if (Array.isArray(key[path])) {
args = key[path];
}
else {
args.push(key[path]);
}
}
var genFunction = utils.getSubAttribute(libraryModule, path);
if (typeof genFunction !== 'function') {
throw new Error('unknown ' + libraryName + '-generator for ' + JSON.stringify(key));
}
// see #116, #117 - faker.js 3.1.0 introduced local dependencies between generators
// making jsf break after upgrading from 3.0.1
var contextObject = libraryModule;
if (libraryName === 'faker') {
var fakerModuleName = path.split('.')[0];
contextObject = libraryModule[fakerModuleName];
}
var result = genFunction.apply(contextObject, args);
return utils.typecast(result, value.type);
};
module.exports = externalType;
},{"../class/Container":3,"../core/utils":11}],23:[function(require,module,exports){
"use strict";
var _boolean = require('./boolean');
var _null = require('./null');
var _array = require('./array');
var _integer = require('./integer');
var _number = require('./number');
var _object = require('./object');
var _string = require('./string');
var _external = require('./external');
var typeMap = {
boolean: _boolean,
null: _null,
array: _array,
integer: _integer,
number: _number,
object: _object,
string: _string,
external: _external
};
module.exports = typeMap;
},{"./array":20,"./boolean":21,"./external":22,"./integer":24,"./null":25,"./number":26,"./object":27,"./string":28}],24:[function(require,module,exports){
"use strict";
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.
var integerType = function integerType(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);
};
module.exports = integerType;
},{"./number":26}],25:[function(require,module,exports){
"use strict";
var nullGenerator = require('../generators/null');
var nullType = nullGenerator;
module.exports = nullType;
},{"../generators/null":16}],26:[function(require,module,exports){
"use strict";
var random = require('../core/random');
var MIN_INTEGER = -100000000, MAX_INTEGER = 100000000;
var numberType = function numberType(value) {
var min = typeof value.minimum === 'undefined' ? MIN_INTEGER : value.minimum, max = typeof value.maximum === 'undefined' ? MAX_INTEGER : value.maximum, multipleOf = value.multipleOf;
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 (min > max) {
return NaN;
}
if (multipleOf) {
return Math.floor(random.number(min, max) / multipleOf) * multipleOf;
}
return random.number(min, max, undefined, undefined, true);
};
module.exports = numberType;
},{"../core/random":8}],27:[function(require,module,exports){
"use strict";
var container = require('../class/Container');
var random = require('../core/random');
var words = require('../generators/words');
var utils = require('../core/utils');
var ParseError = require('../core/error');
var randexp = container.get('randexp');
// TODO provide types
var objectType = function objectType(value, path, resolve, traverseCallback) {
var props = {};
if (!(value.properties || value.patternProperties || value.additionalProperties)) {
if (utils.hasProperties(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.number(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 traverseCallback(props, path.concat(['properties']), resolve);
};
module.exports = objectType;
},{"../class/Container":3,"../core/error":6,"../core/random":8,"../core/utils":11,"../generators/words":18}],28:[function(require,module,exports){
"use strict";
var thunk = require('../generators/thunk');
var ipv4 = require('../generators/ipv4');
var dateTime = require('../generators/dateTime');
var coreFormat = require('../generators/coreFormat');
var format = require('../api/format');
var container = require('../class/Container');
var randexp = container.get('randexp');
function generateFormat(value) {
switch (value.format) {
case 'date-time':
return dateTime();
case 'ipv4':
return ipv4();
case 'regex':
// TODO: discuss
return '.+?';
case 'email':
case 'hostname':
case 'ipv6':
case 'uri':
return coreFormat(value.format);
default:
var callback = format(value.format);
return callback(container.getAll(), value);
}
}
var stringType = function stringType(value) {
if (value.format) {
return generateFormat(value);
}
else if (value.pattern) {
return randexp(value.pattern);
}
else {
return thunk(value.minLength, value.maxLength);
}
};
module.exports = stringType;
},{"../api/format":1,"../class/Container":3,"../generators/coreFormat":13,"../generators/dateTime":14,"../generators/ipv4":15,"../generators/thunk":17}],29:[function(require,module,exports){
'use strict';
var $ = require('./util/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":31,"./util/helpers":32,"./util/normalize-schema":33,"./util/resolve-schema":34}],30:[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;
};
},{}],31:[function(require,module,exports){
'use strict';
var $ = require('./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;
};
},{"./helpers":32}],32:[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];
}
function isKeyword(prop) {
return prop === 'enum' || prop === 'default' || prop === 'required';
}
module.exports = {
isURL: isURL,
parseURI: parseURI,
isKeyword: isKeyword,
resolveURL: resolveURL,
getDocumentURI: getDocumentURI
};
},{}],33:[function(require,module,exports){
'use strict';
var $ = require('./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' && value !== null && !$.isKeyword(key)) {
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":30,"./helpers":32}],34:[function(require,module,exports){
'use strict';
var $ = require('./helpers');
var find = require('./find-reference');
var deepExtend = require('deep-extend');
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' && obj[prop] !== null && !$.isKeyword(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":31,"./helpers":32,"deep-extend":35}],35:[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;
}
},{}],36:[function(require,module,exports){
/**
*
* @namespace faker.address
*/
function Address (faker) {
var f = faker.fake,
Helpers = faker.helpers;
/**
* Generates random zipcode from format. If format is not specified, the
* locale's zip format is used.
*
* @method faker.address.zipCode
* @param {String} format
*/
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);
}
/**
* Generates a random localized city name. The format string can contain any
* method provided by faker wrapped in `{{}}`, e.g. `{{name.firstName}}` in
* order to build the city name.
*
* If no format string is provided one of the following is randomly used:
*
* * `{{address.cityPrefix}} {{name.firstName}}{{address.citySuffix}}`
* * `{{address.cityPrefix}} {{name.firstName}}`
* * `{{name.firstName}}{{address.citySuffix}}`
* * `{{name.lastName}}{{address.citySuffix}}`
*
* @method faker.address.city
* @param {String} 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]);
}
/**
* Return a random localized city prefix
* @method faker.address.cityPrefix
*/
this.cityPrefix = function () {
return faker.random.arrayElement(faker.definitions.address.city_prefix);
}
/**
* Return a random localized city suffix
*
* @method faker.address.citySuffix
*/
this.citySuffix = function () {
return faker.random.arrayElement(faker.definitions.address.city_suffix);
}
/**
* Returns a random localized street name
*
* @method faker.address.streetName
*/
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.
//
/**
* Returns a random localized street address
*
* @method faker.address.streetAddress
* @param {Boolean} useFullAddress
*/
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;
}
/**
* streetSuffix
*
* @method faker.address.streetSuffix
*/
this.streetSuffix = function () {
return faker.random.arrayElement(faker.definitions.address.street_suffix);
}
/**
* streetPrefix
*
* @method faker.address.streetPrefix
*/
this.streetPrefix = function () {
return faker.random.arrayElement(faker.definitions.address.street_prefix);
}
/**
* secondaryAddress
*
* @method faker.address.secondaryAddress
*/
this.secondaryAddress = function () {
return Helpers.replaceSymbolWithNumber(faker.random.arrayElement(
[
'Apt. ###',
'Suite ###'
]
));
}
/**
* county
*
* @method faker.address.county
*/
this.county = function () {
return faker.random.arrayElement(faker.definitions.address.county);
}
/**
* country
*
* @method faker.address.country
*/
this.country = function () {
return faker.random.arrayElement(faker.definitions.address.country);
}
/**
* countryCode
*
* @method faker.address.countryCode
*/
this.countryCode = function () {
return faker.random.arrayElement(faker.definitions.address.country_code);
}
/**
* state
*
* @method faker.address.state
* @param {Boolean} useAbbr
*/
this.state = function (useAbbr) {
return faker.random.arrayElement(faker.definitions.address.state);
}
/**
* stateAbbr
*
* @method faker.address.stateAbbr
*/
this.stateAbbr = function () {
return faker.random.arrayElement(faker.definitions.address.state_abbr);
}
/**
* latitude
*
* @method faker.address.latitude
*/
this.latitude = function () {
return (faker.random.number(180 * 10000) / 10000.0 - 90.0).toFixed(4);
}
/**
* longitude
*
* @method faker.address.longitude
*/
this.longitude = function () {
return (faker.random.number(360 * 10000) / 10000.0 - 180.0).toFixed(4);
}
return this;
}
module.exports = Address;
},{}],37:[function(require,module,exports){
/**
*
* @namespace faker.commerce
*/
var Commerce = function (faker) {
var self = this;
/**
* color
*
* @method faker.commerce.color
*/
self.color = function() {
return faker.random.arrayElement(faker.definitions.commerce.color);
};
/**
* department
*
* @method faker.commerce.department
* @param {number} max
* @param {number} fixedAmount
*/
self.department = function(max, fixedAmount) {
return faker.random.arrayElement(faker.definitions.commerce.department);
};
/**
* productName
*
* @method faker.commerce.productName
*/
self.productName = function() {
return faker.commerce.productAdjective() + " " +
faker.commerce.productMaterial() + " " +
faker.commerce.product();
};
/**
* price
*
* @method faker.commerce.price
* @param {number} min
* @param {number} max
* @param {number} dec
* @param {string} symbol
*/
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;
}
var randValue = faker.random.number({ max: max, min: min });
return symbol + (Math.round(randValue * 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 + " ");
};
*/
/**
* productAdjective
*
* @method faker.commerce.productAdjective
*/
self.productAdjective = function() {
return faker.random.arrayElement(faker.definitions.commerce.product_name.adjective);
};
/**
* productMaterial
*
* @method faker.commerce.productMaterial
*/
self.productMaterial = function() {
return faker.random.arrayElement(faker.definitions.commerce.product_name.material);
};
/**
* product
*
* @method faker.commerce.product
*/
self.product = function() {
return faker.random.arrayElement(faker.definitions.commerce.product_name.product);
}
return self;
};
module['exports'] = Commerce;
},{}],38:[function(require,module,exports){
/**
*
* @namespace faker.company
*/
var Company = function (faker) {
var self = this;
var f = faker.fake;
/**
* suffixes
*
* @method faker.company.suffixes
*/
this.suffixes = function () {
// Don't want the source array exposed to modification, so return a copy
return faker.definitions.company.suffix.slice(0);
}
/**
* companyName
*
* @method faker.company.companyName
* @param {string} format
*/
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]);
}
/**
* companySuffix
*
* @method faker.company.companySuffix
*/
this.companySuffix = function () {
return faker.random.arrayElement(faker.company.suffixes());
}
/**
* catchPhrase
*
* @method faker.company.catchPhrase
*/
this.catchPhrase = function () {
return f('{{company.catchPhraseAdjective}} {{company.catchPhraseDescriptor}} {{company.catchPhraseNoun}}')
}
/**
* bs
*
* @method faker.company.bs
*/
this.bs = function () {
return f('{{company.bsAdjective}} {{company.bsBuzz}} {{company.bsNoun}}');
}
/**
* catchPhraseAdjective
*
* @method faker.company.catchPhraseAdjective
*/
this.catchPhraseAdjective = function () {
return faker.random.arrayElement(faker.definitions.company.adjective);
}
/**
* catchPhraseDescriptor
*
* @method faker.company.catchPhraseDescriptor
*/
this.catchPhraseDescriptor = function () {
return faker.random.arrayElement(faker.definitions.company.descriptor);
}
/**
* catchPhraseNoun
*
* @method faker.company.catchPhraseNoun
*/
this.catchPhraseNoun = function () {
return faker.random.arrayElement(faker.definitions.company.noun);
}
/**
* bsAdjective
*
* @method faker.company.bsAdjective
*/
this.bsAdjective = function () {
return faker.random.arrayElement(faker.definitions.company.bs_adjective);
}
/**
* bsBuzz
*
* @method faker.company.bsBuzz
*/
this.bsBuzz = function () {
return faker.random.arrayElement(faker.definitions.company.bs_verb);
}
/**
* bsNoun
*
* @method faker.company.bsNoun
*/
this.bsNoun = function () {
return faker.random.arrayElement(faker.definitions.company.bs_noun);
}
}
module['exports'] = Company;
},{}],39:[function(require,module,exports){
/**
*
* @namespace faker.date
*/
var _Date = function (faker) {
var self = this;
/**
* past
*
* @method faker.date.past
* @param {number} years
* @param {date} refDate
*/
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;
};
/**
* future
*
* @method faker.date.future
* @param {number} years
* @param {date} refDate
*/
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;
};
/**
* between
*
* @method faker.date.between
* @param {date} from
* @param {date} to
*/
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;
};
/**
* recent
*
* @method faker.date.recent
* @param {number} days
*/
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;
};
/**
* month
*
* @method faker.date.month
* @param {object} options
*/
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);
};
/**
* weekday
*
* @param {object} options
* @method faker.date.weekday
*/
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;
},{}],40:[function(require,module,exports){
/*
fake.js - generator method for combining faker methods based on string input
*/
function Fake (faker) {
/**
* Generator method for combining faker methods based on string input
*
* __Example:__
*
* ```
* console.log(faker.fake('{{name.lastName}}, {{name.firstName}} {{name.suffix}}'));
* //outputs: "Marks, Dean Sr."
* ```
*
* This will interpolate the format string with the value of methods
* [name.lastName]{@link faker.name.lastName}, [name.firstName]{@link faker.name.firstName},
* and [name.suffix]{@link faker.name.suffix}
*
* @method faker.fake
* @param {string} str
*/
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 token = str.substr(start + 2, end - start - 2);
var method = token.replace('}}', '').replace('{{', '');
// console.log('method', method)
// extract method parameters
var regExp = /\(([^)]+)\)/;
var matches = regExp.exec(method);
var parameters = '';
if (matches) {
method = method.replace(regExp, '');
parameters = matches[1];
}
// 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]];
// If parameters are populated here, they are always going to be of string type
// since we might actually be dealing with an object or array,
// we always attempt to the parse the incoming parameters into JSON
var params;
// Note: we experience a small performance hit here due to JSON.parse try / catch
// If anyone actually needs to optimize this specific code path, please open a support issue on github
try {
params = JSON.parse(parameters)
} catch (err) {
// since JSON.parse threw an error, assume parameters was actually a string
params = parameters;
}
var result;
if (typeof params === "string" && params.length === 0) {
result = fn.call(this);
} else {
result = fn.call(this, params);
}
// replace the found tag with the returned fake value
res = str.replace('{{' + token + '}}', result);
// return the response recursively until we are done finding all tags
return fake(res);
}
return this;
}
module['exports'] = Fake;
},{}],41:[function(require,module,exports){
/**
*
* @namespace faker.finance
*/
var Finance = function (faker) {
var Helpers = faker.helpers,
self = this;
/**
* account
*
* @method faker.finance.account
* @param {number} length
*/
self.account = function (length) {
length = length || 8;
var template = '';
for (var i = 0; i < length; i++) {
template = template + '#';
}
length = null;
return Helpers.replaceSymbolWithNumber(template);
}
/**
* accountName
*
* @method faker.finance.accountName
*/
self.accountName = function () {
return [Helpers.randomize(faker.definitions.finance.account_type), 'Account'].join(' ');
}
/**
* mask
*
* @method faker.finance.mask
* @param {number} length
* @param {boolean} parens
* @param {boolean} elipsis
*/
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
/**
* amount
*
* @method faker.finance.amount
* @param {number} min
* @param {number} max
* @param {number} dec
* @param {string} symbol
*/
self.amount = function (min, max, dec, symbol) {
min = min || 0;
max = max || 1000;
dec = dec || 2;
symbol = symbol || '';
var randValue = faker.random.number({ max: max, min: min });
return symbol + (Math.round(randValue * Math.pow(10, dec)) / Math.pow(10, dec)).toFixed(dec);
}
/**
* transactionType
*
* @method faker.finance.transactionType
*/
self.transactionType = function () {
return Helpers.randomize(faker.definitions.finance.transaction_type);
}
/**
* currencyCode
*
* @method faker.finance.currencyCode
*/
self.currencyCode = function () {
return faker.random.objectElement(faker.definitions.finance.currency)['code'];
}
/**
* currencyName
*
* @method faker.finance.currencyName
*/
self.currencyName = function () {
return faker.random.objectElement(faker.definitions.finance.currency, 'key');
}
/**
* currencySymbol
*
* @method faker.finance.currencySymbol
*/
self.currencySymbol = function () {
var symbol;
while (!symbol) {
symbol = faker.random.objectElement(faker.definitions.finance.currency)['symbol'];
}
return symbol;
}
/**
* bitcoinAddress
*
* @method faker.finance.bitcoinAddress
*/
self.bitcoinAddress = function () {
var addressLength = faker.random.number({ min: 27, max: 34 });
var address = faker.random.arrayElement(['1', '3']);
for (var i = 0; i < addressLength - 1; i++)
address += faker.random.alphaNumeric().toUpperCase();
return address;
}
}
module['exports'] = Finance;
},{}],42:[function(require,module,exports){
/**
*
* @namespace faker.hacker
*/
var Hacker = function (faker) {
var self = this;
/**
* abbreviation
*
* @method faker.hacker.abbreviation
*/
self.abbreviation = function () {
return faker.random.arrayElement(faker.definitions.hacker.abbreviation);
};
/**
* adjective
*
* @method faker.hacker.adjective
*/
self.adjective = function () {
return faker.random.arrayElement(faker.definitions.hacker.adjective);
};
/**
* noun
*
* @method faker.hacker.noun
*/
self.noun = function () {
return faker.random.arrayElement(faker.definitions.hacker.noun);
};
/**
* verb
*
* @method faker.hacker.verb
*/
self.verb = function () {
return faker.random.arrayElement(faker.definitions.hacker.verb);
};
/**
* ingverb
*
* @method faker.hacker.ingverb
*/
self.ingverb = function () {
return faker.random.arrayElement(faker.definitions.hacker.ingverb);
};
/**
* phrase
*
* @method faker.hacker.phrase
*/
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;
},{}],43:[function(require,module,exports){
/**
*
* @namespace faker.helpers
*/
var Helpers = function (faker) {
var self = this;
/**
* backword-compatibility
*
* @method faker.helpers.randomize
* @param {array} array
*/
self.randomize = function (array) {
array = array || ["a", "b", "c"];
return faker.random.arrayElement(array);
};
/**
* slugifies string
*
* @method faker.helpers.slugify
* @param {string} 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
*
* @method faker.helpers.replaceSymbolWithNumber
* @param {string} string
* @param {string} symbol defaults to `"#"`
*/
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
*
* @method faker.helpers.replaceSymbols
* @param {string} string
*/
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 += faker.random.arrayElement(alpha);
} else {
str += string.charAt(i);
}
}
return str;
};
/**
* takes an array and returns it randomized
*
* @method faker.helpers.shuffle
* @param {array} o
*/
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;
};
/**
* mustache
*
* @method faker.helpers.mustache
* @param {string} str
* @param {object} data
*/
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;
};
/**
* createCard
*
* @method faker.helpers.createCard
*/
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()]
};
};
/**
* contextualCard
*
* @method faker.helpers.contextualCard
*/
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()
}
};
};
/**
* userCard
*
* @method faker.helpers.userCard
*/
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()
}
};
};
/**
* createTransaction
*
* @method faker.helpers.createTransaction
*/
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;
},{}],44:[function(require,module,exports){
/**
*
* @namespace faker.image
*/
var Image = function (faker) {
var self = this;
/**
* image
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.image
*/
self.image = function (width, height, randomize) {
var categories = ["abstract", "animals", "business", "cats", "city", "food", "nightlife", "fashion", "people", "nature", "sports", "technics", "transport"];
return self[faker.random.arrayElement(categories)](width, height, randomize);
};
/**
* avatar
*
* @method faker.image.avatar
*/
self.avatar = function () {
return faker.internet.avatar();
};
/**
* imageUrl
*
* @param {number} width
* @param {number} height
* @param {string} category
* @param {boolean} randomize
* @method faker.image.imageUrl
*/
self.imageUrl = function (width, height, category, randomize) {
var width = width || 640;
var height = height || 480;
var url ='http://lorempixel.com/' + width + '/' + height;
if (typeof category !== 'undefined') {
url += '/' + category;
}
if (randomize) {
url += '?' + faker.random.number()
}
return url;
};
/**
* abstract
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.abstract
*/
self.abstract = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'abstract', randomize);
};
/**
* animals
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.animals
*/
self.animals = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'animals', randomize);
};
/**
* business
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.business
*/
self.business = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'business', randomize);
};
/**
* cats
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.cats
*/
self.cats = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'cats', randomize);
};
/**
* city
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.city
*/
self.city = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'city', randomize);
};
/**
* food
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.food
*/
self.food = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'food', randomize);
};
/**
* nightlife
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.nightlife
*/
self.nightlife = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'nightlife', randomize);
};
/**
* fashion
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.fashion
*/
self.fashion = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'fashion', randomize);
};
/**
* people
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.people
*/
self.people = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'people', randomize);
};
/**
* nature
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.nature
*/
self.nature = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'nature', randomize);
};
/**
* sports
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.sports
*/
self.sports = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'sports', randomize);
};
/**
* technics
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.technics
*/
self.technics = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'technics', randomize);
};
/**
* transport
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.transport
*/
self.transport = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'transport', randomize);
}
}
module["exports"] = Image;
},{}],45:[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
*/
/**
*
* @namespace faker
*/
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);
var System = require('./system');
self.system = new System(self);
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", "example_email", "password"],
"commerce": ["color", "department", "product_name", "price", "categories"],
"system": ["mimeTypes"],
"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":36,"./commerce":37,"./company":38,"./date":39,"./fake":40,"./finance":41,"./hacker":42,"./helpers":43,"./image":44,"./internet":46,"./lorem":171,"./name":172,"./phone_number":173,"./random":174,"./system":175}],46:[function(require,module,exports){
var password_generator = require('../vendor/password-generator.js'),
random_ua = require('../vendor/user-agent');
/**
*
* @namespace faker.internet
*/
var Internet = function (faker) {
var self = this;
/**
* avatar
*
* @method faker.internet.avatar
*/
self.avatar = function () {
return faker.random.arrayElement(faker.definitions.internet.avatar_uri);
};
self.avatar.schema = {
"description": "Generates a URL for an avatar.",
"sampleResults": ["https://s3.amazonaws.com/uifaces/faces/twitter/igorgarybaldi/128.jpg"]
};
/**
* email
*
* @method faker.internet.email
* @param {string} firstName
* @param {string} lastName
* @param {string} provider
*/
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.email.schema = {
"description": "Generates a valid email address based on optional input criteria",
"sampleResults": ["foo.bar@gmail.com"],
"properties": {
"firstName": {
"type": "string",
"required": false,
"description": "The first name of the user"
},
"lastName": {
"type": "string",
"required": false,
"description": "The last name of the user"
},
"provider": {
"type": "string",
"required": false,
"description": "The domain of the user"
}
}
};
/**
* exampleEmail
*
* @method faker.internet.exampleEmail
* @param {string} firstName
* @param {string} lastName
*/
self.exampleEmail = function (firstName, lastName) {
var provider = faker.random.arrayElement(faker.definitions.internet.example_email);
return self.email(firstName, lastName, provider);
};
/**
* userName
*
* @method faker.internet.userName
* @param {string} firstName
* @param {string} lastName
*/
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.userName.schema = {
"description": "Generates a username based on one of several patterns. The pattern is chosen randomly.",
"sampleResults": [
"Kirstin39",
"Kirstin.Smith",
"Kirstin.Smith39",
"KirstinSmith",
"KirstinSmith39",
],
"properties": {
"firstName": {
"type": "string",
"required": false,
"description": "The first name of the user"
},
"lastName": {
"type": "string",
"required": false,
"description": "The last name of the user"
}
}
};
/**
* protocol
*
* @method faker.internet.protocol
*/
self.protocol = function () {
var protocols = ['http','https'];
return faker.random.arrayElement(protocols);
};
self.protocol.schema = {
"description": "Randomly generates http or https",
"sampleResults": ["https", "http"]
};
/**
* url
*
* @method faker.internet.url
*/
self.url = function () {
return faker.internet.protocol() + '://' + faker.internet.domainName();
};
self.url.schema = {
"description": "Generates a random URL. The URL could be secure or insecure.",
"sampleResults": [
"http://rashawn.name",
"https://rashawn.name"
]
};
/**
* domainName
*
* @method faker.internet.domainName
*/
self.domainName = function () {
return faker.internet.domainWord() + "." + faker.internet.domainSuffix();
};
self.domainName.schema = {
"description": "Generates a random domain name.",
"sampleResults": ["marvin.org"]
};
/**
* domainSuffix
*
* @method faker.internet.domainSuffix
*/
self.domainSuffix = function () {
return faker.random.arrayElement(faker.definitions.internet.domain_suffix);
};
self.domainSuffix.schema = {
"description": "Generates a random domain suffix.",
"sampleResults": ["net"]
};
/**
* domainWord
*
* @method faker.internet.domainWord
*/
self.domainWord = function () {
return faker.name.firstName().replace(/([\\~#&*{}/:<>?|\"'])/ig, '').toLowerCase();
};
self.domainWord.schema = {
"description": "Generates a random domain word.",
"sampleResults": ["alyce"]
};
/**
* ip
*
* @method faker.internet.ip
*/
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.ip.schema = {
"description": "Generates a random IP.",
"sampleResults": ["97.238.241.11"]
};
/**
* userAgent
*
* @method faker.internet.userAgent
*/
self.userAgent = function () {
return random_ua.generate();
};
self.userAgent.schema = {
"description": "Generates a random user agent.",
"sampleResults": ["Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_7_5 rv:6.0; SL) AppleWebKit/532.0.1 (KHTML, like Gecko) Version/7.1.6 Safari/532.0.1"]
};
/**
* color
*
* @method faker.internet.color
* @param {number} baseRed255
* @param {number} baseGreen255
* @param {number} baseBlue255
*/
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.color.schema = {
"description": "Generates a random hexadecimal color.",
"sampleResults": ["#06267f"],
"properties": {
"baseRed255": {
"type": "number",
"required": false,
"description": "The red value. Valid values are 0 - 255."
},
"baseGreen255": {
"type": "number",
"required": false,
"description": "The green value. Valid values are 0 - 255."
},
"baseBlue255": {
"type": "number",
"required": false,
"description": "The blue value. Valid values are 0 - 255."
}
}
};
/**
* mac
*
* @method faker.internet.mac
*/
self.mac = function(){
var i, mac = "";
for (i=0; i < 12; i++) {
mac+= faker.random.number(15).toString(16);
if (i%2==1 && i != 11) {
mac+=":";
}
}
return mac;
};
self.mac.schema = {
"description": "Generates a random mac address.",
"sampleResults": ["78:06:cc:ae:b3:81"]
};
/**
* password
*
* @method faker.internet.password
* @param {number} len
* @param {boolean} memorable
* @param {string} pattern
* @param {string} prefix
*/
self.password = function (len, memorable, pattern, prefix) {
len = len || 15;
if (typeof memorable === "undefined") {
memorable = false;
}
return password_generator(len, memorable, pattern, prefix);
}
self.password.schema = {
"description": "Generates a random password.",
"sampleResults": [
"AM7zl6Mg",
"susejofe"
],
"properties": {
"length": {
"type": "number",
"required": false,
"description": "The number of characters in the password."
},
"memorable": {
"type": "boolean",
"required": false,
"description": "Whether a password should be easy to remember."
},
"pattern": {
"type": "regex",
"required": false,
"description": "A regex to match each character of the password against. This parameter will be negated if the memorable setting is turned on."
},
"prefix": {
"type": "string",
"required": false,
"description": "A value to prepend to the generated password. The prefix counts towards the length of the password."
}
}
};
};
module["exports"] = Internet;
},{"../vendor/password-generator.js":178,"../vendor/user-agent":179}],47:[function(require,module,exports){
module["exports"] = [
"#####",
"####",
"###"
];
},{}],48:[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}"
];
},{}],49:[function(require,module,exports){
module["exports"] = [
"North",
"East",
"West",
"South",
"New",
"Lake",
"Port"
];
},{}],50:[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"
];
},{}],51:[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"
];
},{}],52:[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"
];
},{}],53:[function(require,module,exports){
module["exports"] = [
"Avon",
"Bedfordshire",
"Berkshire",
"Borders",
"Buckinghamshire",
"Cambridgeshire"
];
},{}],54:[function(require,module,exports){
module["exports"] = [
"United States of America"
];
},{}],55:[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":47,"./city":48,"./city_prefix":49,"./city_suffix":50,"./country":51,"./country_code":52,"./county":53,"./default_country":54,"./postcode":56,"./postcode_by_state":57,"./secondary_address":58,"./state":59,"./state_abbr":60,"./street_address":61,"./street_name":62,"./street_suffix":63,"./time_zone":64}],56:[function(require,module,exports){
module["exports"] = [
"#####",
"#####-####"
];
},{}],57:[function(require,module,exports){
arguments[4][56][0].apply(exports,arguments)
},{"dup":56}],58:[function(require,module,exports){
module["exports"] = [
"Apt. ###",
"Suite ###"
];
},{}],59:[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"
];
},{}],60:[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"
];
},{}],61:[function(require,module,exports){
module["exports"] = [
"#{building_number} #{street_name}"
];
},{}],62:[function(require,module,exports){
module["exports"] = [
"#{Name.first_name} #{street_suffix}",
"#{Name.last_name} #{street_suffix}"
];
},{}],63:[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"
];
},{}],64:[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"
];
},{}],65:[function(require,module,exports){
module["exports"] = [
"#{Name.name}",
"#{Company.name}"
];
},{}],66:[function(require,module,exports){
var app = {};
module['exports'] = app;
app.name = require("./name");
app.version = require("./version");
app.author = require("./author");
},{"./author":65,"./name":67,"./version":68}],67:[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"
];
},{}],68:[function(require,module,exports){
module["exports"] = [
"0.#.#",
"0.##",
"#.##",
"#.#",
"#.#.#"
];
},{}],69:[function(require,module,exports){
module["exports"] = [
"2011-10-12",
"2012-11-12",
"2015-11-11",
"2013-9-12"
];
},{}],70:[function(require,module,exports){
module["exports"] = [
"1234-2121-1221-1211",
"1212-1221-1121-1234",
"1211-1221-1234-2201",
"1228-1221-1221-1431"
];
},{}],71:[function(require,module,exports){
module["exports"] = [
"visa",
"mastercard",
"americanexpress",
"discover"
];
},{}],72:[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":69,"./credit_card_numbers":70,"./credit_card_types":71}],73:[function(require,module,exports){
module["exports"] = [
"###-###-####",
"(###) ###-####",
"1-###-###-####",
"###.###.####"
];
},{}],74:[function(require,module,exports){
var cell_phone = {};
module['exports'] = cell_phone;
cell_phone.formats = require("./formats");
},{"./formats":73}],75:[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"
];
},{}],76:[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"
];
},{}],77:[function(require,module,exports){
var commerce = {};
module['exports'] = commerce;
commerce.color = require("./color");
commerce.department = require("./department");
commerce.product_name = require("./product_name");
},{"./color":75,"./department":76,"./product_name":78}],78:[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"
]
};
},{}],79:[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"
];
},{}],80:[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"
];
},{}],81:[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"
];
},{}],82:[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"
];
},{}],83:[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"
];
},{}],84:[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":79,"./bs_adjective":80,"./bs_noun":81,"./bs_verb":82,"./descriptor":83,"./name":85,"./noun":86,"./suffix":87}],85:[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}"
];
},{}],86:[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"
];
},{}],87:[function(require,module,exports){
module["exports"] = [
"Inc",
"and Sons",
"LLC",
"Group"
];
},{}],88:[function(require,module,exports){
module["exports"] = [
"/34##-######-####L/",
"/37##-######-####L/"
];
},{}],89:[function(require,module,exports){
module["exports"] = [
"/30[0-5]#-######-###L/",
"/368#-######-###L/"
];
},{}],90:[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/"
];
},{}],91:[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":88,"./diners_club":89,"./discover":90,"./jcb":92,"./laser":93,"./maestro":94,"./mastercard":95,"./solo":96,"./switch":97,"./visa":98}],92:[function(require,module,exports){
module["exports"] = [
"/3528-####-####-###L/",
"/3529-####-####-###L/",
"/35[3-8]#-####-####-###L/"
];
},{}],93:[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/"
];
},{}],94:[function(require,module,exports){
module["exports"] = [
"/50#{9,16}L/",
"/5[6-8]#{9,16}L/",
"/56##{9,16}L/"
];
},{}],95:[function(require,module,exports){
module["exports"] = [
"/5[1-5]##-####-####-###L/",
"/6771-89##-####-###L/"
];
},{}],96:[function(require,module,exports){
module["exports"] = [
"/6767-####-####-###L/",
"/6767-####-####-####-#L/",
"/6767-####-####-####-##L/"
];
},{}],97:[function(require,module,exports){
module["exports"] = [
"/6759-####-####-###L/",
"/6759-####-####-####-#L/",
"/6759-####-####-####-##L/"
];
},{}],98:[function(require,module,exports){
module["exports"] = [
"/4###########L/",
"/4###-####-####-###L/"
];
},{}],99:[function(require,module,exports){
var date = {};
module["exports"] = date;
date.month = require("./month");
date.weekday = require("./weekday");
},{"./month":100,"./weekday":101}],100:[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"
]
};
},{}],101:[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"
]
};
},{}],102:[function(require,module,exports){
module["exports"] = [
"Checking",
"Savings",
"Money Market",
"Investment",
"Home Loan",
"Credit Card",
"Auto Loan",
"Personal Loan"
];
},{}],103:[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": ""
}
};
},{}],104:[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":102,"./currency":103,"./transaction_type":105}],105:[function(require,module,exports){
module["exports"] = [
"deposit",
"withdrawal",
"payment",
"invoice"
];
},{}],106:[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"
];
},{}],107:[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"
];
},{}],108:[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":106,"./adjective":107,"./ingverb":109,"./noun":110,"./verb":111}],109:[function(require,module,exports){
module["exports"] = [
"backing up",
"bypassing",
"hacking",
"overriding",
"compressing",
"copying",
"navigating",
"indexing",
"connecting",
"generating",
"quantifying",
"calculating",
"synthesizing",
"transmitting",
"programming",
"parsing"
];
},{}],110:[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"
];
},{}],111:[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"
];
},{}],112:[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");
en.system = require("./system");
},{"./address":55,"./app":66,"./business":72,"./cell_phone":74,"./commerce":77,"./company":84,"./credit_card":91,"./date":99,"./finance":104,"./hacker":108,"./internet":117,"./lorem":118,"./name":122,"./phone_number":129,"./system":130,"./team":133}],113:[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"
];
},{}],114:[function(require,module,exports){
module["exports"] = [
"com",
"biz",
"info",
"name",
"net",
"org"
];
},{}],115:[function(require,module,exports){
module["exports"] = [
"example.org",
"example.com",
"example.net"
];
},{}],116:[function(require,module,exports){
module["exports"] = [
"gmail.com",
"yahoo.com",
"hotmail.com"
];
},{}],117:[function(require,module,exports){
var internet = {};
module['exports'] = internet;
internet.free_email = require("./free_email");
internet.example_email = require("./example_email");
internet.domain_suffix = require("./domain_suffix");
internet.avatar_uri = require("./avatar_uri");
},{"./avatar_uri":113,"./domain_suffix":114,"./example_email":115,"./free_email":116}],118:[function(require,module,exports){
var lorem = {};
module['exports'] = lorem;
lorem.words = require("./words");
lorem.supplemental = require("./supplemental");
},{"./supplemental":119,"./words":120}],119:[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"
];
},{}],120:[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"
];
},{}],121:[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"
];
},{}],122:[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":121,"./last_name":123,"./name":124,"./prefix":125,"./suffix":126,"./title":127}],123:[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"
];
},{}],124:[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}"
];
},{}],125:[function(require,module,exports){
module["exports"] = [
"Mr.",
"Mrs.",
"Ms.",
"Miss",
"Dr."
];
},{}],126:[function(require,module,exports){
module["exports"] = [
"Jr.",
"Sr.",
"I",
"II",
"III",
"IV",
"V",
"MD",
"DDS",
"PhD",
"DVM"
];
},{}],127:[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"
]
};
},{}],128:[function(require,module,exports){
module["exports"] = [
"###-###-####",
"(###) ###-####",
"1-###-###-####",
"###.###.####",
"###-###-####",
"(###) ###-####",
"1-###-###-####",
"###.###.####",
"###-###-#### x###",
"(###) ###-#### x###",
"1-###-###-#### x###",
"###.###.#### x###",
"###-###-#### x####",
"(###) ###-#### x####",
"1-###-###-#### x####",
"###.###.#### x####",
"###-###-#### x#####",
"(###) ###-#### x#####",
"1-###-###-#### x#####",
"###.###.#### x#####"
];
},{}],129:[function(require,module,exports){
var phone_number = {};
module['exports'] = phone_number;
phone_number.formats = require("./formats");
},{"./formats":128}],130:[function(require,module,exports){
var system = {};
module['exports'] = system;
system.mimeTypes = require("./mimeTypes");
},{"./mimeTypes":131}],131:[function(require,module,exports){
/*
The MIT License (MIT)
Copyright (c) 2014 Jonathan Ong me@jongleberry.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS 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.
Definitions from mime-db v1.21.0
For updates check: https://github.com/jshttp/mime-db/blob/master/db.json
*/
module['exports'] = {
"application/1d-interleaved-parityfec": {
"source": "iana"
},
"application/3gpdash-qoe-report+xml": {
"source": "iana"
},
"application/3gpp-ims+xml": {
"source": "iana"
},
"application/a2l": {
"source": "iana"
},
"application/activemessage": {
"source": "iana"
},
"application/alto-costmap+json": {
"source": "iana",
"compressible": true
},
"application/alto-costmapfilter+json": {
"source": "iana",
"compressible": true
},
"application/alto-directory+json": {
"source": "iana",
"compressible": true
},
"application/alto-endpointcost+json": {
"source": "iana",
"compressible": true
},
"application/alto-endpointcostparams+json": {
"source": "iana",
"compressible": true
},
"application/alto-endpointprop+json": {
"source": "iana",
"compressible": true
},
"application/alto-endpointpropparams+json": {
"source": "iana",
"compressible": true
},
"application/alto-error+json": {
"source": "iana",
"compressible": true
},
"application/alto-networkmap+json": {
"source": "iana",
"compressible": true
},
"application/alto-networkmapfilter+json": {
"source": "iana",
"compressible": true
},
"application/aml": {
"source": "iana"
},
"application/andrew-inset": {
"source": "iana",
"extensions": ["ez"]
},
"application/applefile": {
"source": "iana"
},
"application/applixware": {
"source": "apache",
"extensions": ["aw"]
},
"application/atf": {
"source": "iana"
},
"application/atfx": {
"source": "iana"
},
"application/atom+xml": {
"source": "iana",
"compressible": true,
"extensions": ["atom"]
},
"application/atomcat+xml": {
"source": "iana",
"extensions": ["atomcat"]
},
"application/atomdeleted+xml": {
"source": "iana"
},
"application/atomicmail": {
"source": "iana"
},
"application/atomsvc+xml": {
"source": "iana",
"extensions": ["atomsvc"]
},
"application/atxml": {
"source": "iana"
},
"application/auth-policy+xml": {
"source": "iana"
},
"application/bacnet-xdd+zip": {
"source": "iana"
},
"application/batch-smtp": {
"source": "iana"
},
"application/bdoc": {
"compressible": false,
"extensions": ["bdoc"]
},
"application/beep+xml": {
"source": "iana"
},
"application/calendar+json": {
"source": "iana",
"compressible": true
},
"application/calendar+xml": {
"source": "iana"
},
"application/call-completion": {
"source": "iana"
},
"application/cals-1840": {
"source": "iana"
},
"application/cbor": {
"source": "iana"
},
"application/ccmp+xml": {
"source": "iana"
},
"application/ccxml+xml": {
"source": "iana",
"extensions": ["ccxml"]
},
"application/cdfx+xml": {
"source": "iana"
},
"application/cdmi-capability": {
"source": "iana",
"extensions": ["cdmia"]
},
"application/cdmi-container": {
"source": "iana",
"extensions": ["cdmic"]
},
"application/cdmi-domain": {
"source": "iana",
"extensions": ["cdmid"]
},
"application/cdmi-object": {
"source": "iana",
"extensions": ["cdmio"]
},
"application/cdmi-queue": {
"source": "iana",
"extensions": ["cdmiq"]
},
"application/cdni": {
"source": "iana"
},
"application/cea": {
"source": "iana"
},
"application/cea-2018+xml": {
"source": "iana"
},
"application/cellml+xml": {
"source": "iana"
},
"application/cfw": {
"source": "iana"
},
"application/cms": {
"source": "iana"
},
"application/cnrp+xml": {
"source": "iana"
},
"application/coap-group+json": {
"source": "iana",
"compressible": true
},
"application/commonground": {
"source": "iana"
},
"application/conference-info+xml": {
"source": "iana"
},
"application/cpl+xml": {
"source": "iana"
},
"application/csrattrs": {
"source": "iana"
},
"application/csta+xml": {
"source": "iana"
},
"application/cstadata+xml": {
"source": "iana"
},
"application/csvm+json": {
"source": "iana",
"compressible": true
},
"application/cu-seeme": {
"source": "apache",
"extensions": ["cu"]
},
"application/cybercash": {
"source": "iana"
},
"application/dart": {
"compressible": true
},
"application/dash+xml": {
"source": "iana",
"extensions": ["mdp"]
},
"application/dashdelta": {
"source": "iana"
},
"application/davmount+xml": {
"source": "iana",
"extensions": ["davmount"]
},
"application/dca-rft": {
"source": "iana"
},
"application/dcd": {
"source": "iana"
},
"application/dec-dx": {
"source": "iana"
},
"application/dialog-info+xml": {
"source": "iana"
},
"application/dicom": {
"source": "iana"
},
"application/dii": {
"source": "iana"
},
"application/dit": {
"source": "iana"
},
"application/dns": {
"source": "iana"
},
"application/docbook+xml": {
"source": "apache",
"extensions": ["dbk"]
},
"application/dskpp+xml": {
"source": "iana"
},
"application/dssc+der": {
"source": "iana",
"extensions": ["dssc"]
},
"application/dssc+xml": {
"source": "iana",
"extensions": ["xdssc"]
},
"application/dvcs": {
"source": "iana"
},
"application/ecmascript": {
"source": "iana",
"compressible": true,
"extensions": ["ecma"]
},
"application/edi-consent": {
"source": "iana"
},
"application/edi-x12": {
"source": "iana",
"compressible": false
},
"application/edifact": {
"source": "iana",
"compressible": false
},
"application/emergencycalldata.comment+xml": {
"source": "iana"
},
"application/emergencycalldata.deviceinfo+xml": {
"source": "iana"
},
"application/emergencycalldata.providerinfo+xml": {
"source": "iana"
},
"application/emergencycalldata.serviceinfo+xml": {
"source": "iana"
},
"application/emergencycalldata.subscriberinfo+xml": {
"source": "iana"
},
"application/emma+xml": {
"source": "iana",
"extensions": ["emma"]
},
"application/emotionml+xml": {
"source": "iana"
},
"application/encaprtp": {
"source": "iana"
},
"application/epp+xml": {
"source": "iana"
},
"application/epub+zip": {
"source": "iana",
"extensions": ["epub"]
},
"application/eshop": {
"source": "iana"
},
"application/exi": {
"source": "iana",
"extensions": ["exi"]
},
"application/fastinfoset": {
"source": "iana"
},
"application/fastsoap": {
"source": "iana"
},
"application/fdt+xml": {
"source": "iana"
},
"application/fits": {
"source": "iana"
},
"application/font-sfnt": {
"source": "iana"
},
"application/font-tdpfr": {
"source": "iana",
"extensions": ["pfr"]
},
"application/font-woff": {
"source": "iana",
"compressible": false,
"extensions": ["woff"]
},
"application/font-woff2": {
"compressible": false,
"extensions": ["woff2"]
},
"application/framework-attributes+xml": {
"source": "iana"
},
"application/gml+xml": {
"source": "apache",
"extensions": ["gml"]
},
"application/gpx+xml": {
"source": "apache",
"extensions": ["gpx"]
},
"application/gxf": {
"source": "apache",
"extensions": ["gxf"]
},
"application/gzip": {
"source": "iana",
"compressible": false
},
"application/h224": {
"source": "iana"
},
"application/held+xml": {
"source": "iana"
},
"application/http": {
"source": "iana"
},
"application/hyperstudio": {
"source": "iana",
"extensions": ["stk"]
},
"application/ibe-key-request+xml": {
"source": "iana"
},
"application/ibe-pkg-reply+xml": {
"source": "iana"
},
"application/ibe-pp-data": {
"source": "iana"
},
"application/iges": {
"source": "iana"
},
"application/im-iscomposing+xml": {
"source": "iana"
},
"application/index": {
"source": "iana"
},
"application/index.cmd": {
"source": "iana"
},
"application/index.obj": {
"source": "iana"
},
"application/index.response": {
"source": "iana"
},
"application/index.vnd": {
"source": "iana"
},
"application/inkml+xml": {
"source": "iana",
"extensions": ["ink","inkml"]
},
"application/iotp": {
"source": "iana"
},
"application/ipfix": {
"source": "iana",
"extensions": ["ipfix"]
},
"application/ipp": {
"source": "iana"
},
"application/isup": {
"source": "iana"
},
"application/its+xml": {
"source": "iana"
},
"application/java-archive": {
"source": "apache",
"compressible": false,
"extensions": ["jar","war","ear"]
},
"application/java-serialized-object": {
"source": "apache",
"compressible": false,
"extensions": ["ser"]
},
"application/java-vm": {
"source": "apache",
"compressible": false,
"extensions": ["class"]
},
"application/javascript": {
"source": "iana",
"charset": "UTF-8",
"compressible": true,
"extensions": ["js"]
},
"application/jose": {
"source": "iana"
},
"application/jose+json": {
"source": "iana",
"compressible": true
},
"application/jrd+json": {
"source": "iana",
"compressible": true
},
"application/json": {
"source": "iana",
"charset": "UTF-8",
"compressible": true,
"extensions": ["json","map"]
},
"application/json-patch+json": {
"source": "iana",
"compressible": true
},
"application/json-seq": {
"source": "iana"
},
"application/json5": {
"extensions": ["json5"]
},
"application/jsonml+json": {
"source": "apache",
"compressible": true,
"extensions": ["jsonml"]
},
"application/jwk+json": {
"source": "iana",
"compressible": true
},
"application/jwk-set+json": {
"source": "iana",
"compressible": true
},
"application/jwt": {
"source": "iana"
},
"application/kpml-request+xml": {
"source": "iana"
},
"application/kpml-response+xml": {
"source": "iana"
},
"application/ld+json": {
"source": "iana",
"compressible": true,
"extensions": ["jsonld"]
},
"application/link-format": {
"source": "iana"
},
"application/load-control+xml": {
"source": "iana"
},
"application/lost+xml": {
"source": "iana",
"extensions": ["lostxml"]
},
"application/lostsync+xml": {
"source": "iana"
},
"application/lxf": {
"source": "iana"
},
"application/mac-binhex40": {
"source": "iana",
"extensions": ["hqx"]
},
"application/mac-compactpro": {
"source": "apache",
"extensions": ["cpt"]
},
"application/macwriteii": {
"source": "iana"
},
"application/mads+xml": {
"source": "iana",
"extensions": ["mads"]
},
"application/manifest+json": {
"charset": "UTF-8",
"compressible": true,
"extensions": ["webmanifest"]
},
"application/marc": {
"source": "iana",
"extensions": ["mrc"]
},
"application/marcxml+xml": {
"source": "iana",
"extensions": ["mrcx"]
},
"application/mathematica": {
"source": "iana",
"extensions": ["ma","nb","mb"]
},
"application/mathml+xml": {
"source": "iana",
"extensions": ["mathml"]
},
"application/mathml-content+xml": {
"source": "iana"
},
"application/mathml-presentation+xml": {
"source": "iana"
},
"application/mbms-associated-procedure-description+xml": {
"source": "iana"
},
"application/mbms-deregister+xml": {
"source": "iana"
},
"application/mbms-envelope+xml": {
"source": "iana"
},
"application/mbms-msk+xml": {
"source": "iana"
},
"application/mbms-msk-response+xml": {
"source": "iana"
},
"application/mbms-protection-description+xml": {
"source": "iana"
},
"application/mbms-reception-report+xml": {
"source": "iana"
},
"application/mbms-register+xml": {
"source": "iana"
},
"application/mbms-register-response+xml": {
"source": "iana"
},
"application/mbms-schedule+xml": {
"source": "iana"
},
"application/mbms-user-service-description+xml": {
"source": "iana"
},
"application/mbox": {
"source": "iana",
"extensions": ["mbox"]
},
"application/media-policy-dataset+xml": {
"source": "iana"
},
"application/media_control+xml": {
"source": "iana"
},
"application/mediaservercontrol+xml": {
"source": "iana",
"extensions": ["mscml"]
},
"application/merge-patch+json": {
"source": "iana",
"compressible": true
},
"application/metalink+xml": {
"source": "apache",
"extensions": ["metalink"]
},
"application/metalink4+xml": {
"source": "iana",
"extensions": ["meta4"]
},
"application/mets+xml": {
"source": "iana",
"extensions": ["mets"]
},
"application/mf4": {
"source": "iana"
},
"application/mikey": {
"source": "iana"
},
"application/mods+xml": {
"source": "iana",
"extensions": ["mods"]
},
"application/moss-keys": {
"source": "iana"
},
"application/moss-signature": {
"source": "iana"
},
"application/mosskey-data": {
"source": "iana"
},
"application/mosskey-request": {
"source": "iana"
},
"application/mp21": {
"source": "iana",
"extensions": ["m21","mp21"]
},
"application/mp4": {
"source": "iana",
"extensions": ["mp4s","m4p"]
},
"application/mpeg4-generic": {
"source": "iana"
},
"application/mpeg4-iod": {
"source": "iana"
},
"application/mpeg4-iod-xmt": {
"source": "iana"
},
"application/mrb-consumer+xml": {
"source": "iana"
},
"application/mrb-publish+xml": {
"source": "iana"
},
"application/msc-ivr+xml": {
"source": "iana"
},
"application/msc-mixer+xml": {
"source": "iana"
},
"application/msword": {
"source": "iana",
"compressible": false,
"extensions": ["doc","dot"]
},
"application/mxf": {
"source": "iana",
"extensions": ["mxf"]
},
"application/nasdata": {
"source": "iana"
},
"application/news-checkgroups": {
"source": "iana"
},
"application/news-groupinfo": {
"source": "iana"
},
"application/news-transmission": {
"source": "iana"
},
"application/nlsml+xml": {
"source": "iana"
},
"application/nss": {
"source": "iana"
},
"application/ocsp-request": {
"source": "iana"
},
"application/ocsp-response": {
"source": "iana"
},
"application/octet-stream": {
"source": "iana",
"compressible": false,
"extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]
},
"application/oda": {
"source": "iana",
"extensions": ["oda"]
},
"application/odx": {
"source": "iana"
},
"application/oebps-package+xml": {
"source": "iana",
"extensions": ["opf"]
},
"application/ogg": {
"source": "iana",
"compressible": false,
"extensions": ["ogx"]
},
"application/omdoc+xml": {
"source": "apache",
"extensions": ["omdoc"]
},
"application/onenote": {
"source": "apache",
"extensions": ["onetoc","onetoc2","onetmp","onepkg"]
},
"application/oxps": {
"source": "iana",
"extensions": ["oxps"]
},
"application/p2p-overlay+xml": {
"source": "iana"
},
"application/parityfec": {
"source": "iana"
},
"application/patch-ops-error+xml": {
"source": "iana",
"extensions": ["xer"]
},
"application/pdf": {
"source": "iana",
"compressible": false,
"extensions": ["pdf"]
},
"application/pdx": {
"source": "iana"
},
"application/pgp-encrypted": {
"source": "iana",
"compressible": false,
"extensions": ["pgp"]
},
"application/pgp-keys": {
"source": "iana"
},
"application/pgp-signature": {
"source": "iana",
"extensions": ["asc","sig"]
},
"application/pics-rules": {
"source": "apache",
"extensions": ["prf"]
},
"application/pidf+xml": {
"source": "iana"
},
"application/pidf-diff+xml": {
"source": "iana"
},
"application/pkcs10": {
"source": "iana",
"extensions": ["p10"]
},
"application/pkcs12": {
"source": "iana"
},
"application/pkcs7-mime": {
"source": "iana",
"extensions": ["p7m","p7c"]
},
"application/pkcs7-signature": {
"source": "iana",
"extensions": ["p7s"]
},
"application/pkcs8": {
"source": "iana",
"extensions": ["p8"]
},
"application/pkix-attr-cert": {
"source": "iana",
"extensions": ["ac"]
},
"application/pkix-cert": {
"source": "iana",
"extensions": ["cer"]
},
"application/pkix-crl": {
"source": "iana",
"extensions": ["crl"]
},
"application/pkix-pkipath": {
"source": "iana",
"extensions": ["pkipath"]
},
"application/pkixcmp": {
"source": "iana",
"extensions": ["pki"]
},
"application/pls+xml": {
"source": "iana",
"extensions": ["pls"]
},
"application/poc-settings+xml": {
"source": "iana"
},
"application/postscript": {
"source": "iana",
"compressible": true,
"extensions": ["ai","eps","ps"]
},
"application/provenance+xml": {
"source": "iana"
},
"application/prs.alvestrand.titrax-sheet": {
"source": "iana"
},
"application/prs.cww": {
"source": "iana",
"extensions": ["cww"]
},
"application/prs.hpub+zip": {
"source": "iana"
},
"application/prs.nprend": {
"source": "iana"
},
"application/prs.plucker": {
"source": "iana"
},
"application/prs.rdf-xml-crypt": {
"source": "iana"
},
"application/prs.xsf+xml": {
"source": "iana"
},
"application/pskc+xml": {
"source": "iana",
"extensions": ["pskcxml"]
},
"application/qsig": {
"source": "iana"
},
"application/raptorfec": {
"source": "iana"
},
"application/rdap+json": {
"source": "iana",
"compressible": true
},
"application/rdf+xml": {
"source": "iana",
"compressible": true,
"extensions": ["rdf"]
},
"application/reginfo+xml": {
"source": "iana",
"extensions": ["rif"]
},
"application/relax-ng-compact-syntax": {
"source": "iana",
"extensions": ["rnc"]
},
"application/remote-printing": {
"source": "iana"
},
"application/reputon+json": {
"source": "iana",
"compressible": true
},
"application/resource-lists+xml": {
"source": "iana",
"extensions": ["rl"]
},
"application/resource-lists-diff+xml": {
"source": "iana",
"extensions": ["rld"]
},
"application/rfc+xml": {
"source": "iana"
},
"application/riscos": {
"source": "iana"
},
"application/rlmi+xml": {
"source": "iana"
},
"application/rls-services+xml": {
"source": "iana",
"extensions": ["rs"]
},
"application/rpki-ghostbusters": {
"source": "iana",
"extensions": ["gbr"]
},
"application/rpki-manifest": {
"source": "iana",
"extensions": ["mft"]
},
"application/rpki-roa": {
"source": "iana",
"extensions": ["roa"]
},
"application/rpki-updown": {
"source": "iana"
},
"application/rsd+xml": {
"source": "apache",
"extensions": ["rsd"]
},
"application/rss+xml": {
"source": "apache",
"compressible": true,
"extensions": ["rss"]
},
"application/rtf": {
"source": "iana",
"compressible": true,
"extensions": ["rtf"]
},
"application/rtploopback": {
"source": "iana"
},
"application/rtx": {
"source": "iana"
},
"application/samlassertion+xml": {
"source": "iana"
},
"application/samlmetadata+xml": {
"source": "iana"
},
"application/sbml+xml": {
"source": "iana",
"extensions": ["sbml"]
},
"application/scaip+xml": {
"source": "iana"
},
"application/scim+json": {
"source": "iana",
"compressible": true
},
"application/scvp-cv-request": {
"source": "iana",
"extensions": ["scq"]
},
"application/scvp-cv-response": {
"source": "iana",
"extensions": ["scs"]
},
"application/scvp-vp-request": {
"source": "iana",
"extensions": ["spq"]
},
"application/scvp-vp-response": {
"source": "iana",
"extensions": ["spp"]
},
"application/sdp": {
"source": "iana",
"extensions": ["sdp"]
},
"application/sep+xml": {
"source": "iana"
},
"application/sep-exi": {
"source": "iana"
},
"application/session-info": {
"source": "iana"
},
"application/set-payment": {
"source": "iana"
},
"application/set-payment-initiation": {
"source": "iana",
"extensions": ["setpay"]
},
"application/set-registration": {
"source": "iana"
},
"application/set-registration-initiation": {
"source": "iana",
"extensions": ["setreg"]
},
"application/sgml": {
"source": "iana"
},
"application/sgml-open-catalog": {
"source": "iana"
},
"application/shf+xml": {
"source": "iana",
"extensions": ["shf"]
},
"application/sieve": {
"source": "iana"
},
"application/simple-filter+xml": {
"source": "iana"
},
"application/simple-message-summary": {
"source": "iana"
},
"application/simplesymbolcontainer": {
"source": "iana"
},
"application/slate": {
"source": "iana"
},
"application/smil": {
"source": "iana"
},
"application/smil+xml": {
"source": "iana",
"extensions": ["smi","smil"]
},
"application/smpte336m": {
"source": "iana"
},
"application/soap+fastinfoset": {
"source": "iana"
},
"application/soap+xml": {
"source": "iana",
"compressible": true
},
"application/sparql-query": {
"source": "iana",
"extensions": ["rq"]
},
"application/sparql-results+xml": {
"source": "iana",
"extensions": ["srx"]
},
"application/spirits-event+xml": {
"source": "iana"
},
"application/sql": {
"source": "iana"
},
"application/srgs": {
"source": "iana",
"extensions": ["gram"]
},
"application/srgs+xml": {
"source": "iana",
"extensions": ["grxml"]
},
"application/sru+xml": {
"source": "iana",
"extensions": ["sru"]
},
"application/ssdl+xml": {
"source": "apache",
"extensions": ["ssdl"]
},
"application/ssml+xml": {
"source": "iana",
"extensions": ["ssml"]
},
"application/tamp-apex-update": {
"source": "iana"
},
"application/tamp-apex-update-confirm": {
"source": "iana"
},
"application/tamp-community-update": {
"source": "iana"
},
"application/tamp-community-update-confirm": {
"source": "iana"
},
"application/tamp-error": {
"source": "iana"
},
"application/tamp-sequence-adjust": {
"source": "iana"
},
"application/tamp-sequence-adjust-confirm": {
"source": "iana"
},
"application/tamp-status-query": {
"source": "iana"
},
"application/tamp-status-response": {
"source": "iana"
},
"application/tamp-update": {
"source": "iana"
},
"application/tamp-update-confirm": {
"source": "iana"
},
"application/tar": {
"compressible": true
},
"application/tei+xml": {
"source": "iana",
"extensions": ["tei","teicorpus"]
},
"application/thraud+xml": {
"source": "iana",
"extensions": ["tfi"]
},
"application/timestamp-query": {
"source": "iana"
},
"application/timestamp-reply": {
"source": "iana"
},
"application/timestamped-data": {
"source": "iana",
"extensions": ["tsd"]
},
"application/ttml+xml": {
"source": "iana"
},
"application/tve-trigger": {
"source": "iana"
},
"application/ulpfec": {
"source": "iana"
},
"application/urc-grpsheet+xml": {
"source": "iana"
},
"application/urc-ressheet+xml": {
"source": "iana"
},
"application/urc-targetdesc+xml": {
"source": "iana"
},
"application/urc-uisocketdesc+xml": {
"source": "iana"
},
"application/vcard+json": {
"source": "iana",
"compressible": true
},
"application/vcard+xml": {
"source": "iana"
},
"application/vemmi": {
"source": "iana"
},
"application/vividence.scriptfile": {
"source": "apache"
},
"application/vnd.3gpp-prose+xml": {
"source": "iana"
},
"application/vnd.3gpp-prose-pc3ch+xml": {
"source": "iana"
},
"application/vnd.3gpp.access-transfer-events+xml": {
"source": "iana"
},
"application/vnd.3gpp.bsf+xml": {
"source": "iana"
},
"application/vnd.3gpp.mid-call+xml": {
"source": "iana"
},
"application/vnd.3gpp.pic-bw-large": {
"source": "iana",
"extensions": ["plb"]
},
"application/vnd.3gpp.pic-bw-small": {
"source": "iana",
"extensions": ["psb"]
},
"application/vnd.3gpp.pic-bw-var": {
"source": "iana",
"extensions": ["pvb"]
},
"application/vnd.3gpp.sms": {
"source": "iana"
},
"application/vnd.3gpp.srvcc-ext+xml": {
"source": "iana"
},
"application/vnd.3gpp.srvcc-info+xml": {
"source": "iana"
},
"application/vnd.3gpp.state-and-event-info+xml": {
"source": "iana"
},
"application/vnd.3gpp.ussd+xml": {
"source": "iana"
},
"application/vnd.3gpp2.bcmcsinfo+xml": {
"source": "iana"
},
"application/vnd.3gpp2.sms": {
"source": "iana"
},
"application/vnd.3gpp2.tcap": {
"source": "iana",
"extensions": ["tcap"]
},
"application/vnd.3m.post-it-notes": {
"source": "iana",
"extensions": ["pwn"]
},
"application/vnd.accpac.simply.aso": {
"source": "iana",
"extensions": ["aso"]
},
"application/vnd.accpac.simply.imp": {
"source": "iana",
"extensions": ["imp"]
},
"application/vnd.acucobol": {
"source": "iana",
"extensions": ["acu"]
},
"application/vnd.acucorp": {
"source": "iana",
"extensions": ["atc","acutc"]
},
"application/vnd.adobe.air-application-installer-package+zip": {
"source": "apache",
"extensions": ["air"]
},
"application/vnd.adobe.flash.movie": {
"source": "iana"
},
"application/vnd.adobe.formscentral.fcdt": {
"source": "iana",
"extensions": ["fcdt"]
},
"application/vnd.adobe.fxp": {
"source": "iana",
"extensions": ["fxp","fxpl"]
},
"application/vnd.adobe.partial-upload": {
"source": "iana"
},
"application/vnd.adobe.xdp+xml": {
"source": "iana",
"extensions": ["xdp"]
},
"application/vnd.adobe.xfdf": {
"source": "iana",
"extensions": ["xfdf"]
},
"application/vnd.aether.imp": {
"source": "iana"
},
"application/vnd.ah-barcode": {
"source": "iana"
},
"application/vnd.ahead.space": {
"source": "iana",
"extensions": ["ahead"]
},
"application/vnd.airzip.filesecure.azf": {
"source": "iana",
"extensions": ["azf"]
},
"application/vnd.airzip.filesecure.azs": {
"source": "iana",
"extensions": ["azs"]
},
"application/vnd.amazon.ebook": {
"source": "apache",
"extensions": ["azw"]
},
"application/vnd.americandynamics.acc": {
"source": "iana",
"extensions": ["acc"]
},
"application/vnd.amiga.ami": {
"source": "iana",
"extensions": ["ami"]
},
"application/vnd.amundsen.maze+xml": {
"source": "iana"
},
"application/vnd.android.package-archive": {
"source": "apache",
"compressible": false,
"extensions": ["apk"]
},
"application/vnd.anki": {
"source": "iana"
},
"application/vnd.anser-web-certificate-issue-initiation": {
"source": "iana",
"extensions": ["cii"]
},
"application/vnd.anser-web-funds-transfer-initiation": {
"source": "apache",
"extensions": ["fti"]
},
"application/vnd.antix.game-component": {
"source": "iana",
"extensions": ["atx"]
},
"application/vnd.apache.thrift.binary": {
"source": "iana"
},
"application/vnd.apache.thrift.compact": {
"source": "iana"
},
"application/vnd.apache.thrift.json": {
"source": "iana"
},
"application/vnd.api+json": {
"source": "iana",
"compressible": true
},
"application/vnd.apple.installer+xml": {
"source": "iana",
"extensions": ["mpkg"]
},
"application/vnd.apple.mpegurl": {
"source": "iana",
"extensions": ["m3u8"]
},
"application/vnd.apple.pkpass": {
"compressible": false,
"extensions": ["pkpass"]
},
"application/vnd.arastra.swi": {
"source": "iana"
},
"application/vnd.aristanetworks.swi": {
"source": "iana",
"extensions": ["swi"]
},
"application/vnd.artsquare": {
"source": "iana"
},
"application/vnd.astraea-software.iota": {
"source": "iana",
"extensions": ["iota"]
},
"application/vnd.audiograph": {
"source": "iana",
"extensions": ["aep"]
},
"application/vnd.autopackage": {
"source": "iana"
},
"application/vnd.avistar+xml": {
"source": "iana"
},
"application/vnd.balsamiq.bmml+xml": {
"source": "iana"
},
"application/vnd.balsamiq.bmpr": {
"source": "iana"
},
"application/vnd.bekitzur-stech+json": {
"source": "iana",
"compressible": true
},
"application/vnd.biopax.rdf+xml": {
"source": "iana"
},
"application/vnd.blueice.multipass": {
"source": "iana",
"extensions": ["mpm"]
},
"application/vnd.bluetooth.ep.oob": {
"source": "iana"
},
"application/vnd.bluetooth.le.oob": {
"source": "iana"
},
"application/vnd.bmi": {
"source": "iana",
"extensions": ["bmi"]
},
"application/vnd.businessobjects": {
"source": "iana",
"extensions": ["rep"]
},
"application/vnd.cab-jscript": {
"source": "iana"
},
"application/vnd.canon-cpdl": {
"source": "iana"
},
"application/vnd.canon-lips": {
"source": "iana"
},
"application/vnd.cendio.thinlinc.clientconf": {
"source": "iana"
},
"application/vnd.century-systems.tcp_stream": {
"source": "iana"
},
"application/vnd.chemdraw+xml": {
"source": "iana",
"extensions": ["cdxml"]
},
"application/vnd.chipnuts.karaoke-mmd": {
"source": "iana",
"extensions": ["mmd"]
},
"application/vnd.cinderella": {
"source": "iana",
"extensions": ["cdy"]
},
"application/vnd.cirpack.isdn-ext": {
"source": "iana"
},
"application/vnd.citationstyles.style+xml": {
"source": "iana"
},
"application/vnd.claymore": {
"source": "iana",
"extensions": ["cla"]
},
"application/vnd.cloanto.rp9": {
"source": "iana",
"extensions": ["rp9"]
},
"application/vnd.clonk.c4group": {
"source": "iana",
"extensions": ["c4g","c4d","c4f","c4p","c4u"]
},
"application/vnd.cluetrust.cartomobile-config": {
"source": "iana",
"extensions": ["c11amc"]
},
"application/vnd.cluetrust.cartomobile-config-pkg": {
"source": "iana",
"extensions": ["c11amz"]
},
"application/vnd.coffeescript": {
"source": "iana"
},
"application/vnd.collection+json": {
"source": "iana",
"compressible": true
},
"application/vnd.collection.doc+json": {
"source": "iana",
"compressible": true
},
"application/vnd.collection.next+json": {
"source": "iana",
"compressible": true
},
"application/vnd.commerce-battelle": {
"source": "iana"
},
"application/vnd.commonspace": {
"source": "iana",
"extensions": ["csp"]
},
"application/vnd.contact.cmsg": {
"source": "iana",
"extensions": ["cdbcmsg"]
},
"application/vnd.cosmocaller": {
"source": "iana",
"extensions": ["cmc"]
},
"application/vnd.crick.clicker": {
"source": "iana",
"extensions": ["clkx"]
},
"application/vnd.crick.clicker.keyboard": {
"source": "iana",
"extensions": ["clkk"]
},
"application/vnd.crick.clicker.palette": {
"source": "iana",
"extensions": ["clkp"]
},
"application/vnd.crick.clicker.template": {
"source": "iana",
"extensions": ["clkt"]
},
"application/vnd.crick.clicker.wordbank": {
"source": "iana",
"extensions": ["clkw"]
},
"application/vnd.criticaltools.wbs+xml": {
"source": "iana",
"extensions": ["wbs"]
},
"application/vnd.ctc-posml": {
"source": "iana",
"extensions": ["pml"]
},
"application/vnd.ctct.ws+xml": {
"source": "iana"
},
"application/vnd.cups-pdf": {
"source": "iana"
},
"application/vnd.cups-postscript": {
"source": "iana"
},
"application/vnd.cups-ppd": {
"source": "iana",
"extensions": ["ppd"]
},
"application/vnd.cups-raster": {
"source": "iana"
},
"application/vnd.cups-raw": {
"source": "iana"
},
"application/vnd.curl": {
"source": "iana"
},
"application/vnd.curl.car": {
"source": "apache",
"extensions": ["car"]
},
"application/vnd.curl.pcurl": {
"source": "apache",
"extensions": ["pcurl"]
},
"application/vnd.cyan.dean.root+xml": {
"source": "iana"
},
"application/vnd.cybank": {
"source": "iana"
},
"application/vnd.dart": {
"source": "iana",
"compressible": true,
"extensions": ["dart"]
},
"application/vnd.data-vision.rdz": {
"source": "iana",
"extensions": ["rdz"]
},
"application/vnd.debian.binary-package": {
"source": "iana"
},
"application/vnd.dece.data": {
"source": "iana",
"extensions": ["uvf","uvvf","uvd","uvvd"]
},
"application/vnd.dece.ttml+xml": {
"source": "iana",
"extensions": ["uvt","uvvt"]
},
"application/vnd.dece.unspecified": {
"source": "iana",
"extensions": ["uvx","uvvx"]
},
"application/vnd.dece.zip": {
"source": "iana",
"extensions": ["uvz","uvvz"]
},
"application/vnd.denovo.fcselayout-link": {
"source": "iana",
"extensions": ["fe_launch"]
},
"application/vnd.desmume-movie": {
"source": "iana"
},
"application/vnd.dir-bi.plate-dl-nosuffix": {
"source": "iana"
},
"application/vnd.dm.delegation+xml": {
"source": "iana"
},
"application/vnd.dna": {
"source": "iana",
"extensions": ["dna"]
},
"application/vnd.document+json": {
"source": "iana",
"compressible": true
},
"application/vnd.dolby.mlp": {
"source": "apache",
"extensions": ["mlp"]
},
"application/vnd.dolby.mobile.1": {
"source": "iana"
},
"application/vnd.dolby.mobile.2": {
"source": "iana"
},
"application/vnd.doremir.scorecloud-binary-document": {
"source": "iana"
},
"application/vnd.dpgraph": {
"source": "iana",
"extensions": ["dpg"]
},
"application/vnd.dreamfactory": {
"source": "iana",
"extensions": ["dfac"]
},
"application/vnd.drive+json": {
"source": "iana",
"compressible": true
},
"application/vnd.ds-keypoint": {
"source": "apache",
"extensions": ["kpxx"]
},
"application/vnd.dtg.local": {
"source": "iana"
},
"application/vnd.dtg.local.flash": {
"source": "iana"
},
"application/vnd.dtg.local.html": {
"source": "iana"
},
"application/vnd.dvb.ait": {
"source": "iana",
"extensions": ["ait"]
},
"application/vnd.dvb.dvbj": {
"source": "iana"
},
"application/vnd.dvb.esgcontainer": {
"source": "iana"
},
"application/vnd.dvb.ipdcdftnotifaccess": {
"source": "iana"
},
"application/vnd.dvb.ipdcesgaccess": {
"source": "iana"
},
"application/vnd.dvb.ipdcesgaccess2": {
"source": "iana"
},
"application/vnd.dvb.ipdcesgpdd": {
"source": "iana"
},
"application/vnd.dvb.ipdcroaming": {
"source": "iana"
},
"application/vnd.dvb.iptv.alfec-base": {
"source": "iana"
},
"application/vnd.dvb.iptv.alfec-enhancement": {
"source": "iana"
},
"application/vnd.dvb.notif-aggregate-root+xml": {
"source": "iana"
},
"application/vnd.dvb.notif-container+xml": {
"source": "iana"
},
"application/vnd.dvb.notif-generic+xml": {
"source": "iana"
},
"application/vnd.dvb.notif-ia-msglist+xml": {
"source": "iana"
},
"application/vnd.dvb.notif-ia-registration-request+xml": {
"source": "iana"
},
"application/vnd.dvb.notif-ia-registration-response+xml": {
"source": "iana"
},
"application/vnd.dvb.notif-init+xml": {
"source": "iana"
},
"application/vnd.dvb.pfr": {
"source": "iana"
},
"application/vnd.dvb.service": {
"source": "iana",
"extensions": ["svc"]
},
"application/vnd.dxr": {
"source": "iana"
},
"application/vnd.dynageo": {
"source": "iana",
"extensions": ["geo"]
},
"application/vnd.dzr": {
"source": "iana"
},
"application/vnd.easykaraoke.cdgdownload": {
"source": "iana"
},
"application/vnd.ecdis-update": {
"source": "iana"
},
"application/vnd.ecowin.chart": {
"source": "iana",
"extensions": ["mag"]
},
"application/vnd.ecowin.filerequest": {
"source": "iana"
},
"application/vnd.ecowin.fileupdate": {
"source": "iana"
},
"application/vnd.ecowin.series": {
"source": "iana"
},
"application/vnd.ecowin.seriesrequest": {
"source": "iana"
},
"application/vnd.ecowin.seriesupdate": {
"source": "iana"
},
"application/vnd.emclient.accessrequest+xml": {
"source": "iana"
},
"application/vnd.enliven": {
"source": "iana",
"extensions": ["nml"]
},
"application/vnd.enphase.envoy": {
"source": "iana"
},
"application/vnd.eprints.data+xml": {
"source": "iana"
},
"application/vnd.epson.esf": {
"source": "iana",
"extensions": ["esf"]
},
"application/vnd.epson.msf": {
"source": "iana",
"extensions": ["msf"]
},
"application/vnd.epson.quickanime": {
"source": "iana",
"extensions": ["qam"]
},
"application/vnd.epson.salt": {
"source": "iana",
"extensions": ["slt"]
},
"application/vnd.epson.ssf": {
"source": "iana",
"extensions": ["ssf"]
},
"application/vnd.ericsson.quickcall": {
"source": "iana"
},
"application/vnd.eszigno3+xml": {
"source": "iana",
"extensions": ["es3","et3"]
},
"application/vnd.etsi.aoc+xml": {
"source": "iana"
},
"application/vnd.etsi.asic-e+zip": {
"source": "iana"
},
"application/vnd.etsi.asic-s+zip": {
"source": "iana"
},
"application/vnd.etsi.cug+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvcommand+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvdiscovery+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvprofile+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvsad-bc+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvsad-cod+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvsad-npvr+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvservice+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvsync+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvueprofile+xml": {
"source": "iana"
},
"application/vnd.etsi.mcid+xml": {
"source": "iana"
},
"application/vnd.etsi.mheg5": {
"source": "iana"
},
"application/vnd.etsi.overload-control-policy-dataset+xml": {
"source": "iana"
},
"application/vnd.etsi.pstn+xml": {
"source": "iana"
},
"application/vnd.etsi.sci+xml": {
"source": "iana"
},
"application/vnd.etsi.simservs+xml": {
"source": "iana"
},
"application/vnd.etsi.timestamp-token": {
"source": "iana"
},
"application/vnd.etsi.tsl+xml": {
"source": "iana"
},
"application/vnd.etsi.tsl.der": {
"source": "iana"
},
"application/vnd.eudora.data": {
"source": "iana"
},
"application/vnd.ezpix-album": {
"source": "iana",
"extensions": ["ez2"]
},
"application/vnd.ezpix-package": {
"source": "iana",
"extensions": ["ez3"]
},
"application/vnd.f-secure.mobile": {
"source": "iana"
},
"application/vnd.fastcopy-disk-image": {
"source": "iana"
},
"application/vnd.fdf": {
"source": "iana",
"extensions": ["fdf"]
},
"application/vnd.fdsn.mseed": {
"source": "iana",
"extensions": ["mseed"]
},
"application/vnd.fdsn.seed": {
"source": "iana",
"extensions": ["seed","dataless"]
},
"application/vnd.ffsns": {
"source": "iana"
},
"application/vnd.filmit.zfc": {
"source": "iana"
},
"application/vnd.fints": {
"source": "iana"
},
"application/vnd.firemonkeys.cloudcell": {
"source": "iana"
},
"application/vnd.flographit": {
"source": "iana",
"extensions": ["gph"]
},
"application/vnd.fluxtime.clip": {
"source": "iana",
"extensions": ["ftc"]
},
"application/vnd.font-fontforge-sfd": {
"source": "iana"
},
"application/vnd.framemaker": {
"source": "iana",
"extensions": ["fm","frame","maker","book"]
},
"application/vnd.frogans.fnc": {
"source": "iana",
"extensions": ["fnc"]
},
"application/vnd.frogans.ltf": {
"source": "iana",
"extensions": ["ltf"]
},
"application/vnd.fsc.weblaunch": {
"source": "iana",
"extensions": ["fsc"]
},
"application/vnd.fujitsu.oasys": {
"source": "iana",
"extensions": ["oas"]
},
"application/vnd.fujitsu.oasys2": {
"source": "iana",
"extensions": ["oa2"]
},
"application/vnd.fujitsu.oasys3": {
"source": "iana",
"extensions": ["oa3"]
},
"application/vnd.fujitsu.oasysgp": {
"source": "iana",
"extensions": ["fg5"]
},
"application/vnd.fujitsu.oasysprs": {
"source": "iana",
"extensions": ["bh2"]
},
"application/vnd.fujixerox.art-ex": {
"source": "iana"
},
"application/vnd.fujixerox.art4": {
"source": "iana"
},
"application/vnd.fujixerox.ddd": {
"source": "iana",
"extensions": ["ddd"]
},
"application/vnd.fujixerox.docuworks": {
"source": "iana",
"extensions": ["xdw"]
},
"application/vnd.fujixerox.docuworks.binder": {
"source": "iana",
"extensions": ["xbd"]
},
"application/vnd.fujixerox.docuworks.container": {
"source": "iana"
},
"application/vnd.fujixerox.hbpl": {
"source": "iana"
},
"application/vnd.fut-misnet": {
"source": "iana"
},
"application/vnd.fuzzysheet": {
"source": "iana",
"extensions": ["fzs"]
},
"application/vnd.genomatix.tuxedo": {
"source": "iana",
"extensions": ["txd"]
},
"application/vnd.geo+json": {
"source": "iana",
"compressible": true
},
"application/vnd.geocube+xml": {
"source": "iana"
},
"application/vnd.geogebra.file": {
"source": "iana",
"extensions": ["ggb"]
},
"application/vnd.geogebra.tool": {
"source": "iana",
"extensions": ["ggt"]
},
"application/vnd.geometry-explorer": {
"source": "iana",
"extensions": ["gex","gre"]
},
"application/vnd.geonext": {
"source": "iana",
"extensions": ["gxt"]
},
"application/vnd.geoplan": {
"source": "iana",
"extensions": ["g2w"]
},
"application/vnd.geospace": {
"source": "iana",
"extensions": ["g3w"]
},
"application/vnd.gerber": {
"source": "iana"
},
"application/vnd.globalplatform.card-content-mgt": {
"source": "iana"
},
"application/vnd.globalplatform.card-content-mgt-response": {
"source": "iana"
},
"application/vnd.gmx": {
"source": "iana",
"extensions": ["gmx"]
},
"application/vnd.google-apps.document": {
"compressible": false,
"extensions": ["gdoc"]
},
"application/vnd.google-apps.presentation": {
"compressible": false,
"extensions": ["gslides"]
},
"application/vnd.google-apps.spreadsheet": {
"compressible": false,
"extensions": ["gsheet"]
},
"application/vnd.google-earth.kml+xml": {
"source": "iana",
"compressible": true,
"extensions": ["kml"]
},
"application/vnd.google-earth.kmz": {
"source": "iana",
"compressible": false,
"extensions": ["kmz"]
},
"application/vnd.gov.sk.e-form+xml": {
"source": "iana"
},
"application/vnd.gov.sk.e-form+zip": {
"source": "iana"
},
"application/vnd.gov.sk.xmldatacontainer+xml": {
"source": "iana"
},
"application/vnd.grafeq": {
"source": "iana",
"extensions": ["gqf","gqs"]
},
"application/vnd.gridmp": {
"source": "iana"
},
"application/vnd.groove-account": {
"source": "iana",
"extensions": ["gac"]
},
"application/vnd.groove-help": {
"source": "iana",
"extensions": ["ghf"]
},
"application/vnd.groove-identity-message": {
"source": "iana",
"extensions": ["gim"]
},
"application/vnd.groove-injector": {
"source": "iana",
"extensions": ["grv"]
},
"application/vnd.groove-tool-message": {
"source": "iana",
"extensions": ["gtm"]
},
"application/vnd.groove-tool-template": {
"source": "iana",
"extensions": ["tpl"]
},
"application/vnd.groove-vcard": {
"source": "iana",
"extensions": ["vcg"]
},
"application/vnd.hal+json": {
"source": "iana",
"compressible": true
},
"application/vnd.hal+xml": {
"source": "iana",
"extensions": ["hal"]
},
"application/vnd.handheld-entertainment+xml": {
"source": "iana",
"extensions": ["zmm"]
},
"application/vnd.hbci": {
"source": "iana",
"extensions": ["hbci"]
},
"application/vnd.hcl-bireports": {
"source": "iana"
},
"application/vnd.heroku+json": {
"source": "iana",
"compressible": true
},
"application/vnd.hhe.lesson-player": {
"source": "iana",
"extensions": ["les"]
},
"application/vnd.hp-hpgl": {
"source": "iana",
"extensions": ["hpgl"]
},
"application/vnd.hp-hpid": {
"source": "iana",
"extensions": ["hpid"]
},
"application/vnd.hp-hps": {
"source": "iana",
"extensions": ["hps"]
},
"application/vnd.hp-jlyt": {
"source": "iana",
"extensions": ["jlt"]
},
"application/vnd.hp-pcl": {
"source": "iana",
"extensions": ["pcl"]
},
"application/vnd.hp-pclxl": {
"source": "iana",
"extensions": ["pclxl"]
},
"application/vnd.httphone": {
"source": "iana"
},
"application/vnd.hydrostatix.sof-data": {
"source": "iana",
"extensions": ["sfd-hdstx"]
},
"application/vnd.hyperdrive+json": {
"source": "iana",
"compressible": true
},
"application/vnd.hzn-3d-crossword": {
"source": "iana"
},
"application/vnd.ibm.afplinedata": {
"source": "iana"
},
"application/vnd.ibm.electronic-media": {
"source": "iana"
},
"application/vnd.ibm.minipay": {
"source": "iana",
"extensions": ["mpy"]
},
"application/vnd.ibm.modcap": {
"source": "iana",
"extensions": ["afp","listafp","list3820"]
},
"application/vnd.ibm.rights-management": {
"source": "iana",
"extensions": ["irm"]
},
"application/vnd.ibm.secure-container": {
"source": "iana",
"extensions": ["sc"]
},
"application/vnd.iccprofile": {
"source": "iana",
"extensions": ["icc","icm"]
},
"application/vnd.ieee.1905": {
"source": "iana"
},
"application/vnd.igloader": {
"source": "iana",
"extensions": ["igl"]
},
"application/vnd.immervision-ivp": {
"source": "iana",
"extensions": ["ivp"]
},
"application/vnd.immervision-ivu": {
"source": "iana",
"extensions": ["ivu"]
},
"application/vnd.ims.imsccv1p1": {
"source": "iana"
},
"application/vnd.ims.imsccv1p2": {
"source": "iana"
},
"application/vnd.ims.imsccv1p3": {
"source": "iana"
},
"application/vnd.ims.lis.v2.result+json": {
"source": "iana",
"compressible": true
},
"application/vnd.ims.lti.v2.toolconsumerprofile+json": {
"source": "iana",
"compressible": true
},
"application/vnd.ims.lti.v2.toolproxy+json": {
"source": "iana",
"compressible": true
},
"application/vnd.ims.lti.v2.toolproxy.id+json": {
"source": "iana",
"compressible": true
},
"application/vnd.ims.lti.v2.toolsettings+json": {
"source": "iana",
"compressible": true
},
"application/vnd.ims.lti.v2.toolsettings.simple+json": {
"source": "iana",
"compressible": true
},
"application/vnd.informedcontrol.rms+xml": {
"source": "iana"
},
"application/vnd.informix-visionary": {
"source": "iana"
},
"application/vnd.infotech.project": {
"source": "iana"
},
"application/vnd.infotech.project+xml": {
"source": "iana"
},
"application/vnd.innopath.wamp.notification": {
"source": "iana"
},
"application/vnd.insors.igm": {
"source": "iana",
"extensions": ["igm"]
},
"application/vnd.intercon.formnet": {
"source": "iana",
"extensions": ["xpw","xpx"]
},
"application/vnd.intergeo": {
"source": "iana",
"extensions": ["i2g"]
},
"application/vnd.intertrust.digibox": {
"source": "iana"
},
"application/vnd.intertrust.nncp": {
"source": "iana"
},
"application/vnd.intu.qbo": {
"source": "iana",
"extensions": ["qbo"]
},
"application/vnd.intu.qfx": {
"source": "iana",
"extensions": ["qfx"]
},
"application/vnd.iptc.g2.catalogitem+xml": {
"source": "iana"
},
"application/vnd.iptc.g2.conceptitem+xml": {
"source": "iana"
},
"application/vnd.iptc.g2.knowledgeitem+xml": {
"source": "iana"
},
"application/vnd.iptc.g2.newsitem+xml": {
"source": "iana"
},
"application/vnd.iptc.g2.newsmessage+xml": {
"source": "iana"
},
"application/vnd.iptc.g2.packageitem+xml": {
"source": "iana"
},
"application/vnd.iptc.g2.planningitem+xml": {
"source": "iana"
},
"application/vnd.ipunplugged.rcprofile": {
"source": "iana",
"extensions": ["rcprofile"]
},
"application/vnd.irepository.package+xml": {
"source": "iana",
"extensions": ["irp"]
},
"application/vnd.is-xpr": {
"source": "iana",
"extensions": ["xpr"]
},
"application/vnd.isac.fcs": {
"source": "iana",
"extensions": ["fcs"]
},
"application/vnd.jam": {
"source": "iana",
"extensions": ["jam"]
},
"application/vnd.japannet-directory-service": {
"source": "iana"
},
"application/vnd.japannet-jpnstore-wakeup": {
"source": "iana"
},
"application/vnd.japannet-payment-wakeup": {
"source": "iana"
},
"application/vnd.japannet-registration": {
"source": "iana"
},
"application/vnd.japannet-registration-wakeup": {
"source": "iana"
},
"application/vnd.japannet-setstore-wakeup": {
"source": "iana"
},
"application/vnd.japannet-verification": {
"source": "iana"
},
"application/vnd.japannet-verification-wakeup": {
"source": "iana"
},
"application/vnd.jcp.javame.midlet-rms": {
"source": "iana",
"extensions": ["rms"]
},
"application/vnd.jisp": {
"source": "iana",
"extensions": ["jisp"]
},
"application/vnd.joost.joda-archive": {
"source": "iana",
"extensions": ["joda"]
},
"application/vnd.jsk.isdn-ngn": {
"source": "iana"
},
"application/vnd.kahootz": {
"source": "iana",
"extensions": ["ktz","ktr"]
},
"application/vnd.kde.karbon": {
"source": "iana",
"extensions": ["karbon"]
},
"application/vnd.kde.kchart": {
"source": "iana",
"extensions": ["chrt"]
},
"application/vnd.kde.kformula": {
"source": "iana",
"extensions": ["kfo"]
},
"application/vnd.kde.kivio": {
"source": "iana",
"extensions": ["flw"]
},
"application/vnd.kde.kontour": {
"source": "iana",
"extensions": ["kon"]
},
"application/vnd.kde.kpresenter": {
"source": "iana",
"extensions": ["kpr","kpt"]
},
"application/vnd.kde.kspread": {
"source": "iana",
"extensions": ["ksp"]
},
"application/vnd.kde.kword": {
"source": "iana",
"extensions": ["kwd","kwt"]
},
"application/vnd.kenameaapp": {
"source": "iana",
"extensions": ["htke"]
},
"application/vnd.kidspiration": {
"source": "iana",
"extensions": ["kia"]
},
"application/vnd.kinar": {
"source": "iana",
"extensions": ["kne","knp"]
},
"application/vnd.koan": {
"source": "iana",
"extensions": ["skp","skd","skt","skm"]
},
"application/vnd.kodak-descriptor": {
"source": "iana",
"extensions": ["sse"]
},
"application/vnd.las.las+xml": {
"source": "iana",
"extensions": ["lasxml"]
},
"application/vnd.liberty-request+xml": {
"source": "iana"
},
"application/vnd.llamagraphics.life-balance.desktop": {
"source": "iana",
"extensions": ["lbd"]
},
"application/vnd.llamagraphics.life-balance.exchange+xml": {
"source": "iana",
"extensions": ["lbe"]
},
"application/vnd.lotus-1-2-3": {
"source": "iana",
"extensions": ["123"]
},
"application/vnd.lotus-approach": {
"source": "iana",
"extensions": ["apr"]
},
"application/vnd.lotus-freelance": {
"source": "iana",
"extensions": ["pre"]
},
"application/vnd.lotus-notes": {
"source": "iana",
"extensions": ["nsf"]
},
"application/vnd.lotus-organizer": {
"source": "iana",
"extensions": ["org"]
},
"application/vnd.lotus-screencam": {
"source": "iana",
"extensions": ["scm"]
},
"application/vnd.lotus-wordpro": {
"source": "iana",
"extensions": ["lwp"]
},
"application/vnd.macports.portpkg": {
"source": "iana",
"extensions": ["portpkg"]
},
"application/vnd.mapbox-vector-tile": {
"source": "iana"
},
"application/vnd.marlin.drm.actiontoken+xml": {
"source": "iana"
},
"application/vnd.marlin.drm.conftoken+xml": {
"source": "iana"
},
"application/vnd.marlin.drm.license+xml": {
"source": "iana"
},
"application/vnd.marlin.drm.mdcf": {
"source": "iana"
},
"application/vnd.mason+json": {
"source": "iana",
"compressible": true
},
"application/vnd.maxmind.maxmind-db": {
"source": "iana"
},
"application/vnd.mcd": {
"source": "iana",
"extensions": ["mcd"]
},
"application/vnd.medcalcdata": {
"source": "iana",
"extensions": ["mc1"]
},
"application/vnd.mediastation.cdkey": {
"source": "iana",
"extensions": ["cdkey"]
},
"application/vnd.meridian-slingshot": {
"source": "iana"
},
"application/vnd.mfer": {
"source": "iana",
"extensions": ["mwf"]
},
"application/vnd.mfmp": {
"source": "iana",
"extensions": ["mfm"]
},
"application/vnd.micro+json": {
"source": "iana",
"compressible": true
},
"application/vnd.micrografx.flo": {
"source": "iana",
"extensions": ["flo"]
},
"application/vnd.micrografx.igx": {
"source": "iana",
"extensions": ["igx"]
},
"application/vnd.microsoft.portable-executable": {
"source": "iana"
},
"application/vnd.miele+json": {
"source": "iana",
"compressible": true
},
"application/vnd.mif": {
"source": "iana",
"extensions": ["mif"]
},
"application/vnd.minisoft-hp3000-save": {
"source": "iana"
},
"application/vnd.mitsubishi.misty-guard.trustweb": {
"source": "iana"
},
"application/vnd.mobius.daf": {
"source": "iana",
"extensions": ["daf"]
},
"application/vnd.mobius.dis": {
"source": "iana",
"extensions": ["dis"]
},
"application/vnd.mobius.mbk": {
"source": "iana",
"extensions": ["mbk"]
},
"application/vnd.mobius.mqy": {
"source": "iana",
"extensions": ["mqy"]
},
"application/vnd.mobius.msl": {
"source": "iana",
"extensions": ["msl"]
},
"application/vnd.mobius.plc": {
"source": "iana",
"extensions": ["plc"]
},
"application/vnd.mobius.txf": {
"source": "iana",
"extensions": ["txf"]
},
"application/vnd.mophun.application": {
"source": "iana",
"extensions": ["mpn"]
},
"application/vnd.mophun.certificate": {
"source": "iana",
"extensions": ["mpc"]
},
"application/vnd.motorola.flexsuite": {
"source": "iana"
},
"application/vnd.motorola.flexsuite.adsi": {
"source": "iana"
},
"application/vnd.motorola.flexsuite.fis": {
"source": "iana"
},
"application/vnd.motorola.flexsuite.gotap": {
"source": "iana"
},
"application/vnd.motorola.flexsuite.kmr": {
"source": "iana"
},
"application/vnd.motorola.flexsuite.ttc": {
"source": "iana"
},
"application/vnd.motorola.flexsuite.wem": {
"source": "iana"
},
"application/vnd.motorola.iprm": {
"source": "iana"
},
"application/vnd.mozilla.xul+xml": {
"source": "iana",
"compressible": true,
"extensions": ["xul"]
},
"application/vnd.ms-3mfdocument": {
"source": "iana"
},
"application/vnd.ms-artgalry": {
"source": "iana",
"extensions": ["cil"]
},
"application/vnd.ms-asf": {
"source": "iana"
},
"application/vnd.ms-cab-compressed": {
"source": "iana",
"extensions": ["cab"]
},
"application/vnd.ms-color.iccprofile": {
"source": "apache"
},
"application/vnd.ms-excel": {
"source": "iana",
"compressible": false,
"extensions": ["xls","xlm","xla","xlc","xlt","xlw"]
},
"application/vnd.ms-excel.addin.macroenabled.12": {
"source": "iana",
"extensions": ["xlam"]
},
"application/vnd.ms-excel.sheet.binary.macroenabled.12": {
"source": "iana",
"extensions": ["xlsb"]
},
"application/vnd.ms-excel.sheet.macroenabled.12": {
"source": "iana",
"extensions": ["xlsm"]
},
"application/vnd.ms-excel.template.macroenabled.12": {
"source": "iana",
"extensions": ["xltm"]
},
"application/vnd.ms-fontobject": {
"source": "iana",
"compressible": true,
"extensions": ["eot"]
},
"application/vnd.ms-htmlhelp": {
"source": "iana",
"extensions": ["chm"]
},
"application/vnd.ms-ims": {
"source": "iana",
"extensions": ["ims"]
},
"application/vnd.ms-lrm": {
"source": "iana",
"extensions": ["lrm"]
},
"application/vnd.ms-office.activex+xml": {
"source": "iana"
},
"application/vnd.ms-officetheme": {
"source": "iana",
"extensions": ["thmx"]
},
"application/vnd.ms-opentype": {
"source": "apache",
"compressible": true
},
"application/vnd.ms-package.obfuscated-opentype": {
"source": "apache"
},
"application/vnd.ms-pki.seccat": {
"source": "apache",
"extensions": ["cat"]
},
"application/vnd.ms-pki.stl": {
"source": "apache",
"extensions": ["stl"]
},
"application/vnd.ms-playready.initiator+xml": {
"source": "iana"
},
"application/vnd.ms-powerpoint": {
"source": "iana",
"compressible": false,
"extensions": ["ppt","pps","pot"]
},
"application/vnd.ms-powerpoint.addin.macroenabled.12": {
"source": "iana",
"extensions": ["ppam"]
},
"application/vnd.ms-powerpoint.presentation.macroenabled.12": {
"source": "iana",
"extensions": ["pptm"]
},
"application/vnd.ms-powerpoint.slide.macroenabled.12": {
"source": "iana",
"extensions": ["sldm"]
},
"application/vnd.ms-powerpoint.slideshow.macroenabled.12": {
"source": "iana",
"extensions": ["ppsm"]
},
"application/vnd.ms-powerpoint.template.macroenabled.12": {
"source": "iana",
"extensions": ["potm"]
},
"application/vnd.ms-printdevicecapabilities+xml": {
"source": "iana"
},
"application/vnd.ms-printing.printticket+xml": {
"source": "apache"
},
"application/vnd.ms-project": {
"source": "iana",
"extensions": ["mpp","mpt"]
},
"application/vnd.ms-tnef": {
"source": "iana"
},
"application/vnd.ms-windows.devicepairing": {
"source": "iana"
},
"application/vnd.ms-windows.nwprinting.oob": {
"source": "iana"
},
"application/vnd.ms-windows.printerpairing": {
"source": "iana"
},
"application/vnd.ms-windows.wsd.oob": {
"source": "iana"
},
"application/vnd.ms-wmdrm.lic-chlg-req": {
"source": "iana"
},
"application/vnd.ms-wmdrm.lic-resp": {
"source": "iana"
},
"application/vnd.ms-wmdrm.meter-chlg-req": {
"source": "iana"
},
"application/vnd.ms-wmdrm.meter-resp": {
"source": "iana"
},
"application/vnd.ms-word.document.macroenabled.12": {
"source": "iana",
"extensions": ["docm"]
},
"application/vnd.ms-word.template.macroenabled.12": {
"source": "iana",
"extensions": ["dotm"]
},
"application/vnd.ms-works": {
"source": "iana",
"extensions": ["wps","wks","wcm","wdb"]
},
"application/vnd.ms-wpl": {
"source": "iana",
"extensions": ["wpl"]
},
"application/vnd.ms-xpsdocument": {
"source": "iana",
"compressible": false,
"extensions": ["xps"]
},
"application/vnd.msa-disk-image": {
"source": "iana"
},
"application/vnd.mseq": {
"source": "iana",
"extensions": ["mseq"]
},
"application/vnd.msign": {
"source": "iana"
},
"application/vnd.multiad.creator": {
"source": "iana"
},
"application/vnd.multiad.creator.cif": {
"source": "iana"
},
"application/vnd.music-niff": {
"source": "iana"
},
"application/vnd.musician": {
"source": "iana",
"extensions": ["mus"]
},
"application/vnd.muvee.style": {
"source": "iana",
"extensions": ["msty"]
},
"application/vnd.mynfc": {
"source": "iana",
"extensions": ["taglet"]
},
"application/vnd.ncd.control": {
"source": "iana"
},
"application/vnd.ncd.reference": {
"source": "iana"
},
"application/vnd.nervana": {
"source": "iana"
},
"application/vnd.netfpx": {
"source": "iana"
},
"application/vnd.neurolanguage.nlu": {
"source": "iana",
"extensions": ["nlu"]
},
"application/vnd.nintendo.nitro.rom": {
"source": "iana"
},
"application/vnd.nintendo.snes.rom": {
"source": "iana"
},
"application/vnd.nitf": {
"source": "iana",
"extensions": ["ntf","nitf"]
},
"application/vnd.noblenet-directory": {
"source": "iana",
"extensions": ["nnd"]
},
"application/vnd.noblenet-sealer": {
"source": "iana",
"extensions": ["nns"]
},
"application/vnd.noblenet-web": {
"source": "iana",
"extensions": ["nnw"]
},
"application/vnd.nokia.catalogs": {
"source": "iana"
},
"application/vnd.nokia.conml+wbxml": {
"source": "iana"
},
"application/vnd.nokia.conml+xml": {
"source": "iana"
},
"application/vnd.nokia.iptv.config+xml": {
"source": "iana"
},
"application/vnd.nokia.isds-radio-presets": {
"source": "iana"
},
"application/vnd.nokia.landmark+wbxml": {
"source": "iana"
},
"application/vnd.nokia.landmark+xml": {
"source": "iana"
},
"application/vnd.nokia.landmarkcollection+xml": {
"source": "iana"
},
"application/vnd.nokia.n-gage.ac+xml": {
"source": "iana"
},
"application/vnd.nokia.n-gage.data": {
"source": "iana",
"extensions": ["ngdat"]
},
"application/vnd.nokia.n-gage.symbian.install": {
"source": "iana",
"extensions": ["n-gage"]
},
"application/vnd.nokia.ncd": {
"source": "iana"
},
"application/vnd.nokia.pcd+wbxml": {
"source": "iana"
},
"application/vnd.nokia.pcd+xml": {
"source": "iana"
},
"application/vnd.nokia.radio-preset": {
"source": "iana",
"extensions": ["rpst"]
},
"application/vnd.nokia.radio-presets": {
"source": "iana",
"extensions": ["rpss"]
},
"application/vnd.novadigm.edm": {
"source": "iana",
"extensions": ["edm"]
},
"application/vnd.novadigm.edx": {
"source": "iana",
"extensions": ["edx"]
},
"application/vnd.novadigm.ext": {
"source": "iana",
"extensions": ["ext"]
},
"application/vnd.ntt-local.content-share": {
"source": "iana"
},
"application/vnd.ntt-local.file-transfer": {
"source": "iana"
},
"application/vnd.ntt-local.ogw_remote-access": {
"source": "iana"
},
"application/vnd.ntt-local.sip-ta_remote": {
"source": "iana"
},
"application/vnd.ntt-local.sip-ta_tcp_stream": {
"source": "iana"
},
"application/vnd.oasis.opendocument.chart": {
"source": "iana",
"extensions": ["odc"]
},
"application/vnd.oasis.opendocument.chart-template": {
"source": "iana",
"extensions": ["otc"]
},
"application/vnd.oasis.opendocument.database": {
"source": "iana",
"extensions": ["odb"]
},
"application/vnd.oasis.opendocument.formula": {
"source": "iana",
"extensions": ["odf"]
},
"application/vnd.oasis.opendocument.formula-template": {
"source": "iana",
"extensions": ["odft"]
},
"application/vnd.oasis.opendocument.graphics": {
"source": "iana",
"compressible": false,
"extensions": ["odg"]
},
"application/vnd.oasis.opendocument.graphics-template": {
"source": "iana",
"extensions": ["otg"]
},
"application/vnd.oasis.opendocument.image": {
"source": "iana",
"extensions": ["odi"]
},
"application/vnd.oasis.opendocument.image-template": {
"source": "iana",
"extensions": ["oti"]
},
"application/vnd.oasis.opendocument.presentation": {
"source": "iana",
"compressible": false,
"extensions": ["odp"]
},
"application/vnd.oasis.opendocument.presentation-template": {
"source": "iana",
"extensions": ["otp"]
},
"application/vnd.oasis.opendocument.spreadsheet": {
"source": "iana",
"compressible": false,
"extensions": ["ods"]
},
"application/vnd.oasis.opendocument.spreadsheet-template": {
"source": "iana",
"extensions": ["ots"]
},
"application/vnd.oasis.opendocument.text": {
"source": "iana",
"compressible": false,
"extensions": ["odt"]
},
"application/vnd.oasis.opendocument.text-master": {
"source": "iana",
"extensions": ["odm"]
},
"application/vnd.oasis.opendocument.text-template": {
"source": "iana",
"extensions": ["ott"]
},
"application/vnd.oasis.opendocument.text-web": {
"source": "iana",
"extensions": ["oth"]
},
"application/vnd.obn": {
"source": "iana"
},
"application/vnd.oftn.l10n+json": {
"source": "iana",
"compressible": true
},
"application/vnd.oipf.contentaccessdownload+xml": {
"source": "iana"
},
"application/vnd.oipf.contentaccessstreaming+xml": {
"source": "iana"
},
"application/vnd.oipf.cspg-hexbinary": {
"source": "iana"
},
"application/vnd.oipf.dae.svg+xml": {
"source": "iana"
},
"application/vnd.oipf.dae.xhtml+xml": {
"source": "iana"
},
"application/vnd.oipf.mippvcontrolmessage+xml": {
"source": "iana"
},
"application/vnd.oipf.pae.gem": {
"source": "iana"
},
"application/vnd.oipf.spdiscovery+xml": {
"source": "iana"
},
"application/vnd.oipf.spdlist+xml": {
"source": "iana"
},
"application/vnd.oipf.ueprofile+xml": {
"source": "iana"
},
"application/vnd.oipf.userprofile+xml": {
"source": "iana"
},
"application/vnd.olpc-sugar": {
"source": "iana",
"extensions": ["xo"]
},
"application/vnd.oma-scws-config": {
"source": "iana"
},
"application/vnd.oma-scws-http-request": {
"source": "iana"
},
"application/vnd.oma-scws-http-response": {
"source": "iana"
},
"application/vnd.oma.bcast.associated-procedure-parameter+xml": {
"source": "iana"
},
"application/vnd.oma.bcast.drm-trigger+xml": {
"source": "iana"
},
"application/vnd.oma.bcast.imd+xml": {
"source": "iana"
},
"application/vnd.oma.bcast.ltkm": {
"source": "iana"
},
"application/vnd.oma.bcast.notification+xml": {
"source": "iana"
},
"application/vnd.oma.bcast.provisioningtrigger": {
"source": "iana"
},
"application/vnd.oma.bcast.sgboot": {
"source": "iana"
},
"application/vnd.oma.bcast.sgdd+xml": {
"source": "iana"
},
"application/vnd.oma.bcast.sgdu": {
"source": "iana"
},
"application/vnd.oma.bcast.simple-symbol-container": {
"source": "iana"
},
"application/vnd.oma.bcast.smartcard-trigger+xml": {
"source": "iana"
},
"application/vnd.oma.bcast.sprov+xml": {
"source": "iana"
},
"application/vnd.oma.bcast.stkm": {
"source": "iana"
},
"application/vnd.oma.cab-address-book+xml": {
"source": "iana"
},
"application/vnd.oma.cab-feature-handler+xml": {
"source": "iana"
},
"application/vnd.oma.cab-pcc+xml": {
"source": "iana"
},
"application/vnd.oma.cab-subs-invite+xml": {
"source": "iana"
},
"application/vnd.oma.cab-user-prefs+xml": {
"source": "iana"
},
"application/vnd.oma.dcd": {
"source": "iana"
},
"application/vnd.oma.dcdc": {
"source": "iana"
},
"application/vnd.oma.dd2+xml": {
"source": "iana",
"extensions": ["dd2"]
},
"application/vnd.oma.drm.risd+xml": {
"source": "iana"
},
"application/vnd.oma.group-usage-list+xml": {
"source": "iana"
},
"application/vnd.oma.pal+xml": {
"source": "iana"
},
"application/vnd.oma.poc.detailed-progress-report+xml": {
"source": "iana"
},
"application/vnd.oma.poc.final-report+xml": {
"source": "iana"
},
"application/vnd.oma.poc.groups+xml": {
"source": "iana"
},
"application/vnd.oma.poc.invocation-descriptor+xml": {
"source": "iana"
},
"application/vnd.oma.poc.optimized-progress-report+xml": {
"source": "iana"
},
"application/vnd.oma.push": {
"source": "iana"
},
"application/vnd.oma.scidm.messages+xml": {
"source": "iana"
},
"application/vnd.oma.xcap-directory+xml": {
"source": "iana"
},
"application/vnd.omads-email+xml": {
"source": "iana"
},
"application/vnd.omads-file+xml": {
"source": "iana"
},
"application/vnd.omads-folder+xml": {
"source": "iana"
},
"application/vnd.omaloc-supl-init": {
"source": "iana"
},
"application/vnd.openblox.game+xml": {
"source": "iana"
},
"application/vnd.openblox.game-binary": {
"source": "iana"
},
"application/vnd.openeye.oeb": {
"source": "iana"
},
"application/vnd.openofficeorg.extension": {
"source": "apache",
"extensions": ["oxt"]
},
"application/vnd.openxmlformats-officedocument.custom-properties+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.customxmlproperties+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.drawing+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.drawingml.chart+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.extended-properties+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml-template": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.comments+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.presentation": {
"source": "iana",
"compressible": false,
"extensions": ["pptx"]
},
"application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.slide": {
"source": "iana",
"extensions": ["sldx"]
},
"application/vnd.openxmlformats-officedocument.presentationml.slide+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.slideshow": {
"source": "iana",
"extensions": ["ppsx"]
},
"application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.tags+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.template": {
"source": "apache",
"extensions": ["potx"]
},
"application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml-template": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
"source": "iana",
"compressible": false,
"extensions": ["xlsx"]
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.template": {
"source": "apache",
"extensions": ["xltx"]
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.theme+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.themeoverride+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.vmldrawing": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml-template": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": {
"source": "iana",
"compressible": false,
"extensions": ["docx"]
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.template": {
"source": "apache",
"extensions": ["dotx"]
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-package.core-properties+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-package.relationships+xml": {
"source": "iana"
},
"application/vnd.oracle.resource+json": {
"source": "iana",
"compressible": true
},
"application/vnd.orange.indata": {
"source": "iana"
},
"application/vnd.osa.netdeploy": {
"source": "iana"
},
"application/vnd.osgeo.mapguide.package": {
"source": "iana",
"extensions": ["mgp"]
},
"application/vnd.osgi.bundle": {
"source": "iana"
},
"application/vnd.osgi.dp": {
"source": "iana",
"extensions": ["dp"]
},
"application/vnd.osgi.subsystem": {
"source": "iana",
"extensions": ["esa"]
},
"application/vnd.otps.ct-kip+xml": {
"source": "iana"
},
"application/vnd.oxli.countgraph": {
"source": "iana"
},
"application/vnd.pagerduty+json": {
"source": "iana",
"compressible": true
},
"application/vnd.palm": {
"source": "iana",
"extensions": ["pdb","pqa","oprc"]
},
"application/vnd.panoply": {
"source": "iana"
},
"application/vnd.paos+xml": {
"source": "iana"
},
"application/vnd.paos.xml": {
"source": "apache"
},
"application/vnd.pawaafile": {
"source": "iana",
"extensions": ["paw"]
},
"application/vnd.pcos": {
"source": "iana"
},
"application/vnd.pg.format": {
"source": "iana",
"extensions": ["str"]
},
"application/vnd.pg.osasli": {
"source": "iana",
"extensions": ["ei6"]
},
"application/vnd.piaccess.application-licence": {
"source": "iana"
},
"application/vnd.picsel": {
"source": "iana",
"extensions": ["efif"]
},
"application/vnd.pmi.widget": {
"source": "iana",
"extensions": ["wg"]
},
"application/vnd.poc.group-advertisement+xml": {
"source": "iana"
},
"application/vnd.pocketlearn": {
"source": "iana",
"extensions": ["plf"]
},
"application/vnd.powerbuilder6": {
"source": "iana",
"extensions": ["pbd"]
},
"application/vnd.powerbuilder6-s": {
"source": "iana"
},
"application/vnd.powerbuilder7": {
"source": "iana"
},
"application/vnd.powerbuilder7-s": {
"source": "iana"
},
"application/vnd.powerbuilder75": {
"source": "iana"
},
"application/vnd.powerbuilder75-s": {
"source": "iana"
},
"application/vnd.preminet": {
"source": "iana"
},
"application/vnd.previewsystems.box": {
"source": "iana",
"extensions": ["box"]
},
"application/vnd.proteus.magazine": {
"source": "iana",
"extensions": ["mgz"]
},
"application/vnd.publishare-delta-tree": {
"source": "iana",
"extensions": ["qps"]
},
"application/vnd.pvi.ptid1": {
"source": "iana",
"extensions": ["ptid"]
},
"application/vnd.pwg-multiplexed": {
"source": "iana"
},
"application/vnd.pwg-xhtml-print+xml": {
"source": "iana"
},
"application/vnd.qualcomm.brew-app-res": {
"source": "iana"
},
"application/vnd.quark.quarkxpress": {
"source": "iana",
"extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"]
},
"application/vnd.quobject-quoxdocument": {
"source": "iana"
},
"application/vnd.radisys.moml+xml": {
"source": "iana"
},
"application/vnd.radisys.msml+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-audit+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-audit-conf+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-audit-conn+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-audit-dialog+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-audit-stream+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-conf+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-dialog+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-dialog-base+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-dialog-fax-detect+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-dialog-fax-sendrecv+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-dialog-group+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-dialog-speech+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-dialog-transform+xml": {
"source": "iana"
},
"application/vnd.rainstor.data": {
"source": "iana"
},
"application/vnd.rapid": {
"source": "iana"
},
"application/vnd.realvnc.bed": {
"source": "iana",
"extensions": ["bed"]
},
"application/vnd.recordare.musicxml": {
"source": "iana",
"extensions": ["mxl"]
},
"application/vnd.recordare.musicxml+xml": {
"source": "iana",
"extensions": ["musicxml"]
},
"application/vnd.renlearn.rlprint": {
"source": "iana"
},
"application/vnd.rig.cryptonote": {
"source": "iana",
"extensions": ["cryptonote"]
},
"application/vnd.rim.cod": {
"source": "apache",
"extensions": ["cod"]
},
"application/vnd.rn-realmedia": {
"source": "apache",
"extensions": ["rm"]
},
"application/vnd.rn-realmedia-vbr": {
"source": "apache",
"extensions": ["rmvb"]
},
"application/vnd.route66.link66+xml": {
"source": "iana",
"extensions": ["link66"]
},
"application/vnd.rs-274x": {
"source": "iana"
},
"application/vnd.ruckus.download": {
"source": "iana"
},
"application/vnd.s3sms": {
"source": "iana"
},
"application/vnd.sailingtracker.track": {
"source": "iana",
"extensions": ["st"]
},
"application/vnd.sbm.cid": {
"source": "iana"
},
"application/vnd.sbm.mid2": {
"source": "iana"
},
"application/vnd.scribus": {
"source": "iana"
},
"application/vnd.sealed.3df": {
"source": "iana"
},
"application/vnd.sealed.csf": {
"source": "iana"
},
"application/vnd.sealed.doc": {
"source": "iana"
},
"application/vnd.sealed.eml": {
"source": "iana"
},
"application/vnd.sealed.mht": {
"source": "iana"
},
"application/vnd.sealed.net": {
"source": "iana"
},
"application/vnd.sealed.ppt": {
"source": "iana"
},
"application/vnd.sealed.tiff": {
"source": "iana"
},
"application/vnd.sealed.xls": {
"source": "iana"
},
"application/vnd.sealedmedia.softseal.html": {
"source": "iana"
},
"application/vnd.sealedmedia.softseal.pdf": {
"source": "iana"
},
"application/vnd.seemail": {
"source": "iana",
"extensions": ["see"]
},
"application/vnd.sema": {
"source": "iana",
"extensions": ["sema"]
},
"application/vnd.semd": {
"source": "iana",
"extensions": ["semd"]
},
"application/vnd.semf": {
"source": "iana",
"extensions": ["semf"]
},
"application/vnd.shana.informed.formdata": {
"source": "iana",
"extensions": ["ifm"]
},
"application/vnd.shana.informed.formtemplate": {
"source": "iana",
"extensions": ["itp"]
},
"application/vnd.shana.informed.interchange": {
"source": "iana",
"extensions": ["iif"]
},
"application/vnd.shana.informed.package": {
"source": "iana",
"extensions": ["ipk"]
},
"application/vnd.simtech-mindmapper": {
"source": "iana",
"extensions": ["twd","twds"]
},
"application/vnd.siren+json": {
"source": "iana",
"compressible": true
},
"application/vnd.smaf": {
"source": "iana",
"extensions": ["mmf"]
},
"application/vnd.smart.notebook": {
"source": "iana"
},
"application/vnd.smart.teacher": {
"source": "iana",
"extensions": ["teacher"]
},
"application/vnd.software602.filler.form+xml": {
"source": "iana"
},
"application/vnd.software602.filler.form-xml-zip": {
"source": "iana"
},
"application/vnd.solent.sdkm+xml": {
"source": "iana",
"extensions": ["sdkm","sdkd"]
},
"application/vnd.spotfire.dxp": {
"source": "iana",
"extensions": ["dxp"]
},
"application/vnd.spotfire.sfs": {
"source": "iana",
"extensions": ["sfs"]
},
"application/vnd.sss-cod": {
"source": "iana"
},
"application/vnd.sss-dtf": {
"source": "iana"
},
"application/vnd.sss-ntf": {
"source": "iana"
},
"application/vnd.stardivision.calc": {
"source": "apache",
"extensions": ["sdc"]
},
"application/vnd.stardivision.draw": {
"source": "apache",
"extensions": ["sda"]
},
"application/vnd.stardivision.impress": {
"source": "apache",
"extensions": ["sdd"]
},
"application/vnd.stardivision.math": {
"source": "apache",
"extensions": ["smf"]
},
"application/vnd.stardivision.writer": {
"source": "apache",
"extensions": ["sdw","vor"]
},
"application/vnd.stardivision.writer-global": {
"source": "apache",
"extensions": ["sgl"]
},
"application/vnd.stepmania.package": {
"source": "iana",
"extensions": ["smzip"]
},
"application/vnd.stepmania.stepchart": {
"source": "iana",
"extensions": ["sm"]
},
"application/vnd.street-stream": {
"source": "iana"
},
"application/vnd.sun.wadl+xml": {
"source": "iana"
},
"application/vnd.sun.xml.calc": {
"source": "apache",
"extensions": ["sxc"]
},
"application/vnd.sun.xml.calc.template": {
"source": "apache",
"extensions": ["stc"]
},
"application/vnd.sun.xml.draw": {
"source": "apache",
"extensions": ["sxd"]
},
"application/vnd.sun.xml.draw.template": {
"source": "apache",
"extensions": ["std"]
},
"application/vnd.sun.xml.impress": {
"source": "apache",
"extensions": ["sxi"]
},
"application/vnd.sun.xml.impress.template": {
"source": "apache",
"extensions": ["sti"]
},
"application/vnd.sun.xml.math": {
"source": "apache",
"extensions": ["sxm"]
},
"application/vnd.sun.xml.writer": {
"source": "apache",
"extensions": ["sxw"]
},
"application/vnd.sun.xml.writer.global": {
"source": "apache",
"extensions": ["sxg"]
},
"application/vnd.sun.xml.writer.template": {
"source": "apache",
"extensions": ["stw"]
},
"application/vnd.sus-calendar": {
"source": "iana",
"extensions": ["sus","susp"]
},
"application/vnd.svd": {
"source": "iana",
"extensions": ["svd"]
},
"application/vnd.swiftview-ics": {
"source": "iana"
},
"application/vnd.symbian.install": {
"source": "apache",
"extensions": ["sis","sisx"]
},
"application/vnd.syncml+xml": {
"source": "iana",
"extensions": ["xsm"]
},
"application/vnd.syncml.dm+wbxml": {
"source": "iana",
"extensions": ["bdm"]
},
"application/vnd.syncml.dm+xml": {
"source": "iana",
"extensions": ["xdm"]
},
"application/vnd.syncml.dm.notification": {
"source": "iana"
},
"application/vnd.syncml.dmddf+wbxml": {
"source": "iana"
},
"application/vnd.syncml.dmddf+xml": {
"source": "iana"
},
"application/vnd.syncml.dmtnds+wbxml": {
"source": "iana"
},
"application/vnd.syncml.dmtnds+xml": {
"source": "iana"
},
"application/vnd.syncml.ds.notification": {
"source": "iana"
},
"application/vnd.tao.intent-module-archive": {
"source": "iana",
"extensions": ["tao"]
},
"application/vnd.tcpdump.pcap": {
"source": "iana",
"extensions": ["pcap","cap","dmp"]
},
"application/vnd.tmd.mediaflex.api+xml": {
"source": "iana"
},
"application/vnd.tml": {
"source": "iana"
},
"application/vnd.tmobile-livetv": {
"source": "iana",
"extensions": ["tmo"]
},
"application/vnd.trid.tpt": {
"source": "iana",
"extensions": ["tpt"]
},
"application/vnd.triscape.mxs": {
"source": "iana",
"extensions": ["mxs"]
},
"application/vnd.trueapp": {
"source": "iana",
"extensions": ["tra"]
},
"application/vnd.truedoc": {
"source": "iana"
},
"application/vnd.ubisoft.webplayer": {
"source": "iana"
},
"application/vnd.ufdl": {
"source": "iana",
"extensions": ["ufd","ufdl"]
},
"application/vnd.uiq.theme": {
"source": "iana",
"extensions": ["utz"]
},
"application/vnd.umajin": {
"source": "iana",
"extensions": ["umj"]
},
"application/vnd.unity": {
"source": "iana",
"extensions": ["unityweb"]
},
"application/vnd.uoml+xml": {
"source": "iana",
"extensions": ["uoml"]
},
"application/vnd.uplanet.alert": {
"source": "iana"
},
"application/vnd.uplanet.alert-wbxml": {
"source": "iana"
},
"application/vnd.uplanet.bearer-choice": {
"source": "iana"
},
"application/vnd.uplanet.bearer-choice-wbxml": {
"source": "iana"
},
"application/vnd.uplanet.cacheop": {
"source": "iana"
},
"application/vnd.uplanet.cacheop-wbxml": {
"source": "iana"
},
"application/vnd.uplanet.channel": {
"source": "iana"
},
"application/vnd.uplanet.channel-wbxml": {
"source": "iana"
},
"application/vnd.uplanet.list": {
"source": "iana"
},
"application/vnd.uplanet.list-wbxml": {
"source": "iana"
},
"application/vnd.uplanet.listcmd": {
"source": "iana"
},
"application/vnd.uplanet.listcmd-wbxml": {
"source": "iana"
},
"application/vnd.uplanet.signal": {
"source": "iana"
},
"application/vnd.uri-map": {
"source": "iana"
},
"application/vnd.valve.source.material": {
"source": "iana"
},
"application/vnd.vcx": {
"source": "iana",
"extensions": ["vcx"]
},
"application/vnd.vd-study": {
"source": "iana"
},
"application/vnd.vectorworks": {
"source": "iana"
},
"application/vnd.verimatrix.vcas": {
"source": "iana"
},
"application/vnd.vidsoft.vidconference": {
"source": "iana"
},
"application/vnd.visio": {
"source": "iana",
"extensions": ["vsd","vst","vss","vsw"]
},
"application/vnd.visionary": {
"source": "iana",
"extensions": ["vis"]
},
"application/vnd.vividence.scriptfile": {
"source": "iana"
},
"application/vnd.vsf": {
"source": "iana",
"extensions": ["vsf"]
},
"application/vnd.wap.sic": {
"source": "iana"
},
"application/vnd.wap.slc": {
"source": "iana"
},
"application/vnd.wap.wbxml": {
"source": "iana",
"extensions": ["wbxml"]
},
"application/vnd.wap.wmlc": {
"source": "iana",
"extensions": ["wmlc"]
},
"application/vnd.wap.wmlscriptc": {
"source": "iana",
"extensions": ["wmlsc"]
},
"application/vnd.webturbo": {
"source": "iana",
"extensions": ["wtb"]
},
"application/vnd.wfa.p2p": {
"source": "iana"
},
"application/vnd.wfa.wsc": {
"source": "iana"
},
"application/vnd.windows.devicepairing": {
"source": "iana"
},
"application/vnd.wmc": {
"source": "iana"
},
"application/vnd.wmf.bootstrap": {
"source": "iana"
},
"application/vnd.wolfram.mathematica": {
"source": "iana"
},
"application/vnd.wolfram.mathematica.package": {
"source": "iana"
},
"application/vnd.wolfram.player": {
"source": "iana",
"extensions": ["nbp"]
},
"application/vnd.wordperfect": {
"source": "iana",
"extensions": ["wpd"]
},
"application/vnd.wqd": {
"source": "iana",
"extensions": ["wqd"]
},
"application/vnd.wrq-hp3000-labelled": {
"source": "iana"
},
"application/vnd.wt.stf": {
"source": "iana",
"extensions": ["stf"]
},
"application/vnd.wv.csp+wbxml": {
"source": "iana"
},
"application/vnd.wv.csp+xml": {
"source": "iana"
},
"application/vnd.wv.ssp+xml": {
"source": "iana"
},
"application/vnd.xacml+json": {
"source": "iana",
"compressible": true
},
"application/vnd.xara": {
"source": "iana",
"extensions": ["xar"]
},
"application/vnd.xfdl": {
"source": "iana",
"extensions": ["xfdl"]
},
"application/vnd.xfdl.webform": {
"source": "iana"
},
"application/vnd.xmi+xml": {
"source": "iana"
},
"application/vnd.xmpie.cpkg": {
"source": "iana"
},
"application/vnd.xmpie.dpkg": {
"source": "iana"
},
"application/vnd.xmpie.plan": {
"source": "iana"
},
"application/vnd.xmpie.ppkg": {
"source": "iana"
},
"application/vnd.xmpie.xlim": {
"source": "iana"
},
"application/vnd.yamaha.hv-dic": {
"source": "iana",
"extensions": ["hvd"]
},
"application/vnd.yamaha.hv-script": {
"source": "iana",
"extensions": ["hvs"]
},
"application/vnd.yamaha.hv-voice": {
"source": "iana",
"extensions": ["hvp"]
},
"application/vnd.yamaha.openscoreformat": {
"source": "iana",
"extensions": ["osf"]
},
"application/vnd.yamaha.openscoreformat.osfpvg+xml": {
"source": "iana",
"extensions": ["osfpvg"]
},
"application/vnd.yamaha.remote-setup": {
"source": "iana"
},
"application/vnd.yamaha.smaf-audio": {
"source": "iana",
"extensions": ["saf"]
},
"application/vnd.yamaha.smaf-phrase": {
"source": "iana",
"extensions": ["spf"]
},
"application/vnd.yamaha.through-ngn": {
"source": "iana"
},
"application/vnd.yamaha.tunnel-udpencap": {
"source": "iana"
},
"application/vnd.yaoweme": {
"source": "iana"
},
"application/vnd.yellowriver-custom-menu": {
"source": "iana",
"extensions": ["cmp"]
},
"application/vnd.zul": {
"source": "iana",
"extensions": ["zir","zirz"]
},
"application/vnd.zzazz.deck+xml": {
"source": "iana",
"extensions": ["zaz"]
},
"application/voicexml+xml": {
"source": "iana",
"extensions": ["vxml"]
},
"application/vq-rtcpxr": {
"source": "iana"
},
"application/watcherinfo+xml": {
"source": "iana"
},
"application/whoispp-query": {
"source": "iana"
},
"application/whoispp-response": {
"source": "iana"
},
"application/widget": {
"source": "iana",
"extensions": ["wgt"]
},
"application/winhlp": {
"source": "apache",
"extensions": ["hlp"]
},
"application/wita": {
"source": "iana"
},
"application/wordperfect5.1": {
"source": "iana"
},
"application/wsdl+xml": {
"source": "iana",
"extensions": ["wsdl"]
},
"application/wspolicy+xml": {
"source": "iana",
"extensions": ["wspolicy"]
},
"application/x-7z-compressed": {
"source": "apache",
"compressible": false,
"extensions": ["7z"]
},
"application/x-abiword": {
"source": "apache",
"extensions": ["abw"]
},
"application/x-ace-compressed": {
"source": "apache",
"extensions": ["ace"]
},
"application/x-amf": {
"source": "apache"
},
"application/x-apple-diskimage": {
"source": "apache",
"extensions": ["dmg"]
},
"application/x-authorware-bin": {
"source": "apache",
"extensions": ["aab","x32","u32","vox"]
},
"application/x-authorware-map": {
"source": "apache",
"extensions": ["aam"]
},
"application/x-authorware-seg": {
"source": "apache",
"extensions": ["aas"]
},
"application/x-bcpio": {
"source": "apache",
"extensions": ["bcpio"]
},
"application/x-bdoc": {
"compressible": false,
"extensions": ["bdoc"]
},
"application/x-bittorrent": {
"source": "apache",
"extensions": ["torrent"]
},
"application/x-blorb": {
"source": "apache",
"extensions": ["blb","blorb"]
},
"application/x-bzip": {
"source": "apache",
"compressible": false,
"extensions": ["bz"]
},
"application/x-bzip2": {
"source": "apache",
"compressible": false,
"extensions": ["bz2","boz"]
},
"application/x-cbr": {
"source": "apache",
"extensions": ["cbr","cba","cbt","cbz","cb7"]
},
"application/x-cdlink": {
"source": "apache",
"extensions": ["vcd"]
},
"application/x-cfs-compressed": {
"source": "apache",
"extensions": ["cfs"]
},
"application/x-chat": {
"source": "apache",
"extensions": ["chat"]
},
"application/x-chess-pgn": {
"source": "apache",
"extensions": ["pgn"]
},
"application/x-chrome-extension": {
"extensions": ["crx"]
},
"application/x-cocoa": {
"source": "nginx",
"extensions": ["cco"]
},
"application/x-compress": {
"source": "apache"
},
"application/x-conference": {
"source": "apache",
"extensions": ["nsc"]
},
"application/x-cpio": {
"source": "apache",
"extensions": ["cpio"]
},
"application/x-csh": {
"source": "apache",
"extensions": ["csh"]
},
"application/x-deb": {
"compressible": false
},
"application/x-debian-package": {
"source": "apache",
"extensions": ["deb","udeb"]
},
"application/x-dgc-compressed": {
"source": "apache",
"extensions": ["dgc"]
},
"application/x-director": {
"source": "apache",
"extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]
},
"application/x-doom": {
"source": "apache",
"extensions": ["wad"]
},
"application/x-dtbncx+xml": {
"source": "apache",
"extensions": ["ncx"]
},
"application/x-dtbook+xml": {
"source": "apache",
"extensions": ["dtb"]
},
"application/x-dtbresource+xml": {
"source": "apache",
"extensions": ["res"]
},
"application/x-dvi": {
"source": "apache",
"compressible": false,
"extensions": ["dvi"]
},
"application/x-envoy": {
"source": "apache",
"extensions": ["evy"]
},
"application/x-eva": {
"source": "apache",
"extensions": ["eva"]
},
"application/x-font-bdf": {
"source": "apache",
"extensions": ["bdf"]
},
"application/x-font-dos": {
"source": "apache"
},
"application/x-font-framemaker": {
"source": "apache"
},
"application/x-font-ghostscript": {
"source": "apache",
"extensions": ["gsf"]
},
"application/x-font-libgrx": {
"source": "apache"
},
"application/x-font-linux-psf": {
"source": "apache",
"extensions": ["psf"]
},
"application/x-font-otf": {
"source": "apache",
"compressible": true,
"extensions": ["otf"]
},
"application/x-font-pcf": {
"source": "apache",
"extensions": ["pcf"]
},
"application/x-font-snf": {
"source": "apache",
"extensions": ["snf"]
},
"application/x-font-speedo": {
"source": "apache"
},
"application/x-font-sunos-news": {
"source": "apache"
},
"application/x-font-ttf": {
"source": "apache",
"compressible": true,
"extensions": ["ttf","ttc"]
},
"application/x-font-type1": {
"source": "apache",
"extensions": ["pfa","pfb","pfm","afm"]
},
"application/x-font-vfont": {
"source": "apache"
},
"application/x-freearc": {
"source": "apache",
"extensions": ["arc"]
},
"application/x-futuresplash": {
"source": "apache",
"extensions": ["spl"]
},
"application/x-gca-compressed": {
"source": "apache",
"extensions": ["gca"]
},
"application/x-glulx": {
"source": "apache",
"extensions": ["ulx"]
},
"application/x-gnumeric": {
"source": "apache",
"extensions": ["gnumeric"]
},
"application/x-gramps-xml": {
"source": "apache",
"extensions": ["gramps"]
},
"application/x-gtar": {
"source": "apache",
"extensions": ["gtar"]
},
"application/x-gzip": {
"source": "apache"
},
"application/x-hdf": {
"source": "apache",
"extensions": ["hdf"]
},
"application/x-httpd-php": {
"compressible": true,
"extensions": ["php"]
},
"application/x-install-instructions": {
"source": "apache",
"extensions": ["install"]
},
"application/x-iso9660-image": {
"source": "apache",
"extensions": ["iso"]
},
"application/x-java-archive-diff": {
"source": "nginx",
"extensions": ["jardiff"]
},
"application/x-java-jnlp-file": {
"source": "apache",
"compressible": false,
"extensions": ["jnlp"]
},
"application/x-javascript": {
"compressible": true
},
"application/x-latex": {
"source": "apache",
"compressible": false,
"extensions": ["latex"]
},
"application/x-lua-bytecode": {
"extensions": ["luac"]
},
"application/x-lzh-compressed": {
"source": "apache",
"extensions": ["lzh","lha"]
},
"application/x-makeself": {
"source": "nginx",
"extensions": ["run"]
},
"application/x-mie": {
"source": "apache",
"extensions": ["mie"]
},
"application/x-mobipocket-ebook": {
"source": "apache",
"extensions": ["prc","mobi"]
},
"application/x-mpegurl": {
"compressible": false
},
"application/x-ms-application": {
"source": "apache",
"extensions": ["application"]
},
"application/x-ms-shortcut": {
"source": "apache",
"extensions": ["lnk"]
},
"application/x-ms-wmd": {
"source": "apache",
"extensions": ["wmd"]
},
"application/x-ms-wmz": {
"source": "apache",
"extensions": ["wmz"]
},
"application/x-ms-xbap": {
"source": "apache",
"extensions": ["xbap"]
},
"application/x-msaccess": {
"source": "apache",
"extensions": ["mdb"]
},
"application/x-msbinder": {
"source": "apache",
"extensions": ["obd"]
},
"application/x-mscardfile": {
"source": "apache",
"extensions": ["crd"]
},
"application/x-msclip": {
"source": "apache",
"extensions": ["clp"]
},
"application/x-msdos-program": {
"extensions": ["exe"]
},
"application/x-msdownload": {
"source": "apache",
"extensions": ["exe","dll","com","bat","msi"]
},
"application/x-msmediaview": {
"source": "apache",
"extensions": ["mvb","m13","m14"]
},
"application/x-msmetafile": {
"source": "apache",
"extensions": ["wmf","wmz","emf","emz"]
},
"application/x-msmoney": {
"source": "apache",
"extensions": ["mny"]
},
"application/x-mspublisher": {
"source": "apache",
"extensions": ["pub"]
},
"application/x-msschedule": {
"source": "apache",
"extensions": ["scd"]
},
"application/x-msterminal": {
"source": "apache",
"extensions": ["trm"]
},
"application/x-mswrite": {
"source": "apache",
"extensions": ["wri"]
},
"application/x-netcdf": {
"source": "apache",
"extensions": ["nc","cdf"]
},
"application/x-ns-proxy-autoconfig": {
"compressible": true,
"extensions": ["pac"]
},
"application/x-nzb": {
"source": "apache",
"extensions": ["nzb"]
},
"application/x-perl": {
"source": "nginx",
"extensions": ["pl","pm"]
},
"application/x-pilot": {
"source": "nginx",
"extensions": ["prc","pdb"]
},
"application/x-pkcs12": {
"source": "apache",
"compressible": false,
"extensions": ["p12","pfx"]
},
"application/x-pkcs7-certificates": {
"source": "apache",
"extensions": ["p7b","spc"]
},
"application/x-pkcs7-certreqresp": {
"source": "apache",
"extensions": ["p7r"]
},
"application/x-rar-compressed": {
"source": "apache",
"compressible": false,
"extensions": ["rar"]
},
"application/x-redhat-package-manager": {
"source": "nginx",
"extensions": ["rpm"]
},
"application/x-research-info-systems": {
"source": "apache",
"extensions": ["ris"]
},
"application/x-sea": {
"source": "nginx",
"extensions": ["sea"]
},
"application/x-sh": {
"source": "apache",
"compressible": true,
"extensions": ["sh"]
},
"application/x-shar": {
"source": "apache",
"extensions": ["shar"]
},
"application/x-shockwave-flash": {
"source": "apache",
"compressible": false,
"extensions": ["swf"]
},
"application/x-silverlight-app": {
"source": "apache",
"extensions": ["xap"]
},
"application/x-sql": {
"source": "apache",
"extensions": ["sql"]
},
"application/x-stuffit": {
"source": "apache",
"compressible": false,
"extensions": ["sit"]
},
"application/x-stuffitx": {
"source": "apache",
"extensions": ["sitx"]
},
"application/x-subrip": {
"source": "apache",
"extensions": ["srt"]
},
"application/x-sv4cpio": {
"source": "apache",
"extensions": ["sv4cpio"]
},
"application/x-sv4crc": {
"source": "apache",
"extensions": ["sv4crc"]
},
"application/x-t3vm-image": {
"source": "apache",
"extensions": ["t3"]
},
"application/x-tads": {
"source": "apache",
"extensions": ["gam"]
},
"application/x-tar": {
"source": "apache",
"compressible": true,
"extensions": ["tar"]
},
"application/x-tcl": {
"source": "apache",
"extensions": ["tcl","tk"]
},
"application/x-tex": {
"source": "apache",
"extensions": ["tex"]
},
"application/x-tex-tfm": {
"source": "apache",
"extensions": ["tfm"]
},
"application/x-texinfo": {
"source": "apache",
"extensions": ["texinfo","texi"]
},
"application/x-tgif": {
"source": "apache",
"extensions": ["obj"]
},
"application/x-ustar": {
"source": "apache",
"extensions": ["ustar"]
},
"application/x-wais-source": {
"source": "apache",
"extensions": ["src"]
},
"application/x-web-app-manifest+json": {
"compressible": true,
"extensions": ["webapp"]
},
"application/x-www-form-urlencoded": {
"source": "iana",
"compressible": true
},
"application/x-x509-ca-cert": {
"source": "apache",
"extensions": ["der","crt","pem"]
},
"application/x-xfig": {
"source": "apache",
"extensions": ["fig"]
},
"application/x-xliff+xml": {
"source": "apache",
"extensions": ["xlf"]
},
"application/x-xpinstall": {
"source": "apache",
"compressible": false,
"extensions": ["xpi"]
},
"application/x-xz": {
"source": "apache",
"extensions": ["xz"]
},
"application/x-zmachine": {
"source": "apache",
"extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"]
},
"application/x400-bp": {
"source": "iana"
},
"application/xacml+xml": {
"source": "iana"
},
"application/xaml+xml": {
"source": "apache",
"extensions": ["xaml"]
},
"application/xcap-att+xml": {
"source": "iana"
},
"application/xcap-caps+xml": {
"source": "iana"
},
"application/xcap-diff+xml": {
"source": "iana",
"extensions": ["xdf"]
},
"application/xcap-el+xml": {
"source": "iana"
},
"application/xcap-error+xml": {
"source": "iana"
},
"application/xcap-ns+xml": {
"source": "iana"
},
"application/xcon-conference-info+xml": {
"source": "iana"
},
"application/xcon-conference-info-diff+xml": {
"source": "iana"
},
"application/xenc+xml": {
"source": "iana",
"extensions": ["xenc"]
},
"application/xhtml+xml": {
"source": "iana",
"compressible": true,
"extensions": ["xhtml","xht"]
},
"application/xhtml-voice+xml": {
"source": "apache"
},
"application/xml": {
"source": "iana",
"compressible": true,
"extensions": ["xml","xsl","xsd"]
},
"application/xml-dtd": {
"source": "iana",
"compressible": true,
"extensions": ["dtd"]
},
"application/xml-external-parsed-entity": {
"source": "iana"
},
"application/xml-patch+xml": {
"source": "iana"
},
"application/xmpp+xml": {
"source": "iana"
},
"application/xop+xml": {
"source": "iana",
"compressible": true,
"extensions": ["xop"]
},
"application/xproc+xml": {
"source": "apache",
"extensions": ["xpl"]
},
"application/xslt+xml": {
"source": "iana",
"extensions": ["xslt"]
},
"application/xspf+xml": {
"source": "apache",
"extensions": ["xspf"]
},
"application/xv+xml": {
"source": "iana",
"extensions": ["mxml","xhvml","xvml","xvm"]
},
"application/yang": {
"source": "iana",
"extensions": ["yang"]
},
"application/yin+xml": {
"source": "iana",
"extensions": ["yin"]
},
"application/zip": {
"source": "iana",
"compressible": false,
"extensions": ["zip"]
},
"application/zlib": {
"source": "iana"
},
"audio/1d-interleaved-parityfec": {
"source": "iana"
},
"audio/32kadpcm": {
"source": "iana"
},
"audio/3gpp": {
"source": "iana"
},
"audio/3gpp2": {
"source": "iana"
},
"audio/ac3": {
"source": "iana"
},
"audio/adpcm": {
"source": "apache",
"extensions": ["adp"]
},
"audio/amr": {
"source": "iana"
},
"audio/amr-wb": {
"source": "iana"
},
"audio/amr-wb+": {
"source": "iana"
},
"audio/aptx": {
"source": "iana"
},
"audio/asc": {
"source": "iana"
},
"audio/atrac-advanced-lossless": {
"source": "iana"
},
"audio/atrac-x": {
"source": "iana"
},
"audio/atrac3": {
"source": "iana"
},
"audio/basic": {
"source": "iana",
"compressible": false,
"extensions": ["au","snd"]
},
"audio/bv16": {
"source": "iana"
},
"audio/bv32": {
"source": "iana"
},
"audio/clearmode": {
"source": "iana"
},
"audio/cn": {
"source": "iana"
},
"audio/dat12": {
"source": "iana"
},
"audio/dls": {
"source": "iana"
},
"audio/dsr-es201108": {
"source": "iana"
},
"audio/dsr-es202050": {
"source": "iana"
},
"audio/dsr-es202211": {
"source": "iana"
},
"audio/dsr-es202212": {
"source": "iana"
},
"audio/dv": {
"source": "iana"
},
"audio/dvi4": {
"source": "iana"
},
"audio/eac3": {
"source": "iana"
},
"audio/encaprtp": {
"source": "iana"
},
"audio/evrc": {
"source": "iana"
},
"audio/evrc-qcp": {
"source": "iana"
},
"audio/evrc0": {
"source": "iana"
},
"audio/evrc1": {
"source": "iana"
},
"audio/evrcb": {
"source": "iana"
},
"audio/evrcb0": {
"source": "iana"
},
"audio/evrcb1": {
"source": "iana"
},
"audio/evrcnw": {
"source": "iana"
},
"audio/evrcnw0": {
"source": "iana"
},
"audio/evrcnw1": {
"source": "iana"
},
"audio/evrcwb": {
"source": "iana"
},
"audio/evrcwb0": {
"source": "iana"
},
"audio/evrcwb1": {
"source": "iana"
},
"audio/evs": {
"source": "iana"
},
"audio/fwdred": {
"source": "iana"
},
"audio/g711-0": {
"source": "iana"
},
"audio/g719": {
"source": "iana"
},
"audio/g722": {
"source": "iana"
},
"audio/g7221": {
"source": "iana"
},
"audio/g723": {
"source": "iana"
},
"audio/g726-16": {
"source": "iana"
},
"audio/g726-24": {
"source": "iana"
},
"audio/g726-32": {
"source": "iana"
},
"audio/g726-40": {
"source": "iana"
},
"audio/g728": {
"source": "iana"
},
"audio/g729": {
"source": "iana"
},
"audio/g7291": {
"source": "iana"
},
"audio/g729d": {
"source": "iana"
},
"audio/g729e": {
"source": "iana"
},
"audio/gsm": {
"source": "iana"
},
"audio/gsm-efr": {
"source": "iana"
},
"audio/gsm-hr-08": {
"source": "iana"
},
"audio/ilbc": {
"source": "iana"
},
"audio/ip-mr_v2.5": {
"source": "iana"
},
"audio/isac": {
"source": "apache"
},
"audio/l16": {
"source": "iana"
},
"audio/l20": {
"source": "iana"
},
"audio/l24": {
"source": "iana",
"compressible": false
},
"audio/l8": {
"source": "iana"
},
"audio/lpc": {
"source": "iana"
},
"audio/midi": {
"source": "apache",
"extensions": ["mid","midi","kar","rmi"]
},
"audio/mobile-xmf": {
"source": "iana"
},
"audio/mp4": {
"source": "iana",
"compressible": false,
"extensions": ["mp4a","m4a"]
},
"audio/mp4a-latm": {
"source": "iana"
},
"audio/mpa": {
"source": "iana"
},
"audio/mpa-robust": {
"source": "iana"
},
"audio/mpeg": {
"source": "iana",
"compressible": false,
"extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"]
},
"audio/mpeg4-generic": {
"source": "iana"
},
"audio/musepack": {
"source": "apache"
},
"audio/ogg": {
"source": "iana",
"compressible": false,
"extensions": ["oga","ogg","spx"]
},
"audio/opus": {
"source": "iana"
},
"audio/parityfec": {
"source": "iana"
},
"audio/pcma": {
"source": "iana"
},
"audio/pcma-wb": {
"source": "iana"
},
"audio/pcmu": {
"source": "iana"
},
"audio/pcmu-wb": {
"source": "iana"
},
"audio/prs.sid": {
"source": "iana"
},
"audio/qcelp": {
"source": "iana"
},
"audio/raptorfec": {
"source": "iana"
},
"audio/red": {
"source": "iana"
},
"audio/rtp-enc-aescm128": {
"source": "iana"
},
"audio/rtp-midi": {
"source": "iana"
},
"audio/rtploopback": {
"source": "iana"
},
"audio/rtx": {
"source": "iana"
},
"audio/s3m": {
"source": "apache",
"extensions": ["s3m"]
},
"audio/silk": {
"source": "apache",
"extensions": ["sil"]
},
"audio/smv": {
"source": "iana"
},
"audio/smv-qcp": {
"source": "iana"
},
"audio/smv0": {
"source": "iana"
},
"audio/sp-midi": {
"source": "iana"
},
"audio/speex": {
"source": "iana"
},
"audio/t140c": {
"source": "iana"
},
"audio/t38": {
"source": "iana"
},
"audio/telephone-event": {
"source": "iana"
},
"audio/tone": {
"source": "iana"
},
"audio/uemclip": {
"source": "iana"
},
"audio/ulpfec": {
"source": "iana"
},
"audio/vdvi": {
"source": "iana"
},
"audio/vmr-wb": {
"source": "iana"
},
"audio/vnd.3gpp.iufp": {
"source": "iana"
},
"audio/vnd.4sb": {
"source": "iana"
},
"audio/vnd.audiokoz": {
"source": "iana"
},
"audio/vnd.celp": {
"source": "iana"
},
"audio/vnd.cisco.nse": {
"source": "iana"
},
"audio/vnd.cmles.radio-events": {
"source": "iana"
},
"audio/vnd.cns.anp1": {
"source": "iana"
},
"audio/vnd.cns.inf1": {
"source": "iana"
},
"audio/vnd.dece.audio": {
"source": "iana",
"extensions": ["uva","uvva"]
},
"audio/vnd.digital-winds": {
"source": "iana",
"extensions": ["eol"]
},
"audio/vnd.dlna.adts": {
"source": "iana"
},
"audio/vnd.dolby.heaac.1": {
"source": "iana"
},
"audio/vnd.dolby.heaac.2": {
"source": "iana"
},
"audio/vnd.dolby.mlp": {
"source": "iana"
},
"audio/vnd.dolby.mps": {
"source": "iana"
},
"audio/vnd.dolby.pl2": {
"source": "iana"
},
"audio/vnd.dolby.pl2x": {
"source": "iana"
},
"audio/vnd.dolby.pl2z": {
"source": "iana"
},
"audio/vnd.dolby.pulse.1": {
"source": "iana"
},
"audio/vnd.dra": {
"source": "iana",
"extensions": ["dra"]
},
"audio/vnd.dts": {
"source": "iana",
"extensions": ["dts"]
},
"audio/vnd.dts.hd": {
"source": "iana",
"extensions": ["dtshd"]
},
"audio/vnd.dvb.file": {
"source": "iana"
},
"audio/vnd.everad.plj": {
"source": "iana"
},
"audio/vnd.hns.audio": {
"source": "iana"
},
"audio/vnd.lucent.voice": {
"source": "iana",
"extensions": ["lvp"]
},
"audio/vnd.ms-playready.media.pya": {
"source": "iana",
"extensions": ["pya"]
},
"audio/vnd.nokia.mobile-xmf": {
"source": "iana"
},
"audio/vnd.nortel.vbk": {
"source": "iana"
},
"audio/vnd.nuera.ecelp4800": {
"source": "iana",
"extensions": ["ecelp4800"]
},
"audio/vnd.nuera.ecelp7470": {
"source": "iana",
"extensions": ["ecelp7470"]
},
"audio/vnd.nuera.ecelp9600": {
"source": "iana",
"extensions": ["ecelp9600"]
},
"audio/vnd.octel.sbc": {
"source": "iana"
},
"audio/vnd.qcelp": {
"source": "iana"
},
"audio/vnd.rhetorex.32kadpcm": {
"source": "iana"
},
"audio/vnd.rip": {
"source": "iana",
"extensions": ["rip"]
},
"audio/vnd.rn-realaudio": {
"compressible": false
},
"audio/vnd.sealedmedia.softseal.mpeg": {
"source": "iana"
},
"audio/vnd.vmx.cvsd": {
"source": "iana"
},
"audio/vnd.wave": {
"compressible": false
},
"audio/vorbis": {
"source": "iana",
"compressible": false
},
"audio/vorbis-config": {
"source": "iana"
},
"audio/wav": {
"compressible": false,
"extensions": ["wav"]
},
"audio/wave": {
"compressible": false,
"extensions": ["wav"]
},
"audio/webm": {
"source": "apache",
"compressible": false,
"extensions": ["weba"]
},
"audio/x-aac": {
"source": "apache",
"compressible": false,
"extensions": ["aac"]
},
"audio/x-aiff": {
"source": "apache",
"extensions": ["aif","aiff","aifc"]
},
"audio/x-caf": {
"source": "apache",
"compressible": false,
"extensions": ["caf"]
},
"audio/x-flac": {
"source": "apache",
"extensions": ["flac"]
},
"audio/x-m4a": {
"source": "nginx",
"extensions": ["m4a"]
},
"audio/x-matroska": {
"source": "apache",
"extensions": ["mka"]
},
"audio/x-mpegurl": {
"source": "apache",
"extensions": ["m3u"]
},
"audio/x-ms-wax": {
"source": "apache",
"extensions": ["wax"]
},
"audio/x-ms-wma": {
"source": "apache",
"extensions": ["wma"]
},
"audio/x-pn-realaudio": {
"source": "apache",
"extensions": ["ram","ra"]
},
"audio/x-pn-realaudio-plugin": {
"source": "apache",
"extensions": ["rmp"]
},
"audio/x-realaudio": {
"source": "nginx",
"extensions": ["ra"]
},
"audio/x-tta": {
"source": "apache"
},
"audio/x-wav": {
"source": "apache",
"extensions": ["wav"]
},
"audio/xm": {
"source": "apache",
"extensions": ["xm"]
},
"chemical/x-cdx": {
"source": "apache",
"extensions": ["cdx"]
},
"chemical/x-cif": {
"source": "apache",
"extensions": ["cif"]
},
"chemical/x-cmdf": {
"source": "apache",
"extensions": ["cmdf"]
},
"chemical/x-cml": {
"source": "apache",
"extensions": ["cml"]
},
"chemical/x-csml": {
"source": "apache",
"extensions": ["csml"]
},
"chemical/x-pdb": {
"source": "apache"
},
"chemical/x-xyz": {
"source": "apache",
"extensions": ["xyz"]
},
"font/opentype": {
"compressible": true,
"extensions": ["otf"]
},
"image/bmp": {
"source": "apache",
"compressible": true,
"extensions": ["bmp"]
},
"image/cgm": {
"source": "iana",
"extensions": ["cgm"]
},
"image/fits": {
"source": "iana"
},
"image/g3fax": {
"source": "iana",
"extensions": ["g3"]
},
"image/gif": {
"source": "iana",
"compressible": false,
"extensions": ["gif"]
},
"image/ief": {
"source": "iana",
"extensions": ["ief"]
},
"image/jp2": {
"source": "iana"
},
"image/jpeg": {
"source": "iana",
"compressible": false,
"extensions": ["jpeg","jpg","jpe"]
},
"image/jpm": {
"source": "iana"
},
"image/jpx": {
"source": "iana"
},
"image/ktx": {
"source": "iana",
"extensions": ["ktx"]
},
"image/naplps": {
"source": "iana"
},
"image/pjpeg": {
"compressible": false
},
"image/png": {
"source": "iana",
"compressible": false,
"extensions": ["png"]
},
"image/prs.btif": {
"source": "iana",
"extensions": ["btif"]
},
"image/prs.pti": {
"source": "iana"
},
"image/pwg-raster": {
"source": "iana"
},
"image/sgi": {
"source": "apache",
"extensions": ["sgi"]
},
"image/svg+xml": {
"source": "iana",
"compressible": true,
"extensions": ["svg","svgz"]
},
"image/t38": {
"source": "iana"
},
"image/tiff": {
"source": "iana",
"compressible": false,
"extensions": ["tiff","tif"]
},
"image/tiff-fx": {
"source": "iana"
},
"image/vnd.adobe.photoshop": {
"source": "iana",
"compressible": true,
"extensions": ["psd"]
},
"image/vnd.airzip.accelerator.azv": {
"source": "iana"
},
"image/vnd.cns.inf2": {
"source": "iana"
},
"image/vnd.dece.graphic": {
"source": "iana",
"extensions": ["uvi","uvvi","uvg","uvvg"]
},
"image/vnd.djvu": {
"source": "iana",
"extensions": ["djvu","djv"]
},
"image/vnd.dvb.subtitle": {
"source": "iana",
"extensions": ["sub"]
},
"image/vnd.dwg": {
"source": "iana",
"extensions": ["dwg"]
},
"image/vnd.dxf": {
"source": "iana",
"extensions": ["dxf"]
},
"image/vnd.fastbidsheet": {
"source": "iana",
"extensions": ["fbs"]
},
"image/vnd.fpx": {
"source": "iana",
"extensions": ["fpx"]
},
"image/vnd.fst": {
"source": "iana",
"extensions": ["fst"]
},
"image/vnd.fujixerox.edmics-mmr": {
"source": "iana",
"extensions": ["mmr"]
},
"image/vnd.fujixerox.edmics-rlc": {
"source": "iana",
"extensions": ["rlc"]
},
"image/vnd.globalgraphics.pgb": {
"source": "iana"
},
"image/vnd.microsoft.icon": {
"source": "iana"
},
"image/vnd.mix": {
"source": "iana"
},
"image/vnd.mozilla.apng": {
"source": "iana"
},
"image/vnd.ms-modi": {
"source": "iana",
"extensions": ["mdi"]
},
"image/vnd.ms-photo": {
"source": "apache",
"extensions": ["wdp"]
},
"image/vnd.net-fpx": {
"source": "iana",
"extensions": ["npx"]
},
"image/vnd.radiance": {
"source": "iana"
},
"image/vnd.sealed.png": {
"source": "iana"
},
"image/vnd.sealedmedia.softseal.gif": {
"source": "iana"
},
"image/vnd.sealedmedia.softseal.jpg": {
"source": "iana"
},
"image/vnd.svf": {
"source": "iana"
},
"image/vnd.tencent.tap": {
"source": "iana"
},
"image/vnd.valve.source.texture": {
"source": "iana"
},
"image/vnd.wap.wbmp": {
"source": "iana",
"extensions": ["wbmp"]
},
"image/vnd.xiff": {
"source": "iana",
"extensions": ["xif"]
},
"image/vnd.zbrush.pcx": {
"source": "iana"
},
"image/webp": {
"source": "apache",
"extensions": ["webp"]
},
"image/x-3ds": {
"source": "apache",
"extensions": ["3ds"]
},
"image/x-cmu-raster": {
"source": "apache",
"extensions": ["ras"]
},
"image/x-cmx": {
"source": "apache",
"extensions": ["cmx"]
},
"image/x-freehand": {
"source": "apache",
"extensions": ["fh","fhc","fh4","fh5","fh7"]
},
"image/x-icon": {
"source": "apache",
"compressible": true,
"extensions": ["ico"]
},
"image/x-jng": {
"source": "nginx",
"extensions": ["jng"]
},
"image/x-mrsid-image": {
"source": "apache",
"extensions": ["sid"]
},
"image/x-ms-bmp": {
"source": "nginx",
"compressible": true,
"extensions": ["bmp"]
},
"image/x-pcx": {
"source": "apache",
"extensions": ["pcx"]
},
"image/x-pict": {
"source": "apache",
"extensions": ["pic","pct"]
},
"image/x-portable-anymap": {
"source": "apache",
"extensions": ["pnm"]
},
"image/x-portable-bitmap": {
"source": "apache",
"extensions": ["pbm"]
},
"image/x-portable-graymap": {
"source": "apache",
"extensions": ["pgm"]
},
"image/x-portable-pixmap": {
"source": "apache",
"extensions": ["ppm"]
},
"image/x-rgb": {
"source": "apache",
"extensions": ["rgb"]
},
"image/x-tga": {
"source": "apache",
"extensions": ["tga"]
},
"image/x-xbitmap": {
"source": "apache",
"extensions": ["xbm"]
},
"image/x-xcf": {
"compressible": false
},
"image/x-xpixmap": {
"source": "apache",
"extensions": ["xpm"]
},
"image/x-xwindowdump": {
"source": "apache",
"extensions": ["xwd"]
},
"message/cpim": {
"source": "iana"
},
"message/delivery-status": {
"source": "iana"
},
"message/disposition-notification": {
"source": "iana"
},
"message/external-body": {
"source": "iana"
},
"message/feedback-report": {
"source": "iana"
},
"message/global": {
"source": "iana"
},
"message/global-delivery-status": {
"source": "iana"
},
"message/global-disposition-notification": {
"source": "iana"
},
"message/global-headers": {
"source": "iana"
},
"message/http": {
"source": "iana",
"compressible": false
},
"message/imdn+xml": {
"source": "iana",
"compressible": true
},
"message/news": {
"source": "iana"
},
"message/partial": {
"source": "iana",
"compressible": false
},
"message/rfc822": {
"source": "iana",
"compressible": true,
"extensions": ["eml","mime"]
},
"message/s-http": {
"source": "iana"
},
"message/sip": {
"source": "iana"
},
"message/sipfrag": {
"source": "iana"
},
"message/tracking-status": {
"source": "iana"
},
"message/vnd.si.simp": {
"source": "iana"
},
"message/vnd.wfa.wsc": {
"source": "iana"
},
"model/iges": {
"source": "iana",
"compressible": false,
"extensions": ["igs","iges"]
},
"model/mesh": {
"source": "iana",
"compressible": false,
"extensions": ["msh","mesh","silo"]
},
"model/vnd.collada+xml": {
"source": "iana",
"extensions": ["dae"]
},
"model/vnd.dwf": {
"source": "iana",
"extensions": ["dwf"]
},
"model/vnd.flatland.3dml": {
"source": "iana"
},
"model/vnd.gdl": {
"source": "iana",
"extensions": ["gdl"]
},
"model/vnd.gs-gdl": {
"source": "apache"
},
"model/vnd.gs.gdl": {
"source": "iana"
},
"model/vnd.gtw": {
"source": "iana",
"extensions": ["gtw"]
},
"model/vnd.moml+xml": {
"source": "iana"
},
"model/vnd.mts": {
"source": "iana",
"extensions": ["mts"]
},
"model/vnd.opengex": {
"source": "iana"
},
"model/vnd.parasolid.transmit.binary": {
"source": "iana"
},
"model/vnd.parasolid.transmit.text": {
"source": "iana"
},
"model/vnd.valve.source.compiled-map": {
"source": "iana"
},
"model/vnd.vtu": {
"source": "iana",
"extensions": ["vtu"]
},
"model/vrml": {
"source": "iana",
"compressible": false,
"extensions": ["wrl","vrml"]
},
"model/x3d+binary": {
"source": "apache",
"compressible": false,
"extensions": ["x3db","x3dbz"]
},
"model/x3d+fastinfoset": {
"source": "iana"
},
"model/x3d+vrml": {
"source": "apache",
"compressible": false,
"extensions": ["x3dv","x3dvz"]
},
"model/x3d+xml": {
"source": "iana",
"compressible": true,
"extensions": ["x3d","x3dz"]
},
"model/x3d-vrml": {
"source": "iana"
},
"multipart/alternative": {
"source": "iana",
"compressible": false
},
"multipart/appledouble": {
"source": "iana"
},
"multipart/byteranges": {
"source": "iana"
},
"multipart/digest": {
"source": "iana"
},
"multipart/encrypted": {
"source": "iana",
"compressible": false
},
"multipart/form-data": {
"source": "iana",
"compressible": false
},
"multipart/header-set": {
"source": "iana"
},
"multipart/mixed": {
"source": "iana",
"compressible": false
},
"multipart/parallel": {
"source": "iana"
},
"multipart/related": {
"source": "iana",
"compressible": false
},
"multipart/report": {
"source": "iana"
},
"multipart/signed": {
"source": "iana",
"compressible": false
},
"multipart/voice-message": {
"source": "iana"
},
"multipart/x-mixed-replace": {
"source": "iana"
},
"text/1d-interleaved-parityfec": {
"source": "iana"
},
"text/cache-manifest": {
"source": "iana",
"compressible": true,
"extensions": ["appcache","manifest"]
},
"text/calendar": {
"source": "iana",
"extensions": ["ics","ifb"]
},
"text/calender": {
"compressible": true
},
"text/cmd": {
"compressible": true
},
"text/coffeescript": {
"extensions": ["coffee","litcoffee"]
},
"text/css": {
"source": "iana",
"compressible": true,
"extensions": ["css"]
},
"text/csv": {
"source": "iana",
"compressible": true,
"extensions": ["csv"]
},
"text/csv-schema": {
"source": "iana"
},
"text/directory": {
"source": "iana"
},
"text/dns": {
"source": "iana"
},
"text/ecmascript": {
"source": "iana"
},
"text/encaprtp": {
"source": "iana"
},
"text/enriched": {
"source": "iana"
},
"text/fwdred": {
"source": "iana"
},
"text/grammar-ref-list": {
"source": "iana"
},
"text/hjson": {
"extensions": ["hjson"]
},
"text/html": {
"source": "iana",
"compressible": true,
"extensions": ["html","htm","shtml"]
},
"text/jade": {
"extensions": ["jade"]
},
"text/javascript": {
"source": "iana",
"compressible": true
},
"text/jcr-cnd": {
"source": "iana"
},
"text/jsx": {
"compressible": true,
"extensions": ["jsx"]
},
"text/less": {
"extensions": ["less"]
},
"text/markdown": {
"source": "iana"
},
"text/mathml": {
"source": "nginx",
"extensions": ["mml"]
},
"text/mizar": {
"source": "iana"
},
"text/n3": {
"source": "iana",
"compressible": true,
"extensions": ["n3"]
},
"text/parameters": {
"source": "iana"
},
"text/parityfec": {
"source": "iana"
},
"text/plain": {
"source": "iana",
"compressible": true,
"extensions": ["txt","text","conf","def","list","log","in","ini"]
},
"text/provenance-notation": {
"source": "iana"
},
"text/prs.fallenstein.rst": {
"source": "iana"
},
"text/prs.lines.tag": {
"source": "iana",
"extensions": ["dsc"]
},
"text/raptorfec": {
"source": "iana"
},
"text/red": {
"source": "iana"
},
"text/rfc822-headers": {
"source": "iana"
},
"text/richtext": {
"source": "iana",
"compressible": true,
"extensions": ["rtx"]
},
"text/rtf": {
"source": "iana",
"compressible": true,
"extensions": ["rtf"]
},
"text/rtp-enc-aescm128": {
"source": "iana"
},
"text/rtploopback": {
"source": "iana"
},
"text/rtx": {
"source": "iana"
},
"text/sgml": {
"source": "iana",
"extensions": ["sgml","sgm"]
},
"text/stylus": {
"extensions": ["stylus","styl"]
},
"text/t140": {
"source": "iana"
},
"text/tab-separated-values": {
"source": "iana",
"compressible": true,
"extensions": ["tsv"]
},
"text/troff": {
"source": "iana",
"extensions": ["t","tr","roff","man","me","ms"]
},
"text/turtle": {
"source": "iana",
"extensions": ["ttl"]
},
"text/ulpfec": {
"source": "iana"
},
"text/uri-list": {
"source": "iana",
"compressible": true,
"extensions": ["uri","uris","urls"]
},
"text/vcard": {
"source": "iana",
"compressible": true,
"extensions": ["vcard"]
},
"text/vnd.a": {
"source": "iana"
},
"text/vnd.abc": {
"source": "iana"
},
"text/vnd.curl": {
"source": "iana",
"extensions": ["curl"]
},
"text/vnd.curl.dcurl": {
"source": "apache",
"extensions": ["dcurl"]
},
"text/vnd.curl.mcurl": {
"source": "apache",
"extensions": ["mcurl"]
},
"text/vnd.curl.scurl": {
"source": "apache",
"extensions": ["scurl"]
},
"text/vnd.debian.copyright": {
"source": "iana"
},
"text/vnd.dmclientscript": {
"source": "iana"
},
"text/vnd.dvb.subtitle": {
"source": "iana",
"extensions": ["sub"]
},
"text/vnd.esmertec.theme-descriptor": {
"source": "iana"
},
"text/vnd.fly": {
"source": "iana",
"extensions": ["fly"]
},
"text/vnd.fmi.flexstor": {
"source": "iana",
"extensions": ["flx"]
},
"text/vnd.graphviz": {
"source": "iana",
"extensions": ["gv"]
},
"text/vnd.in3d.3dml": {
"source": "iana",
"extensions": ["3dml"]
},
"text/vnd.in3d.spot": {
"source": "iana",
"extensions": ["spot"]
},
"text/vnd.iptc.newsml": {
"source": "iana"
},
"text/vnd.iptc.nitf": {
"source": "iana"
},
"text/vnd.latex-z": {
"source": "iana"
},
"text/vnd.motorola.reflex": {
"source": "iana"
},
"text/vnd.ms-mediapackage": {
"source": "iana"
},
"text/vnd.net2phone.commcenter.command": {
"source": "iana"
},
"text/vnd.radisys.msml-basic-layout": {
"source": "iana"
},
"text/vnd.si.uricatalogue": {
"source": "iana"
},
"text/vnd.sun.j2me.app-descriptor": {
"source": "iana",
"extensions": ["jad"]
},
"text/vnd.trolltech.linguist": {
"source": "iana"
},
"text/vnd.wap.si": {
"source": "iana"
},
"text/vnd.wap.sl": {
"source": "iana"
},
"text/vnd.wap.wml": {
"source": "iana",
"extensions": ["wml"]
},
"text/vnd.wap.wmlscript": {
"source": "iana",
"extensions": ["wmls"]
},
"text/vtt": {
"charset": "UTF-8",
"compressible": true,
"extensions": ["vtt"]
},
"text/x-asm": {
"source": "apache",
"extensions": ["s","asm"]
},
"text/x-c": {
"source": "apache",
"extensions": ["c","cc","cxx","cpp","h","hh","dic"]
},
"text/x-component": {
"source": "nginx",
"extensions": ["htc"]
},
"text/x-fortran": {
"source": "apache",
"extensions": ["f","for","f77","f90"]
},
"text/x-gwt-rpc": {
"compressible": true
},
"text/x-handlebars-template": {
"extensions": ["hbs"]
},
"text/x-java-source": {
"source": "apache",
"extensions": ["java"]
},
"text/x-jquery-tmpl": {
"compressible": true
},
"text/x-lua": {
"extensions": ["lua"]
},
"text/x-markdown": {
"compressible": true,
"extensions": ["markdown","md","mkd"]
},
"text/x-nfo": {
"source": "apache",
"extensions": ["nfo"]
},
"text/x-opml": {
"source": "apache",
"extensions": ["opml"]
},
"text/x-pascal": {
"source": "apache",
"extensions": ["p","pas"]
},
"text/x-processing": {
"compressible": true,
"extensions": ["pde"]
},
"text/x-sass": {
"extensions": ["sass"]
},
"text/x-scss": {
"extensions": ["scss"]
},
"text/x-setext": {
"source": "apache",
"extensions": ["etx"]
},
"text/x-sfv": {
"source": "apache",
"extensions": ["sfv"]
},
"text/x-suse-ymp": {
"compressible": true,
"extensions": ["ymp"]
},
"text/x-uuencode": {
"source": "apache",
"extensions": ["uu"]
},
"text/x-vcalendar": {
"source": "apache",
"extensions": ["vcs"]
},
"text/x-vcard": {
"source": "apache",
"extensions": ["vcf"]
},
"text/xml": {
"source": "iana",
"compressible": true,
"extensions": ["xml"]
},
"text/xml-external-parsed-entity": {
"source": "iana"
},
"text/yaml": {
"extensions": ["yaml","yml"]
},
"video/1d-interleaved-parityfec": {
"source": "apache"
},
"video/3gpp": {
"source": "apache",
"extensions": ["3gp","3gpp"]
},
"video/3gpp-tt": {
"source": "apache"
},
"video/3gpp2": {
"source": "apache",
"extensions": ["3g2"]
},
"video/bmpeg": {
"source": "apache"
},
"video/bt656": {
"source": "apache"
},
"video/celb": {
"source": "apache"
},
"video/dv": {
"source": "apache"
},
"video/h261": {
"source": "apache",
"extensions": ["h261"]
},
"video/h263": {
"source": "apache",
"extensions": ["h263"]
},
"video/h263-1998": {
"source": "apache"
},
"video/h263-2000": {
"source": "apache"
},
"video/h264": {
"source": "apache",
"extensions": ["h264"]
},
"video/h264-rcdo": {
"source": "apache"
},
"video/h264-svc": {
"source": "apache"
},
"video/jpeg": {
"source": "apache",
"extensions": ["jpgv"]
},
"video/jpeg2000": {
"source": "apache"
},
"video/jpm": {
"source": "apache",
"extensions": ["jpm","jpgm"]
},
"video/mj2": {
"source": "apache",
"extensions": ["mj2","mjp2"]
},
"video/mp1s": {
"source": "apache"
},
"video/mp2p": {
"source": "apache"
},
"video/mp2t": {
"source": "apache",
"extensions": ["ts"]
},
"video/mp4": {
"source": "apache",
"compressible": false,
"extensions": ["mp4","mp4v","mpg4"]
},
"video/mp4v-es": {
"source": "apache"
},
"video/mpeg": {
"source": "apache",
"compressible": false,
"extensions": ["mpeg","mpg","mpe","m1v","m2v"]
},
"video/mpeg4-generic": {
"source": "apache"
},
"video/mpv": {
"source": "apache"
},
"video/nv": {
"source": "apache"
},
"video/ogg": {
"source": "apache",
"compressible": false,
"extensions": ["ogv"]
},
"video/parityfec": {
"source": "apache"
},
"video/pointer": {
"source": "apache"
},
"video/quicktime": {
"source": "apache",
"compressible": false,
"extensions": ["qt","mov"]
},
"video/raw": {
"source": "apache"
},
"video/rtp-enc-aescm128": {
"source": "apache"
},
"video/rtx": {
"source": "apache"
},
"video/smpte292m": {
"source": "apache"
},
"video/ulpfec": {
"source": "apache"
},
"video/vc1": {
"source": "apache"
},
"video/vnd.cctv": {
"source": "apache"
},
"video/vnd.dece.hd": {
"source": "apache",
"extensions": ["uvh","uvvh"]
},
"video/vnd.dece.mobile": {
"source": "apache",
"extensions": ["uvm","uvvm"]
},
"video/vnd.dece.mp4": {
"source": "apache"
},
"video/vnd.dece.pd": {
"source": "apache",
"extensions": ["uvp","uvvp"]
},
"video/vnd.dece.sd": {
"source": "apache",
"extensions": ["uvs","uvvs"]
},
"video/vnd.dece.video": {
"source": "apache",
"extensions": ["uvv","uvvv"]
},
"video/vnd.directv.mpeg": {
"source": "apache"
},
"video/vnd.directv.mpeg-tts": {
"source": "apache"
},
"video/vnd.dlna.mpeg-tts": {
"source": "apache"
},
"video/vnd.dvb.file": {
"source": "apache",
"extensions": ["dvb"]
},
"video/vnd.fvt": {
"source": "apache",
"extensions": ["fvt"]
},
"video/vnd.hns.video": {
"source": "apache"
},
"video/vnd.iptvforum.1dparityfec-1010": {
"source": "apache"
},
"video/vnd.iptvforum.1dparityfec-2005": {
"source": "apache"
},
"video/vnd.iptvforum.2dparityfec-1010": {
"source": "apache"
},
"video/vnd.iptvforum.2dparityfec-2005": {
"source": "apache"
},
"video/vnd.iptvforum.ttsavc": {
"source": "apache"
},
"video/vnd.iptvforum.ttsmpeg2": {
"source": "apache"
},
"video/vnd.motorola.video": {
"source": "apache"
},
"video/vnd.motorola.videop": {
"source": "apache"
},
"video/vnd.mpegurl": {
"source": "apache",
"extensions": ["mxu","m4u"]
},
"video/vnd.ms-playready.media.pyv": {
"source": "apache",
"extensions": ["pyv"]
},
"video/vnd.nokia.interleaved-multimedia": {
"source": "apache"
},
"video/vnd.nokia.videovoip": {
"source": "apache"
},
"video/vnd.objectvideo": {
"source": "apache"
},
"video/vnd.sealed.mpeg1": {
"source": "apache"
},
"video/vnd.sealed.mpeg4": {
"source": "apache"
},
"video/vnd.sealed.swf": {
"source": "apache"
},
"video/vnd.sealedmedia.softseal.mov": {
"source": "apache"
},
"video/vnd.uvvu.mp4": {
"source": "apache",
"extensions": ["uvu","uvvu"]
},
"video/vnd.vivo": {
"source": "apache",
"extensions": ["viv"]
},
"video/webm": {
"source": "apache",
"compressible": false,
"extensions": ["webm"]
},
"video/x-f4v": {
"source": "apache",
"extensions": ["f4v"]
},
"video/x-fli": {
"source": "apache",
"extensions": ["fli"]
},
"video/x-flv": {
"source": "apache",
"compressible": false,
"extensions": ["flv"]
},
"video/x-m4v": {
"source": "apache",
"extensions": ["m4v"]
},
"video/x-matroska": {
"source": "apache",
"compressible": false,
"extensions": ["mkv","mk3d","mks"]
},
"video/x-mng": {
"source": "apache",
"extensions": ["mng"]
},
"video/x-ms-asf": {
"source": "apache",
"extensions": ["asf","asx"]
},
"video/x-ms-vob": {
"source": "apache",
"extensions": ["vob"]
},
"video/x-ms-wm": {
"source": "apache",
"extensions": ["wm"]
},
"video/x-ms-wmv": {
"source": "apache",
"compressible": false,
"extensions": ["wmv"]
},
"video/x-ms-wmx": {
"source": "apache",
"extensions": ["wmx"]
},
"video/x-ms-wvx": {
"source": "apache",
"extensions": ["wvx"]
},
"video/x-msvideo": {
"source": "apache",
"extensions": ["avi"]
},
"video/x-sgi-movie": {
"source": "apache",
"extensions": ["movie"]
},
"video/x-smv": {
"source": "apache",
"extensions": ["smv"]
},
"x-conference/x-cooltalk": {
"source": "apache",
"extensions": ["ice"]
},
"x-shader/x-fragment": {
"compressible": true
},
"x-shader/x-vertex": {
"compressible": true
}
}
},{}],132:[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"
];
},{}],133:[function(require,module,exports){
var team = {};
module['exports'] = team;
team.creature = require("./creature");
team.name = require("./name");
},{"./creature":132,"./name":134}],134:[function(require,module,exports){
module["exports"] = [
"#{Address.state} #{creature}"
];
},{}],135:[function(require,module,exports){
module["exports"] = [
"####",
"###",
"##",
"#"
];
},{}],136:[function(require,module,exports){
module["exports"] = [
"#{city_name}"
];
},{}],137:[function(require,module,exports){
module["exports"] = [
"Paris",
"Marseille",
"Lyon",
"Toulouse",
"Nice",
"Nantes",
"Strasbourg",
"Montpellier",
"Bordeaux",
"Lille13",
"Rennes",
"Reims",
"Le Havre",
"Saint-Étienne",
"Toulon",
"Grenoble",
"Dijon",
"Angers",
"Saint-Denis",
"Villeurbanne",
"Le Mans",
"Aix-en-Provence",
"Brest",
"Nîmes",
"Limoges",
"Clermont-Ferrand",
"Tours",
"Amiens",
"Metz",
"Perpignan",
"Besançon",
"Orléans",
"Boulogne-Billancourt",
"Mulhouse",
"Rouen",
"Caen",
"Nancy",
"Saint-Denis",
"Saint-Paul",
"Montreuil",
"Argenteuil",
"Roubaix",
"Dunkerque14",
"Tourcoing",
"Nanterre",
"Avignon",
"Créteil",
"Poitiers",
"Fort-de-France",
"Courbevoie",
"Versailles",
"Vitry-sur-Seine",
"Colombes",
"Pau",
"Aulnay-sous-Bois",
"Asnières-sur-Seine",
"Rueil-Malmaison",
"Saint-Pierre",
"Antibes",
"Saint-Maur-des-Fossés",
"Champigny-sur-Marne",
"La Rochelle",
"Aubervilliers",
"Calais",
"Cannes",
"Le Tampon",
"Béziers",
"Colmar",
"Bourges",
"Drancy",
"Mérignac",
"Saint-Nazaire",
"Valence",
"Ajaccio",
"Issy-les-Moulineaux",
"Villeneuve-d'Ascq",
"Levallois-Perret",
"Noisy-le-Grand",
"Quimper",
"La Seyne-sur-Mer",
"Antony",
"Troyes",
"Neuilly-sur-Seine",
"Sarcelles",
"Les Abymes",
"Vénissieux",
"Clichy",
"Lorient",
"Pessac",
"Ivry-sur-Seine",
"Cergy",
"Cayenne",
"Niort",
"Chambéry",
"Montauban",
"Saint-Quentin",
"Villejuif",
"Hyères",
"Beauvais",
"Cholet"
];
},{}],138:[function(require,module,exports){
module["exports"] = [
"France"
];
},{}],139:[function(require,module,exports){
var address = {};
module['exports'] = address;
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.city_name = require("./city_name");
address.city = require("./city");
address.street_suffix = require("./street_suffix");
address.street_name = require("./street_name");
address.street_address = require("./street_address");
address.default_country = require("./default_country");
},{"./building_number":135,"./city":136,"./city_name":137,"./default_country":138,"./postcode":140,"./secondary_address":141,"./state":142,"./street_address":143,"./street_name":144,"./street_prefix":145,"./street_suffix":146}],140:[function(require,module,exports){
module["exports"] = [
"#####"
];
},{}],141:[function(require,module,exports){
module["exports"] = [
"Apt. ###",
"# étage"
];
},{}],142:[function(require,module,exports){
module["exports"] = [
"Alsace",
"Aquitaine",
"Auvergne",
"Basse-Normandie",
"Bourgogne",
"Bretagne",
"Centre",
"Champagne-Ardenne",
"Corse",
"Franche-Comté",
"Haute-Normandie",
"Île-de-France",
"Languedoc-Roussillon",
"Limousin",
"Lorraine",
"Midi-Pyrénées",
"Nord-Pas-de-Calais",
"Pays de la Loire",
"Picardie",
"Poitou-Charentes",
"Provence-Alpes-Côte d'Azur",
"Rhône-Alpes"
];
},{}],143:[function(require,module,exports){
arguments[4][61][0].apply(exports,arguments)
},{"dup":61}],144:[function(require,module,exports){
module["exports"] = [
"#{street_prefix} #{street_suffix}"
];
},{}],145:[function(require,module,exports){
module["exports"] = [
"Allée, Voie",
"Rue",
"Avenue",
"Boulevard",
"Quai",
"Passage",
"Impasse",
"Place"
];
},{}],146:[function(require,module,exports){
module["exports"] = [
"de l'Abbaye",
"Adolphe Mille",
"d'Alésia",
"d'Argenteuil",
"d'Assas",
"du Bac",
"de Paris",
"La Boétie",
"Bonaparte",
"de la Bûcherie",
"de Caumartin",
"Charlemagne",
"du Chat-qui-Pêche",
"de la Chaussée-d'Antin",
"du Dahomey",
"Dauphine",
"Delesseux",
"du Faubourg Saint-Honoré",
"du Faubourg-Saint-Denis",
"de la Ferronnerie",
"des Francs-Bourgeois",
"des Grands Augustins",
"de la Harpe",
"du Havre",
"de la Huchette",
"Joubert",
"Laffitte",
"Lepic",
"des Lombards",
"Marcadet",
"Molière",
"Monsieur-le-Prince",
"de Montmorency",
"Montorgueil",
"Mouffetard",
"de Nesle",
"Oberkampf",
"de l'Odéon",
"d'Orsel",
"de la Paix",
"des Panoramas",
"Pastourelle",
"Pierre Charron",
"de la Pompe",
"de Presbourg",
"de Provence",
"de Richelieu",
"de Rivoli",
"des Rosiers",
"Royale",
"d'Abbeville",
"Saint-Honoré",
"Saint-Bernard",
"Saint-Denis",
"Saint-Dominique",
"Saint-Jacques",
"Saint-Séverin",
"des Saussaies",
"de Seine",
"de Solférino",
"Du Sommerard",
"de Tilsitt",
"Vaneau",
"de Vaugirard",
"de la Victoire",
"Zadkine"
];
},{}],147:[function(require,module,exports){
arguments[4][79][0].apply(exports,arguments)
},{"dup":79}],148:[function(require,module,exports){
arguments[4][80][0].apply(exports,arguments)
},{"dup":80}],149:[function(require,module,exports){
arguments[4][81][0].apply(exports,arguments)
},{"dup":81}],150:[function(require,module,exports){
arguments[4][82][0].apply(exports,arguments)
},{"dup":82}],151:[function(require,module,exports){
arguments[4][83][0].apply(exports,arguments)
},{"dup":83}],152:[function(require,module,exports){
arguments[4][84][0].apply(exports,arguments)
},{"./adjective":147,"./bs_adjective":148,"./bs_noun":149,"./bs_verb":150,"./descriptor":151,"./name":153,"./noun":154,"./suffix":155,"dup":84}],153:[function(require,module,exports){
module["exports"] = [
"#{Name.last_name} #{suffix}",
"#{Name.last_name} et #{Name.last_name}"
];
},{}],154:[function(require,module,exports){
arguments[4][86][0].apply(exports,arguments)
},{"dup":86}],155:[function(require,module,exports){
module["exports"] = [
"SARL",
"SA",
"EURL",
"SAS",
"SEM",
"SCOP",
"GIE",
"EI"
];
},{}],156:[function(require,module,exports){
var fr = {};
module['exports'] = fr;
fr.title = "French";
fr.address = require("./address");
fr.company = require("./company");
fr.internet = require("./internet");
fr.lorem = require("./lorem");
fr.name = require("./name");
fr.phone_number = require("./phone_number");
},{"./address":139,"./company":152,"./internet":159,"./lorem":160,"./name":164,"./phone_number":170}],157:[function(require,module,exports){
module["exports"] = [
"com",
"fr",
"eu",
"info",
"name",
"net",
"org"
];
},{}],158:[function(require,module,exports){
module["exports"] = [
"gmail.com",
"yahoo.fr",
"hotmail.fr"
];
},{}],159:[function(require,module,exports){
var internet = {};
module['exports'] = internet;
internet.free_email = require("./free_email");
internet.domain_suffix = require("./domain_suffix");
},{"./domain_suffix":157,"./free_email":158}],160:[function(require,module,exports){
arguments[4][118][0].apply(exports,arguments)
},{"./supplemental":161,"./words":162,"dup":118}],161:[function(require,module,exports){
arguments[4][119][0].apply(exports,arguments)
},{"dup":119}],162:[function(require,module,exports){
arguments[4][120][0].apply(exports,arguments)
},{"dup":120}],163:[function(require,module,exports){
module["exports"] = [
"Enzo",
"Lucas",
"Mathis",
"Nathan",
"Thomas",
"Hugo",
"Théo",
"Tom",
"Louis",
"Raphaël",
"Clément",
"Léo",
"Mathéo",
"Maxime",
"Alexandre",
"Antoine",
"Yanis",
"Paul",
"Baptiste",
"Alexis",
"Gabriel",
"Arthur",
"Jules",
"Ethan",
"Noah",
"Quentin",
"Axel",
"Evan",
"Mattéo",
"Romain",
"Valentin",
"Maxence",
"Noa",
"Adam",
"Nicolas",
"Julien",
"Mael",
"Pierre",
"Rayan",
"Victor",
"Mohamed",
"Adrien",
"Kylian",
"Sacha",
"Benjamin",
"Léa",
"Clara",
"Manon",
"Chloé",
"Camille",
"Ines",
"Sarah",
"Jade",
"Lola",
"Anaïs",
"Lucie",
"Océane",
"Lilou",
"Marie",
"Eva",
"Romane",
"Lisa",
"Zoe",
"Julie",
"Mathilde",
"Louise",
"Juliette",
"Clémence",
"Célia",
"Laura",
"Lena",
"Maëlys",
"Charlotte",
"Ambre",
"Maeva",
"Pauline",
"Lina",
"Jeanne",
"Lou",
"Noémie",
"Justine",
"Louna",
"Elisa",
"Alice",
"Emilie",
"Carla",
"Maëlle",
"Alicia",
"Mélissa"
];
},{}],164:[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":163,"./last_name":165,"./name":166,"./prefix":167,"./title":168}],165:[function(require,module,exports){
module["exports"] = [
"Martin",
"Bernard",
"Dubois",
"Thomas",
"Robert",
"Richard",
"Petit",
"Durand",
"Leroy",
"Moreau",
"Simon",
"Laurent",
"Lefebvre",
"Michel",
"Garcia",
"David",
"Bertrand",
"Roux",
"Vincent",
"Fournier",
"Morel",
"Girard",
"Andre",
"Lefevre",
"Mercier",
"Dupont",
"Lambert",
"Bonnet",
"Francois",
"Martinez",
"Legrand",
"Garnier",
"Faure",
"Rousseau",
"Blanc",
"Guerin",
"Muller",
"Henry",
"Roussel",
"Nicolas",
"Perrin",
"Morin",
"Mathieu",
"Clement",
"Gauthier",
"Dumont",
"Lopez",
"Fontaine",
"Chevalier",
"Robin",
"Masson",
"Sanchez",
"Gerard",
"Nguyen",
"Boyer",
"Denis",
"Lemaire",
"Duval",
"Joly",
"Gautier",
"Roger",
"Roche",
"Roy",
"Noel",
"Meyer",
"Lucas",
"Meunier",
"Jean",
"Perez",
"Marchand",
"Dufour",
"Blanchard",
"Marie",
"Barbier",
"Brun",
"Dumas",
"Brunet",
"Schmitt",
"Leroux",
"Colin",
"Fernandez",
"Pierre",
"Renard",
"Arnaud",
"Rolland",
"Caron",
"Aubert",
"Giraud",
"Leclerc",
"Vidal",
"Bourgeois",
"Renaud",
"Lemoine",
"Picard",
"Gaillard",
"Philippe",
"Leclercq",
"Lacroix",
"Fabre",
"Dupuis",
"Olivier",
"Rodriguez",
"Da silva",
"Hubert",
"Louis",
"Charles",
"Guillot",
"Riviere",
"Le gall",
"Guillaume",
"Adam",
"Rey",
"Moulin",
"Gonzalez",
"Berger",
"Lecomte",
"Menard",
"Fleury",
"Deschamps",
"Carpentier",
"Julien",
"Benoit",
"Paris",
"Maillard",
"Marchal",
"Aubry",
"Vasseur",
"Le roux",
"Renault",
"Jacquet",
"Collet",
"Prevost",
"Poirier",
"Charpentier",
"Royer",
"Huet",
"Baron",
"Dupuy",
"Pons",
"Paul",
"Laine",
"Carre",
"Breton",
"Remy",
"Schneider",
"Perrot",
"Guyot",
"Barre",
"Marty",
"Cousin"
];
},{}],166:[function(require,module,exports){
module["exports"] = [
"#{prefix} #{first_name} #{last_name}",
"#{first_name} #{last_name}",
"#{last_name} #{first_name}"
];
},{}],167:[function(require,module,exports){
module["exports"] = [
"M",
"Mme",
"Mlle",
"Dr",
"Prof"
];
},{}],168:[function(require,module,exports){
module["exports"] = {
"job": [
"Superviseur",
"Executif",
"Manager",
"Ingenieur",
"Specialiste",
"Directeur",
"Coordinateur",
"Administrateur",
"Architecte",
"Analyste",
"Designer",
"Technicien",
"Developpeur",
"Producteur",
"Consultant",
"Assistant",
"Agent",
"Stagiaire"
]
};
},{}],169:[function(require,module,exports){
module["exports"] = [
"01########",
"02########",
"03########",
"04########",
"05########",
"06########",
"07########",
"+33 1########",
"+33 2########",
"+33 3########",
"+33 4########",
"+33 5########",
"+33 6########",
"+33 7########"
];
},{}],170:[function(require,module,exports){
arguments[4][129][0].apply(exports,arguments)
},{"./formats":169,"dup":129}],171:[function(require,module,exports){
/**
*
* @namespace faker.lorem
*/
var Lorem = function (faker) {
var self = this;
var Helpers = faker.helpers;
/**
* word
*
* @method faker.lorem.word
* @param {number} num
*/
self.word = function (num) {
return faker.random.arrayElement(faker.definitions.lorem.words);
};
/**
* generates a space separated list of words
*
* @method faker.lorem.words
* @param {number} num number of words, defaults to 3
*/
self.words = function (num) {
if (typeof num == 'undefined') { num = 3; }
var words = [];
for (var i = 0; i < num; i++) {
words.push(faker.lorem.word());
}
return words.join(' ');
};
/**
* sentence
*
* @method faker.lorem.sentence
* @param {number} wordCount defaults to a random number between 3 and 10
* @param {number} range
*/
self.sentence = function (wordCount, range) {
if (typeof wordCount == 'undefined') { wordCount = faker.random.number({ min: 3, max: 10 }); }
// 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);
return sentence.charAt(0).toUpperCase() + sentence.slice(1) + '.';
};
/**
* sentences
*
* @method faker.lorem.sentences
* @param {number} sentenceCount defautls to a random number between 2 and 6
* @param {string} separator defaults to `' '`
*/
self.sentences = function (sentenceCount, separator) {
if (typeof sentenceCount === 'undefined') { sentenceCount = faker.random.number({ min: 2, max: 6 });}
if (typeof separator == 'undefined') { separator = " "; }
var sentences = [];
for (sentenceCount; sentenceCount > 0; sentenceCount--) {
sentences.push(faker.lorem.sentence());
}
return sentences.join(separator);
};
/**
* paragraph
*
* @method faker.lorem.paragraph
* @param {number} sentenceCount defaults to 3
*/
self.paragraph = function (sentenceCount) {
if (typeof sentenceCount == 'undefined') { sentenceCount = 3; }
return faker.lorem.sentences(sentenceCount + faker.random.number(3));
};
/**
* paragraphs
*
* @method faker.lorem.paragraphs
* @param {number} paragraphCount defaults to 3
* @param {string} separatora defaults to `'\n \r'`
*/
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);
}
/**
* returns random text based on a random lorem method
*
* @method faker.lorem.text
* @param {number} times
*/
self.text = function loremText (times) {
var loremMethods = ['lorem.word', 'lorem.words', 'lorem.sentence', 'lorem.sentences', 'lorem.paragraph', 'lorem.paragraphs', 'lorem.lines'];
var randomLoremMethod = faker.random.arrayElement(loremMethods);
return faker.fake('{{' + randomLoremMethod + '}}');
};
/**
* returns lines of lorem separated by `'\n'`
*
* @method faker.lorem.lines
* @param {number} lineCount defaults to a random number between 1 and 5
*/
self.lines = function lines (lineCount) {
if (typeof lineCount === 'undefined') { lineCount = faker.random.number({ min: 1, max: 5 });}
return faker.lorem.sentences(lineCount, '\n')
};
return self;
};
module["exports"] = Lorem;
},{}],172:[function(require,module,exports){
/**
*
* @namespace faker.name
*/
function Name (faker) {
/**
* firstName
*
* @method firstName
* @param {mixed} gender
* @memberof faker.name
*/
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);
};
/**
* lastName
*
* @method lastName
* @param {mixed} gender
* @memberof faker.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);
};
/**
* findName
*
* @method findName
* @param {string} firstName
* @param {string} lastName
* @param {mixed} gender
* @memberof faker.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(gender);
if (prefix) {
return prefix + " " + firstName + " " + lastName;
}
case 1:
suffix = faker.name.suffix(gender);
if (suffix) {
return firstName + " " + lastName + " " + suffix;
}
}
return firstName + " " + lastName;
};
/**
* jobTitle
*
* @method jobTitle
* @memberof faker.name
*/
this.jobTitle = function () {
return faker.name.jobDescriptor() + " " +
faker.name.jobArea() + " " +
faker.name.jobType();
};
/**
* prefix
*
* @method prefix
* @param {mixed} gender
* @memberof faker.name
*/
this.prefix = function (gender) {
if (typeof faker.definitions.name.male_prefix !== "undefined" && typeof faker.definitions.name.female_prefix !== "undefined") {
if (typeof gender !== 'number') {
gender = faker.random.number(1);
}
if (gender === 0) {
return faker.random.arrayElement(faker.locales[faker.locale].name.male_prefix);
} else {
return faker.random.arrayElement(faker.locales[faker.locale].name.female_prefix);
}
}
return faker.random.arrayElement(faker.definitions.name.prefix);
};
/**
* suffix
*
* @method suffix
* @memberof faker.name
*/
this.suffix = function () {
return faker.random.arrayElement(faker.definitions.name.suffix);
};
/**
* title
*
* @method title
* @memberof faker.name
*/
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;
};
/**
* jobDescriptor
*
* @method jobDescriptor
* @memberof faker.name
*/
this.jobDescriptor = function () {
return faker.random.arrayElement(faker.definitions.name.title.descriptor);
};
/**
* jobArea
*
* @method jobArea
* @memberof faker.name
*/
this.jobArea = function () {
return faker.random.arrayElement(faker.definitions.name.title.level);
};
/**
* jobType
*
* @method jobType
* @memberof faker.name
*/
this.jobType = function () {
return faker.random.arrayElement(faker.definitions.name.title.job);
};
}
module['exports'] = Name;
},{}],173:[function(require,module,exports){
/**
*
* @namespace faker.phone
*/
var Phone = function (faker) {
var self = this;
/**
* phoneNumber
*
* @method faker.phone.phoneNumber
* @param {string} format
*/
self.phoneNumber = function (format) {
format = format || faker.phone.phoneFormats();
return faker.helpers.replaceSymbolWithNumber(format);
};
// FIXME: this is strange passing in an array index.
/**
* phoneNumberFormat
*
* @method faker.phone.phoneFormatsArrayIndex
* @param phoneFormatsArrayIndex
*/
self.phoneNumberFormat = function (phoneFormatsArrayIndex) {
phoneFormatsArrayIndex = phoneFormatsArrayIndex || 0;
return faker.helpers.replaceSymbolWithNumber(faker.definitions.phone_number.formats[phoneFormatsArrayIndex]);
};
/**
* phoneFormats
*
* @method faker.phone.phoneFormats
*/
self.phoneFormats = function () {
return faker.random.arrayElement(faker.definitions.phone_number.formats);
};
return self;
};
module['exports'] = Phone;
},{}],174:[function(require,module,exports){
var mersenne = require('../vendor/mersenne');
/**
*
* @namespace faker.random
*/
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
*
* @method faker.random.number
* @param {mixed} options
*/
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
*
* @method faker.random.arrayElement
* @param {array} 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
*
* @method faker.random.objectElement
* @param {object} object
* @param {mixed} field
*/
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];
}
/**
* uuid
*
* @method faker.random.uuid
*/
this.uuid = function () {
var self = this;
var RFC4122_TEMPLATE = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
var replacePlaceholders = function (placeholder) {
var random = self.number({ min: 0, max: 15 });
var value = placeholder == 'x' ? random : (random &0x3 | 0x8);
return value.toString(16);
};
return RFC4122_TEMPLATE.replace(/[xy]/g, replacePlaceholders);
}
/**
* boolean
*
* @method faker.random.boolean
*/
this.boolean = function () {
return !!faker.random.number(1)
}
// TODO: have ability to return specific type of word? As in: noun, adjective, verb, etc
/**
* word
*
* @method faker.random.word
* @param {string} type
*/
this.word = function randomWord (type) {
var wordMethods = [
'commerce.department',
'commerce.productName',
'commerce.productAdjective',
'commerce.productMaterial',
'commerce.product',
'commerce.color',
'company.catchPhraseAdjective',
'company.catchPhraseDescriptor',
'company.catchPhraseNoun',
'company.bsAdjective',
'company.bsBuzz',
'company.bsNoun',
'address.streetSuffix',
'address.county',
'address.country',
'address.state',
'finance.accountName',
'finance.transactionType',
'finance.currencyName',
'hacker.noun',
'hacker.verb',
'hacker.adjective',
'hacker.ingverb',
'hacker.abbreviation',
'name.jobDescriptor',
'name.jobArea',
'name.jobType'];
// randomly pick from the many faker methods that can generate words
var randomWordMethod = faker.random.arrayElement(wordMethods);
return faker.fake('{{' + randomWordMethod + '}}');
}
/**
* randomWords
*
* @method faker.random.words
* @param {number} count defaults to a random value between 1 and 3
*/
this.words = function randomWords (count) {
var words = [];
if (typeof count === "undefined") {
count = faker.random.number({min:1, max: 3});
}
for (var i = 0; i<count; i++) {
words.push(faker.random.word());
}
return words.join(' ');
}
/**
* locale
*
* @method faker.random.image
*/
this.image = function randomImage () {
return faker.image.image();
}
/**
* locale
*
* @method faker.random.locale
*/
this.locale = function randomLocale () {
return faker.random.arrayElement(Object.keys(faker.locales));
};
/**
* alphaNumeric
*
* @method faker.random.alphaNumeric
*/
this.alphaNumeric = function alphaNumeric() {
return faker.random.arrayElement(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "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"]);
}
return this;
}
module['exports'] = Random;
},{"../vendor/mersenne":177}],175:[function(require,module,exports){
// generates fake data for many computer systems properties
/**
*
* @namespace faker.system
*/
function System (faker) {
/**
* generates a file name with extension or optional type
*
* @method faker.system.fileName
* @param {string} ext
* @param {string} type
*/
this.fileName = function (ext, type) {
var str = faker.fake("{{random.words}}.{{system.fileExt}}");
str = str.replace(/ /g, '_');
str = str.replace(/\,/g, '_');
str = str.replace(/\-/g, '_');
str = str.replace(/\\/g, '_');
str = str.toLowerCase();
return str;
};
/**
* commonFileName
*
* @method faker.system.commonFileName
* @param {string} ext
* @param {string} type
*/
this.commonFileName = function (ext, type) {
var str = faker.random.words() + "." + (ext || faker.system.commonFileExt());
str = str.replace(/ /g, '_');
str = str.replace(/\,/g, '_');
str = str.replace(/\-/g, '_');
str = str.replace(/\\/g, '_');
str = str.toLowerCase();
return str;
};
/**
* mimeType
*
* @method faker.system.mimeType
*/
this.mimeType = function () {
return faker.random.arrayElement(Object.keys(faker.definitions.system.mimeTypes));
};
/**
* returns a commonly used file type
*
* @method faker.system.commonFileType
*/
this.commonFileType = function () {
var types = ['video', 'audio', 'image', 'text', 'application'];
return faker.random.arrayElement(types)
};
/**
* returns a commonly used file extension based on optional type
*
* @method faker.system.commonFileExt
* @param {string} type
*/
this.commonFileExt = function (type) {
var types = [
'application/pdf',
'audio/mpeg',
'audio/wav',
'image/png',
'image/jpeg',
'image/gif',
'video/mp4',
'video/mpeg',
'text/html'
];
return faker.system.fileExt(faker.random.arrayElement(types));
};
/**
* returns any file type available as mime-type
*
* @method faker.system.fileType
*/
this.fileType = function () {
var types = [];
var mimes = faker.definitions.system.mimeTypes;
Object.keys(mimes).forEach(function(m){
var parts = m.split('/');
if (types.indexOf(parts[0]) === -1) {
types.push(parts[0]);
}
});
return faker.random.arrayElement(types);
};
/**
* fileExt
*
* @method faker.system.fileExt
* @param {string} mimeType
*/
this.fileExt = function (mimeType) {
var exts = [];
var mimes = faker.definitions.system.mimeTypes;
// get specific ext by mime-type
if (typeof mimes[mimeType] === "object") {
return faker.random.arrayElement(mimes[mimeType].extensions);
}
// reduce mime-types to those with file-extensions
Object.keys(mimes).forEach(function(m){
if (mimes[m].extensions instanceof Array) {
mimes[m].extensions.forEach(function(ext){
exts.push(ext)
});
}
});
return faker.random.arrayElement(exts);
};
/**
* not yet implemented
*
* @method faker.system.directoryPath
*/
this.directoryPath = function () {
// TODO
};
/**
* not yet implemented
*
* @method faker.system.filePath
*/
this.filePath = function () {
// TODO
};
/**
* semver
*
* @method faker.system.semver
*/
this.semver = function () {
return [faker.random.number(9),
faker.random.number(9),
faker.random.number(9)].join('.');
}
}
module['exports'] = System;
},{}],176:[function(require,module,exports){
var Faker = require('../lib');
var faker = new Faker({ locale: 'fr', localeFallback: 'en' });
faker.locales['fr'] = require('../lib/locales/fr');
faker.locales['en'] = require('../lib/locales/en');
module['exports'] = faker;
},{"../lib":45,"../lib/locales/en":112,"../lib/locales/fr":156}],177:[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);
}
},{}],178:[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));
},{}],179:[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]);
};
},{}],180:[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);
} else if (token.type === ret.types.RANGE) {
return new DRange(token.from, token.to);
} else {
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;
}
}
}
/**
* Checks if some custom properties have been set for this regexp.
*
* @param {RandExp} randexp
* @param {RegExp} regexp
*/
function checkCustom(randexp, regexp) {
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;
}
}
/**
* @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;
checkCustom(this, regexp);
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;
}
checkCustom(randexp, regexp);
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:
// Ignore lookaheads for now.
if (token.followedBy || 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 expandedSet = expand.call(this, token);
if (!expandedSet.length) { return ''; }
return String.fromCharCode(randSelect.call(this, expandedSet));
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":181,"ret":182}],181:[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;
},{}],182:[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) {
if (last.length === 0) {
repeatErr(i);
}
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":183,"./sets":184,"./types":185,"./util":186}],183:[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":185}],184:[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":185}],185:[function(require,module,exports){
module.exports = {
ROOT : 0,
GROUP : 1,
POSITION : 2,
SET : 3,
RANGE : 4,
REPETITION : 5,
REFERENCE : 6,
CHAR : 7,
};
},{}],186:[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) {
/* jshint maxlen: false */
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) :
SLSH[eslsh];
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) {
/* jshint maxlen: false */
var tokens = [];
var regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g;
var 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":184,"./types":185}],"json-schema-faker":[function(require,module,exports){
module.exports = require('../lib/')
.extend('faker', function() {
try {
return require('faker/locale/fr');
} catch (e) {
return null;
}
});
},{"../lib/":19,"faker/locale/fr":176}]},{},["json-schema-faker"])("json-schema-faker")
});
|
sajochiu/cdnjs
|
ajax/libs/json-schema-faker/0.3.5/locale/fr.js
|
JavaScript
|
mit
| 512,633
|
var asn1 = require('../asn1');
var util = require('util');
var vm = require('vm');
var api = exports;
api.define = function define(name, body) {
return new Entity(name, body);
};
function Entity(name, body) {
this.name = name;
this.body = body;
this.decoders = {};
this.encoders = {};
};
Entity.prototype._createNamed = function createNamed(base) {
var named = vm.runInThisContext('(function ' + this.name + '(entity) {\n' +
' this._initNamed(entity);\n' +
'})');
util.inherits(named, base);
named.prototype._initNamed = function initnamed(entity) {
base.call(this, entity);
};
return new named(this);
};
Entity.prototype._getDecoder = function _getDecoder(enc) {
// Lazily create decoder
if (!this.decoders.hasOwnProperty(enc))
this.decoders[enc] = this._createNamed(asn1.decoders[enc]);
return this.decoders[enc];
};
Entity.prototype.decode = function decode(data, enc, options) {
return this._getDecoder(enc).decode(data, options);
};
Entity.prototype._getEncoder = function _getEncoder(enc) {
// Lazily create encoder
if (!this.encoders.hasOwnProperty(enc))
this.encoders[enc] = this._createNamed(asn1.encoders[enc]);
return this.encoders[enc];
};
Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
return this._getEncoder(enc).encode(data, reporter);
};
|
kimisan/Presentations
|
quadrant/node_modules/browserify/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/asn1.js/lib/asn1/api.js
|
JavaScript
|
apache-2.0
| 1,355
|
/*
* file-store-test.js: Tests for the nconf File store.
*
* (C) 2011, Charlie Robbins and the Contributors.
*
*/
var fs = require('fs'),
path = require('path'),
vows = require('vows'),
assert = require('assert'),
nconf = require('../lib/nconf'),
data = require('./fixtures/data').data;
vows.describe('nconf').addBatch({
"When using the nconf": {
"should have the correct methods set": function () {
assert.isFunction(nconf.key);
assert.isFunction(nconf.path);
assert.isFunction(nconf.use);
assert.isFunction(nconf.get);
assert.isFunction(nconf.set);
assert.isFunction(nconf.clear);
assert.isFunction(nconf.load);
assert.isFunction(nconf.save);
assert.isFunction(nconf.reset);
},
"the use() method": {
"should instaniate the correct store": function () {
nconf.use('memory');
nconf.load();
assert.instanceOf(nconf.stores['memory'], nconf.Memory);
}
},
"it should": {
topic: function () {
fs.readFile(path.join(__dirname, '..', 'package.json'), this.callback);
},
"have the correct version set": function (err, data) {
assert.isNull(err);
data = JSON.parse(data.toString());
assert.equal(nconf.version, data.version);
}
}
}
}).addBatch({
"When using the nconf": {
"with the memory store": {
"the set() method": {
"should respond with true": function () {
assert.isTrue(nconf.set('foo:bar:bazz', 'buzz'));
}
},
"the get() method": {
"without a callback": {
"should respond with the correct value": function () {
assert.equal(nconf.get('foo:bar:bazz'), 'buzz');
}
},
"with a callback": {
topic: function () {
nconf.get('foo:bar:bazz', this.callback);
},
"should respond with the correct value": function (err, value) {
assert.equal(value, 'buzz');
}
}
}
}
}
}).addBatch({
"When using the nconf": {
"with the memory store": {
"the get() method": {
"should respond allow access to the root": function () {
assert(nconf.get(null));
assert(nconf.get(undefined));
assert(nconf.get());
}
},
"the set() method": {
"should respond allow access to the root and complain about non-objects": function () {
assert(!nconf.set(null, null));
assert(!nconf.set(null, undefined));
assert(!nconf.set(null));
assert(!nconf.set(null, ''));
assert(!nconf.set(null, 1));
var original = nconf.get();
assert(nconf.set(null, nconf.get()));
assert.notEqual(nconf.get(), original);
assert.deepEqual(nconf.get(), original)
}
}
}
}
}).addBatch({
"When using nconf": {
"with the memory store": {
"the clear() method": {
"should respond with the true": function () {
assert.equal(nconf.get('foo:bar:bazz'), 'buzz');
assert.isTrue(nconf.clear('foo:bar:bazz'));
assert.isTrue(typeof nconf.get('foo:bar:bazz') === 'undefined');
}
},
"the load() method": {
"without a callback": {
"should respond with the merged store": function () {
assert.deepEqual(nconf.load(), {
title: 'My specific title',
color: 'green',
movie: 'Kill Bill'
});
}
},
"with a callback": {
topic: function () {
nconf.load(this.callback.bind(null, null));
},
"should respond with the merged store": function (ign, err, store) {
assert.isNull(err);
assert.deepEqual(store, {
title: 'My specific title',
color: 'green',
movie: 'Kill Bill'
});
}
}
}
}
}
}).export(module);
|
bryce-gibson/nconf
|
test/nconf-test.js
|
JavaScript
|
mit
| 4,016
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _pure = require('recompose/pure');
var _pure2 = _interopRequireDefault(_pure);
var _SvgIcon = require('../../SvgIcon');
var _SvgIcon2 = _interopRequireDefault(_SvgIcon);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var AvAddToQueue = function AvAddToQueue(props) {
return _react2.default.createElement(
_SvgIcon2.default,
props,
_react2.default.createElement('path', { d: 'M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12zm-5-7v2h-3v3h-2v-3H8v-2h3V7h2v3h3z' })
);
};
AvAddToQueue = (0, _pure2.default)(AvAddToQueue);
AvAddToQueue.displayName = 'AvAddToQueue';
AvAddToQueue.muiName = 'SvgIcon';
exports.default = AvAddToQueue;
|
Jorginho211/TFG
|
web/node_modules/material-ui/svg-icons/av/add-to-queue.js
|
JavaScript
|
gpl-3.0
| 926
|
version https://git-lfs.github.com/spec/v1
oid sha256:2523fe5f69055ea87647d430c9d85263fa5922f797974552bb0c663728e0b693
size 2192
|
yogeshsaroya/new-cdnjs
|
ajax/libs/webshim/1.4.2/dev/shims/i18n/formcfg-pt.js
|
JavaScript
|
mit
| 129
|
/*jshint eqnull:true*/
(function (root) {
"use strict";
var GLOBAL_KEY = "Random";
var imul = (typeof Math.imul !== "function" || Math.imul(0xffffffff, 5) !== -5 ?
function (a, b) {
var ah = (a >>> 16) & 0xffff;
var al = a & 0xffff;
var bh = (b >>> 16) & 0xffff;
var bl = b & 0xffff;
// the shift by 0 fixes the sign on the high part
// the final |0 converts the unsigned value into a signed value
return (al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0;
} :
Math.imul);
var stringRepeat = (typeof String.prototype.repeat === "function" && "x".repeat(3) === "xxx" ?
function (x, y) {
return x.repeat(y);
} : function (pattern, count) {
var result = "";
while (count > 0) {
if (count & 1) {
result += pattern;
}
count >>= 1;
pattern += pattern;
}
return result;
});
function Random(engine) {
if (!(this instanceof Random)) {
return new Random(engine);
}
if (engine == null) {
engine = Random.engines.nativeMath;
} else if (typeof engine !== "function") {
throw new TypeError("Expected engine to be a function, got " + typeof engine);
}
this.engine = engine;
}
var proto = Random.prototype;
Random.engines = {
nativeMath: function () {
return (Math.random() * 0x100000000) | 0;
},
mt19937: (function (Int32Array) {
// http://en.wikipedia.org/wiki/Mersenne_twister
function refreshData(data) {
var k = 0;
var tmp = 0;
for (;
(k | 0) < 227; k = (k + 1) | 0) {
tmp = (data[k] & 0x80000000) | (data[(k + 1) | 0] & 0x7fffffff);
data[k] = data[(k + 397) | 0] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);
}
for (;
(k | 0) < 623; k = (k + 1) | 0) {
tmp = (data[k] & 0x80000000) | (data[(k + 1) | 0] & 0x7fffffff);
data[k] = data[(k - 227) | 0] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);
}
tmp = (data[623] & 0x80000000) | (data[0] & 0x7fffffff);
data[623] = data[396] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);
}
function temper(value) {
value ^= value >>> 11;
value ^= (value << 7) & 0x9d2c5680;
value ^= (value << 15) & 0xefc60000;
return value ^ (value >>> 18);
}
function seedWithArray(data, source) {
var i = 1;
var j = 0;
var sourceLength = source.length;
var k = Math.max(sourceLength, 624) | 0;
var previous = data[0] | 0;
for (;
(k | 0) > 0; --k) {
data[i] = previous = ((data[i] ^ imul((previous ^ (previous >>> 30)), 0x0019660d)) + (source[j] | 0) + (j | 0)) | 0;
i = (i + 1) | 0;
++j;
if ((i | 0) > 623) {
data[0] = data[623];
i = 1;
}
if (j >= sourceLength) {
j = 0;
}
}
for (k = 623;
(k | 0) > 0; --k) {
data[i] = previous = ((data[i] ^ imul((previous ^ (previous >>> 30)), 0x5d588b65)) - i) | 0;
i = (i + 1) | 0;
if ((i | 0) > 623) {
data[0] = data[623];
i = 1;
}
}
data[0] = 0x80000000;
}
function mt19937() {
var data = new Int32Array(624);
var index = 0;
var uses = 0;
function next() {
if ((index | 0) >= 624) {
refreshData(data);
index = 0;
}
var value = data[index];
index = (index + 1) | 0;
uses += 1;
return temper(value) | 0;
}
next.getUseCount = function() {
return uses;
};
next.discard = function (count) {
uses += count;
if ((index | 0) >= 624) {
refreshData(data);
index = 0;
}
while ((count - index) > 624) {
count -= 624 - index;
refreshData(data);
index = 0;
}
index = (index + count) | 0;
return next;
};
next.seed = function (initial) {
var previous = 0;
data[0] = previous = initial | 0;
for (var i = 1; i < 624; i = (i + 1) | 0) {
data[i] = previous = (imul((previous ^ (previous >>> 30)), 0x6c078965) + i) | 0;
}
index = 624;
uses = 0;
return next;
};
next.seedWithArray = function (source) {
next.seed(0x012bd6aa);
seedWithArray(data, source);
return next;
};
next.autoSeed = function () {
return next.seedWithArray(Random.generateEntropyArray());
};
return next;
}
return mt19937;
}(typeof Int32Array === "function" ? Int32Array : Array)),
browserCrypto: (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function" && typeof Int32Array === "function") ? (function () {
var data = null;
var index = 128;
return function () {
if (index >= 128) {
if (data === null) {
data = new Int32Array(128);
}
crypto.getRandomValues(data);
index = 0;
}
return data[index++] | 0;
};
}()) : null
};
Random.generateEntropyArray = function () {
var array = [];
var engine = Random.engines.nativeMath;
for (var i = 0; i < 16; ++i) {
array[i] = engine() | 0;
}
array.push(new Date().getTime() | 0);
return array;
};
function returnValue(value) {
return function () {
return value;
};
}
// [-0x80000000, 0x7fffffff]
Random.int32 = function (engine) {
return engine() | 0;
};
proto.int32 = function () {
return Random.int32(this.engine);
};
// [0, 0xffffffff]
Random.uint32 = function (engine) {
return engine() >>> 0;
};
proto.uint32 = function () {
return Random.uint32(this.engine);
};
// [0, 0x1fffffffffffff]
Random.uint53 = function (engine) {
var high = engine() & 0x1fffff;
var low = engine() >>> 0;
return (high * 0x100000000) + low;
};
proto.uint53 = function () {
return Random.uint53(this.engine);
};
// [0, 0x20000000000000]
Random.uint53Full = function (engine) {
while (true) {
var high = engine() | 0;
if (high & 0x200000) {
if ((high & 0x3fffff) === 0x200000 && (engine() | 0) === 0) {
return 0x20000000000000;
}
} else {
var low = engine() >>> 0;
return ((high & 0x1fffff) * 0x100000000) + low;
}
}
};
proto.uint53Full = function () {
return Random.uint53Full(this.engine);
};
// [-0x20000000000000, 0x1fffffffffffff]
Random.int53 = function (engine) {
var high = engine() | 0;
var low = engine() >>> 0;
return ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);
};
proto.int53 = function () {
return Random.int53(this.engine);
};
// [-0x20000000000000, 0x20000000000000]
Random.int53Full = function (engine) {
while (true) {
var high = engine() | 0;
if (high & 0x400000) {
if ((high & 0x7fffff) === 0x400000 && (engine() | 0) === 0) {
return 0x20000000000000;
}
} else {
var low = engine() >>> 0;
return ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);
}
}
};
proto.int53Full = function () {
return Random.int53Full(this.engine);
};
function add(generate, addend) {
if (addend === 0) {
return generate;
} else {
return function (engine) {
return generate(engine) + addend;
};
}
}
Random.integer = (function () {
function isPowerOfTwoMinusOne(value) {
return ((value + 1) & value) === 0;
}
function bitmask(masking) {
return function (engine) {
return engine() & masking;
};
}
function downscaleToLoopCheckedRange(range) {
var extendedRange = range + 1;
var maximum = extendedRange * Math.floor(0x100000000 / extendedRange);
return function (engine) {
var value = 0;
do {
value = engine() >>> 0;
} while (value >= maximum);
return value % extendedRange;
};
}
function downscaleToRange(range) {
if (isPowerOfTwoMinusOne(range)) {
return bitmask(range);
} else {
return downscaleToLoopCheckedRange(range);
}
}
function isEvenlyDivisibleByMaxInt32(value) {
return (value | 0) === 0;
}
function upscaleWithHighMasking(masking) {
return function (engine) {
var high = engine() & masking;
var low = engine() >>> 0;
return (high * 0x100000000) + low;
};
}
function upscaleToLoopCheckedRange(extendedRange) {
var maximum = extendedRange * Math.floor(0x20000000000000 / extendedRange);
return function (engine) {
var ret = 0;
do {
var high = engine() & 0x1fffff;
var low = engine() >>> 0;
ret = (high * 0x100000000) + low;
} while (ret >= maximum);
return ret % extendedRange;
};
}
function upscaleWithinU53(range) {
var extendedRange = range + 1;
if (isEvenlyDivisibleByMaxInt32(extendedRange)) {
var highRange = ((extendedRange / 0x100000000) | 0) - 1;
if (isPowerOfTwoMinusOne(highRange)) {
return upscaleWithHighMasking(highRange);
}
}
return upscaleToLoopCheckedRange(extendedRange);
}
function upscaleWithinI53AndLoopCheck(min, max) {
return function (engine) {
var ret = 0;
do {
var high = engine() | 0;
var low = engine() >>> 0;
ret = ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);
} while (ret < min || ret > max);
return ret;
};
}
return function (min, max) {
min = Math.floor(min);
max = Math.floor(max);
if (min < -0x20000000000000 || !isFinite(min)) {
throw new RangeError("Expected min to be at least " + (-0x20000000000000));
} else if (max > 0x20000000000000 || !isFinite(max)) {
throw new RangeError("Expected max to be at most " + 0x20000000000000);
}
var range = max - min;
if (range <= 0 || !isFinite(range)) {
return returnValue(min);
} else if (range === 0xffffffff) {
if (min === 0) {
return Random.uint32;
} else {
return add(Random.int32, min + 0x80000000);
}
} else if (range < 0xffffffff) {
return add(downscaleToRange(range), min);
} else if (range === 0x1fffffffffffff) {
return add(Random.uint53, min);
} else if (range < 0x1fffffffffffff) {
return add(upscaleWithinU53(range), min);
} else if (max - 1 - min === 0x1fffffffffffff) {
return add(Random.uint53Full, min);
} else if (min === -0x20000000000000 && max === 0x20000000000000) {
return Random.int53Full;
} else if (min === -0x20000000000000 && max === 0x1fffffffffffff) {
return Random.int53;
} else if (min === -0x1fffffffffffff && max === 0x20000000000000) {
return add(Random.int53, 1);
} else if (max === 0x20000000000000) {
return add(upscaleWithinI53AndLoopCheck(min - 1, max - 1), 1);
} else {
return upscaleWithinI53AndLoopCheck(min, max);
}
};
}());
proto.integer = function (min, max) {
return Random.integer(min, max)(this.engine);
};
// [0, 1] (floating point)
Random.realZeroToOneInclusive = function (engine) {
return Random.uint53Full(engine) / 0x20000000000000;
};
proto.realZeroToOneInclusive = function () {
return Random.realZeroToOneInclusive(this.engine);
};
// [0, 1) (floating point)
Random.realZeroToOneExclusive = function (engine) {
return Random.uint53(engine) / 0x20000000000000;
};
proto.realZeroToOneExclusive = function () {
return Random.realZeroToOneExclusive(this.engine);
};
Random.real = (function () {
function multiply(generate, multiplier) {
if (multiplier === 1) {
return generate;
} else if (multiplier === 0) {
return function () {
return 0;
};
} else {
return function (engine) {
return generate(engine) * multiplier;
};
}
}
return function (left, right, inclusive) {
if (!isFinite(left)) {
throw new RangeError("Expected left to be a finite number");
} else if (!isFinite(right)) {
throw new RangeError("Expected right to be a finite number");
}
return add(
multiply(
inclusive ? Random.realZeroToOneInclusive : Random.realZeroToOneExclusive,
right - left),
left);
};
}());
proto.real = function (min, max, inclusive) {
return Random.real(min, max, inclusive)(this.engine);
};
Random.bool = (function () {
function isLeastBitTrue(engine) {
return (engine() & 1) === 1;
}
function lessThan(generate, value) {
return function (engine) {
return generate(engine) < value;
};
}
function probability(percentage) {
if (percentage <= 0) {
return returnValue(false);
} else if (percentage >= 1) {
return returnValue(true);
} else {
var scaled = percentage * 0x100000000;
if (scaled % 1 === 0) {
return lessThan(Random.int32, (scaled - 0x80000000) | 0);
} else {
return lessThan(Random.uint53, Math.round(percentage * 0x20000000000000));
}
}
}
return function (numerator, denominator) {
if (denominator == null) {
if (numerator == null) {
return isLeastBitTrue;
}
return probability(numerator);
} else {
if (numerator <= 0) {
return returnValue(false);
} else if (numerator >= denominator) {
return returnValue(true);
}
return lessThan(Random.integer(0, denominator - 1), numerator);
}
};
}());
proto.bool = function (numerator, denominator) {
return Random.bool(numerator, denominator)(this.engine);
};
function toInteger(value) {
var number = +value;
if (number < 0) {
return Math.ceil(number);
} else {
return Math.floor(number);
}
}
function convertSliceArgument(value, length) {
if (value < 0) {
return Math.max(value + length, 0);
} else {
return Math.min(value, length);
}
}
Random.pick = function (engine, array, begin, end) {
var length = array.length;
var start = begin == null ? 0 : convertSliceArgument(toInteger(begin), length);
var finish = end === void 0 ? length : convertSliceArgument(toInteger(end), length);
if (start >= finish) {
return void 0;
}
var distribution = Random.integer(start, finish - 1);
return array[distribution(engine)];
};
proto.pick = function (array, begin, end) {
return Random.pick(this.engine, array, begin, end);
};
function returnUndefined() {
return void 0;
}
var slice = Array.prototype.slice;
Random.picker = function (array, begin, end) {
var clone = slice.call(array, begin, end);
if (!clone.length) {
return returnUndefined;
}
var distribution = Random.integer(0, clone.length - 1);
return function (engine) {
return clone[distribution(engine)];
};
};
Random.shuffle = function (engine, array, downTo) {
var length = array.length;
if (length) {
if (downTo == null) {
downTo = 0;
}
for (var i = (length - 1) >>> 0; i > downTo; --i) {
var distribution = Random.integer(0, i);
var j = distribution(engine);
if (i !== j) {
var tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
}
return array;
};
proto.shuffle = function (array) {
return Random.shuffle(this.engine, array);
};
Random.sample = function (engine, population, sampleSize) {
if (sampleSize < 0 || sampleSize > population.length || !isFinite(sampleSize)) {
throw new RangeError("Expected sampleSize to be within 0 and the length of the population");
}
if (sampleSize === 0) {
return [];
}
var clone = slice.call(population);
var length = clone.length;
if (length === sampleSize) {
return Random.shuffle(engine, clone, 0);
}
var tailLength = length - sampleSize;
return Random.shuffle(engine, clone, tailLength - 1).slice(tailLength);
};
proto.sample = function (population, sampleSize) {
return Random.sample(this.engine, population, sampleSize);
};
Random.die = function (sideCount) {
return Random.integer(1, sideCount);
};
proto.die = function (sideCount) {
return Random.die(sideCount)(this.engine);
};
Random.dice = function (sideCount, dieCount) {
var distribution = Random.die(sideCount);
return function (engine) {
var result = [];
result.length = dieCount;
for (var i = 0; i < dieCount; ++i) {
result[i] = distribution(engine);
}
return result;
};
};
proto.dice = function (sideCount, dieCount) {
return Random.dice(sideCount, dieCount)(this.engine);
};
// http://en.wikipedia.org/wiki/Universally_unique_identifier
Random.uuid4 = (function () {
function zeroPad(string, zeroCount) {
return stringRepeat("0", zeroCount - string.length) + string;
}
return function (engine) {
var a = engine() >>> 0;
var b = engine() | 0;
var c = engine() | 0;
var d = engine() >>> 0;
return (
zeroPad(a.toString(16), 8) +
"-" +
zeroPad((b & 0xffff).toString(16), 4) +
"-" +
zeroPad((((b >> 4) & 0x0fff) | 0x4000).toString(16), 4) +
"-" +
zeroPad(((c & 0x3fff) | 0x8000).toString(16), 4) +
"-" +
zeroPad(((c >> 4) & 0xffff).toString(16), 4) +
zeroPad(d.toString(16), 8));
};
}());
proto.uuid4 = function () {
return Random.uuid4(this.engine);
};
Random.string = (function () {
// has 2**x chars, for faster uniform distribution
var DEFAULT_STRING_POOL = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
return function (pool) {
if (pool == null) {
pool = DEFAULT_STRING_POOL;
}
var length = pool.length;
if (!length) {
throw new Error("Expected pool not to be an empty string");
}
var distribution = Random.integer(0, length - 1);
return function (engine, length) {
var result = "";
for (var i = 0; i < length; ++i) {
var j = distribution(engine);
result += pool.charAt(j);
}
return result;
};
};
}());
proto.string = function (length, pool) {
return Random.string(pool)(this.engine, length);
};
Random.hex = (function () {
var LOWER_HEX_POOL = "0123456789abcdef";
var lowerHex = Random.string(LOWER_HEX_POOL);
var upperHex = Random.string(LOWER_HEX_POOL.toUpperCase());
return function (upper) {
if (upper) {
return upperHex;
} else {
return lowerHex;
}
};
}());
proto.hex = function (length, upper) {
return Random.hex(upper)(this.engine, length);
};
Random.date = function (start, end) {
if (!(start instanceof Date)) {
throw new TypeError("Expected start to be a Date, got " + typeof start);
} else if (!(end instanceof Date)) {
throw new TypeError("Expected end to be a Date, got " + typeof end);
}
var distribution = Random.integer(start.getTime(), end.getTime());
return function (engine) {
return new Date(distribution(engine));
};
};
proto.date = function (start, end) {
return Random.date(start, end)(this.engine);
};
if (typeof define === "function" && define.amd) {
define(function () {
return Random;
});
} else if (typeof module !== "undefined" && typeof require === "function") {
module.exports = Random;
} else {
(function () {
var oldGlobal = root[GLOBAL_KEY];
Random.noConflict = function () {
root[GLOBAL_KEY] = oldGlobal;
return this;
};
}());
root[GLOBAL_KEY] = Random;
}
}(this));
|
michapixel/xkcd_pwd_gen
|
src/vendor/js/random/lib/random.js
|
JavaScript
|
mit
| 20,534
|
YUI.add('paginator-core', function (Y, NAME) {
/**
Paginator's core functionality consists of keeping track of the current page
being displayed and providing information for previous and next pages.
@module paginator
@submodule paginator-core
@since 3.11.0
*/
/**
_API docs for this extension are included in the Paginator class._
Class extension providing the core API and structure for the Paginator module.
Use this class extension with Widget or another Base-based superclass to
create the basic Paginator model API and composing class structure.
@class Paginator.Core
@for Paginator
@since 3.11.0
*/
var PaginatorCore = Y.namespace('Paginator').Core = function () {};
PaginatorCore.ATTRS = {
/**
Current page count. First page is 1.
@attribute page
@type Number
@default 1
**/
page: {
value: 1
},
/**
Total number of pages to display
@readOnly
@attribute totalPages
@type Number
**/
totalPages: {
readOnly: true,
getter: '_getTotalPagesFn'
},
/**
Maximum number of items per page. A value of negative one (-1) indicates
all items on one page.
@attribute itemsPerPage
@type Number
@default 10
**/
itemsPerPage: {
value: 10
},
/**
Total number of items in all pages.
@attribute totalItems
@type Number
@default 0
**/
totalItems: {
value: 0
}
};
Y.mix(PaginatorCore.prototype, {
/**
Sets the page to the previous page in the set, if there is a previous page.
@method prevPage
@chainable
*/
prevPage: function () {
if (this.hasPrevPage()) {
this.set('page', this.get('page') - 1);
}
return this;
},
/**
Sets the page to the next page in the set, if there is a next page.
@method nextPage
@chainable
*/
nextPage: function () {
if (this.hasNextPage()) {
this.set('page', this.get('page') + 1);
}
return this;
},
/**
Returns True if there is a previous page in the set.
@method hasPrevPage
@return {Boolean} `true` if there is a previous page, `false` otherwise.
*/
hasPrevPage: function () {
return this.get('page') > 1;
},
/**
Returns True if there is a next page in the set.
If totalItems isn't set, assume there is always next page.
@method hasNextPage
@return {Boolean} `true` if there is a next page, `false` otherwise.
*/
hasNextPage: function () {
return (!this.get('totalItems') || this.get('page') < this.get('totalPages'));
},
//--- P R O T E C T E D
/**
Returns the total number of pages based on the total number of
items provided and the number of items per page
@protected
@method _getTotalPagesFn
@return {Number} Total number of pages based on total number of items and
items per page or one if itemsPerPage is less than one
*/
_getTotalPagesFn: function () {
var itemsPerPage = this.get('itemsPerPage');
return (itemsPerPage < 1) ? 1 : Math.ceil(this.get('totalItems') / itemsPerPage);
}
});
}, '3.14.1', {"requires": ["base"]});
|
aqt01/math_problems
|
node_modules/yui/paginator-core/paginator-core.js
|
JavaScript
|
gpl-2.0
| 3,282
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v4.2.2
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var context_1 = require("./context/context");
var constants_1 = require("./constants");
var columnController_1 = require("./columnController/columnController");
var floatingRowModel_1 = require("./rowControllers/floatingRowModel");
var utils_1 = require("./utils");
var gridRow_1 = require("./entities/gridRow");
var gridCell_1 = require("./entities/gridCell");
var CellNavigationService = (function () {
function CellNavigationService() {
}
CellNavigationService.prototype.getNextCellToFocus = function (key, lastCellToFocus) {
switch (key) {
case constants_1.Constants.KEY_UP: return this.getCellAbove(lastCellToFocus);
case constants_1.Constants.KEY_DOWN: return this.getCellBelow(lastCellToFocus);
case constants_1.Constants.KEY_RIGHT: return this.getCellToRight(lastCellToFocus);
case constants_1.Constants.KEY_LEFT: return this.getCellToLeft(lastCellToFocus);
default: console.log('ag-Grid: unknown key for navigation ' + key);
}
};
CellNavigationService.prototype.getCellToLeft = function (lastCell) {
var colToLeft = this.columnController.getDisplayedColBefore(lastCell.column);
if (!colToLeft) {
return null;
}
else {
return new gridCell_1.GridCell(lastCell.rowIndex, lastCell.floating, colToLeft);
}
};
CellNavigationService.prototype.getCellToRight = function (lastCell) {
var colToRight = this.columnController.getDisplayedColAfter(lastCell.column);
// if already on right, do nothing
if (!colToRight) {
return null;
}
else {
return new gridCell_1.GridCell(lastCell.rowIndex, lastCell.floating, colToRight);
}
};
CellNavigationService.prototype.getRowBelow = function (lastRow) {
// if already on top row, do nothing
if (this.isLastRowInContainer(lastRow)) {
if (lastRow.isFloatingBottom()) {
return null;
}
else if (lastRow.isNotFloating()) {
if (this.floatingRowModel.isRowsToRender(constants_1.Constants.FLOATING_BOTTOM)) {
return new gridRow_1.GridRow(0, constants_1.Constants.FLOATING_BOTTOM);
}
else {
return null;
}
}
else {
if (this.rowModel.isRowsToRender()) {
return new gridRow_1.GridRow(0, null);
}
else if (this.floatingRowModel.isRowsToRender(constants_1.Constants.FLOATING_BOTTOM)) {
return new gridRow_1.GridRow(0, constants_1.Constants.FLOATING_BOTTOM);
}
else {
return null;
}
}
}
else {
return new gridRow_1.GridRow(lastRow.rowIndex + 1, lastRow.floating);
}
};
CellNavigationService.prototype.getCellBelow = function (lastCell) {
var rowBelow = this.getRowBelow(lastCell.getGridRow());
if (rowBelow) {
return new gridCell_1.GridCell(rowBelow.rowIndex, rowBelow.floating, lastCell.column);
}
else {
return null;
}
};
CellNavigationService.prototype.isLastRowInContainer = function (gridRow) {
if (gridRow.isFloatingTop()) {
var lastTopIndex = this.floatingRowModel.getFloatingTopRowData().length - 1;
return lastTopIndex === gridRow.rowIndex;
}
else if (gridRow.isFloatingBottom()) {
var lastBottomIndex = this.floatingRowModel.getFloatingBottomRowData().length - 1;
return lastBottomIndex === gridRow.rowIndex;
}
else {
var lastBodyIndex = this.rowModel.getRowCount() - 1;
return lastBodyIndex === gridRow.rowIndex;
}
};
CellNavigationService.prototype.getRowAbove = function (lastRow) {
// if already on top row, do nothing
if (lastRow.rowIndex === 0) {
if (lastRow.isFloatingTop()) {
return null;
}
else if (lastRow.isNotFloating()) {
if (this.floatingRowModel.isRowsToRender(constants_1.Constants.FLOATING_TOP)) {
return this.getLastFloatingTopRow();
}
else {
return null;
}
}
else {
// last floating bottom
if (this.rowModel.isRowsToRender()) {
return this.getLastBodyCell();
}
else if (this.floatingRowModel.isRowsToRender(constants_1.Constants.FLOATING_TOP)) {
return this.getLastFloatingTopRow();
}
else {
return null;
}
}
}
else {
return new gridRow_1.GridRow(lastRow.rowIndex - 1, lastRow.floating);
}
};
CellNavigationService.prototype.getCellAbove = function (lastCell) {
var rowAbove = this.getRowAbove(lastCell.getGridRow());
if (rowAbove) {
return new gridCell_1.GridCell(rowAbove.rowIndex, rowAbove.floating, lastCell.column);
}
else {
return null;
}
};
CellNavigationService.prototype.getLastBodyCell = function () {
var lastBodyRow = this.rowModel.getRowCount() - 1;
return new gridRow_1.GridRow(lastBodyRow, null);
};
CellNavigationService.prototype.getLastFloatingTopRow = function () {
var lastFloatingRow = this.floatingRowModel.getFloatingTopRowData().length - 1;
return new gridRow_1.GridRow(lastFloatingRow, constants_1.Constants.FLOATING_TOP);
};
CellNavigationService.prototype.getNextTabbedCell = function (gridCell, backwards) {
if (backwards) {
return this.getNextTabbedCellBackwards(gridCell);
}
else {
return this.getNextTabbedCellForwards(gridCell);
}
};
CellNavigationService.prototype.getNextTabbedCellForwards = function (gridCell) {
var displayedColumns = this.columnController.getAllDisplayedColumns();
var newRowIndex = gridCell.rowIndex;
var newFloating = gridCell.floating;
// move along to the next cell
var newColumn = this.columnController.getDisplayedColAfter(gridCell.column);
// check if end of the row, and if so, go forward a row
if (!newColumn) {
newColumn = displayedColumns[0];
var rowBelow = this.getRowBelow(gridCell.getGridRow());
if (utils_1.Utils.missing(rowBelow)) {
return;
}
newRowIndex = rowBelow.rowIndex;
newFloating = rowBelow.floating;
}
return new gridCell_1.GridCell(newRowIndex, newFloating, newColumn);
};
CellNavigationService.prototype.getNextTabbedCellBackwards = function (gridCell) {
var displayedColumns = this.columnController.getAllDisplayedColumns();
var newRowIndex = gridCell.rowIndex;
var newFloating = gridCell.floating;
// move along to the next cell
var newColumn = this.columnController.getDisplayedColBefore(gridCell.column);
// check if end of the row, and if so, go forward a row
if (!newColumn) {
newColumn = displayedColumns[displayedColumns.length - 1];
var rowAbove = this.getRowAbove(gridCell.getGridRow());
if (utils_1.Utils.missing(rowAbove)) {
return;
}
newRowIndex = rowAbove.rowIndex;
newFloating = rowAbove.floating;
}
return new gridCell_1.GridCell(newRowIndex, newFloating, newColumn);
};
__decorate([
context_1.Autowired('columnController'),
__metadata('design:type', columnController_1.ColumnController)
], CellNavigationService.prototype, "columnController", void 0);
__decorate([
context_1.Autowired('rowModel'),
__metadata('design:type', Object)
], CellNavigationService.prototype, "rowModel", void 0);
__decorate([
context_1.Autowired('floatingRowModel'),
__metadata('design:type', floatingRowModel_1.FloatingRowModel)
], CellNavigationService.prototype, "floatingRowModel", void 0);
CellNavigationService = __decorate([
context_1.Bean('cellNavigationService'),
__metadata('design:paramtypes', [])
], CellNavigationService);
return CellNavigationService;
})();
exports.CellNavigationService = CellNavigationService;
|
seogi1004/cdnjs
|
ajax/libs/ag-grid/4.2.3/lib/cellNavigationService.js
|
JavaScript
|
mit
| 9,583
|
/**
* A dialogue type designed to display a confirmation to the user.
*
* @module moodle-core-notification
* @submodule moodle-core-notification-confirm
*/
var CONFIRM_NAME = 'Moodle confirmation dialogue',
CONFIRM;
/**
* Extends core Dialogue to show the confirmation dialogue.
*
* @param {Object} config Object literal specifying the dialogue configuration properties.
* @constructor
* @class M.core.confirm
* @extends M.core.dialogue
*/
CONFIRM = function(config) {
CONFIRM.superclass.constructor.apply(this, [config]);
};
Y.extend(CONFIRM, M.core.notification.info, {
/**
* The list of events to detach when destroying this dialogue.
*
* @property _closeEvents
* @type EventHandle[]
* @private
*/
_closeEvents: null,
/**
* A reference to the yes button.
*
* @property _yesButton
* @type Node
* @private
*/
_yesButton: null,
/**
* A reference to the No button.
*
* @property _noButton
* @type Node
* @private
*/
_noButton: null,
/**
* A reference to the Question.
*
* @property _question
* @type Node
* @private
*/
_question: null,
initializer: function() {
this._closeEvents = [];
this.publish('complete');
this.publish('complete-yes');
this.publish('complete-no');
this._yesButton = Y.Node.create('<input type="button" class="btn btn-primary" id="id_yuiconfirmyes-' +
this.get('COUNT') + '" value="' + this.get(CONFIRMYES) + '" />');
this._noButton = Y.Node.create('<input type="button" class="btn btn-secondary" id="id_yuiconfirmno-' +
this.get('COUNT') + '" value="' + this.get(CONFIRMNO) + '" />');
this._question = Y.Node.create('<div class="confirmation-message">' + this.get(QUESTION) + '</div>');
var content = Y.Node.create('<div class="confirmation-dialogue"></div>')
.append(this._question)
.append(Y.Node.create('<div class="confirmation-buttons form-inline justify-content-around"></div>')
.append(this._yesButton)
.append(this._noButton));
this.get(BASE).addClass('moodle-dialogue-confirm');
this.setStdModContent(Y.WidgetStdMod.BODY, content, Y.WidgetStdMod.REPLACE);
this.setStdModContent(Y.WidgetStdMod.HEADER,
'<h5 id="moodle-dialogue-' + this.get('COUNT') + '-wrap-header-text">' + this.get(TITLE) + '</h5>',
Y.WidgetStdMod.REPLACE);
this._closeEvents.push(
Y.on('key', this.submit, window, 'down:27', this, false),
this._yesButton.on('click', this.submit, this, true),
this._noButton.on('click', this.submit, this, false)
);
var closeButton = this.get('boundingBox').one('.closebutton');
if (closeButton) {
// The close button should act exactly like the 'No' button.
this._closeEvents.push(
closeButton.on('click', this.submit, this)
);
}
},
submit: function(e, outcome) {
new Y.EventHandle(this._closeEvents).detach();
this.fire('complete', outcome);
if (outcome) {
this.fire('complete-yes');
} else {
this.fire('complete-no');
}
this.hide();
this.destroy();
}
}, {
NAME: CONFIRM_NAME,
CSS_PREFIX: DIALOGUE_PREFIX,
ATTRS: {
/**
* The button text to use to accept the confirmation.
*
* @attribute yesLabel
* @type String
* @default 'Yes'
*/
yesLabel: {
validator: Y.Lang.isString,
valueFn: function() {
return M.util.get_string('yes', 'moodle');
},
setter: function(value) {
if (this._yesButton) {
this._yesButton.set('value', value);
}
return value;
}
},
/**
* The button text to use to reject the confirmation.
*
* @attribute noLabel
* @type String
* @default 'No'
*/
noLabel: {
validator: Y.Lang.isString,
valueFn: function() {
return M.util.get_string('no', 'moodle');
},
setter: function(value) {
if (this._noButton) {
this._noButton.set('value', value);
}
return value;
}
},
/**
* The title of the dialogue.
*
* @attribute title
* @type String
* @default 'Confirm'
*/
title: {
validator: Y.Lang.isString,
value: M.util.get_string('confirm', 'moodle')
},
/**
* The question posed by the dialogue.
*
* @attribute question
* @type String
* @default 'Are you sure?'
*/
question: {
validator: Y.Lang.isString,
valueFn: function() {
return M.util.get_string('areyousure', 'moodle');
},
setter: function(value) {
if (this._question) {
this._question.set('value', value);
}
return value;
}
}
}
});
Y.augment(CONFIRM, Y.EventTarget);
M.core.confirm = CONFIRM;
|
michael-milette/moodle
|
lib/yui/src/notification/js/confirm.js
|
JavaScript
|
gpl-3.0
| 5,579
|
(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._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: 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', {
dataSet: 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 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(); }
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(); }
}
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');
this.chainSend('update', {
query: query,
update: update,
dataSet: updated
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
if (callback) { callback(); }
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(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(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.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');
self.chainSend('insert', {
dataSet: [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('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) {
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.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({
/**
* 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');
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.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 (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":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 + '"');
}
}
};
/**
* 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);
};
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":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;
};
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;
};
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 = {
/**
*
* @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
},
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,
/**
* 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;
},
/**
* Generates a unique hash for the passed object.
* @param {Object} obj The object to generate a hash for.
* @returns {String}
*/
hash: function (obj) {
return this.jStringify(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;
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;
},{}],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) {
// 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":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 + '"');
}
},
/**
* 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 {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;
},{}],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];
}
delete 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;
} 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) {
// 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":77}],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":78}],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 () {
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) {
if (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;
},{}],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.650',
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":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) {
self._handleChainIO_ActiveJoin(chainPacket, sharedData);
}
if (hasActiveQuery) {
self._handleChainIO_ActiveQuery(chainPacket, sharedData);
}
if (hasTransformIn) {
self._handleChainIO_TransformIn(chainPacket, sharedData);
}
// 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) {
self._handleChainIO_RemovePackets(this, chainPacket, sharedData);
}
if (sharedData.dataArr.length) {
self._handleChainIO_UpsertPackets(this, chainPacket, sharedData);
}
// 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');
}
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);
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();
}
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._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();
}
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;
};
/**
* 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.
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 (!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":76}],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);
words[nBytes >>> 2] |= (bits1 | bits2) << (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){
// 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; };
},{}],77:[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":76}],78:[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":79,"./lib/inflate":80,"./lib/utils/common":81,"./lib/zlib/constants":84}],79:[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":81,"./utils/strings":82,"./zlib/deflate.js":86,"./zlib/messages":91,"./zlib/zstream":93}],80:[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":81,"./utils/strings":82,"./zlib/constants":84,"./zlib/gzheader":87,"./zlib/inflate.js":89,"./zlib/messages":91,"./zlib/zstream":93}],81:[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);
},{}],82:[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":81}],83:[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;
},{}],84:[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
};
},{}],85:[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;
},{}],86:[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":81,"./adler32":83,"./crc32":85,"./messages":91,"./trees":92}],87:[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;
},{}],88:[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;
};
},{}],89:[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":81,"./adler32":83,"./crc32":85,"./inffast":88,"./inftrees":90}],90:[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":81}],91:[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) */
};
},{}],92:[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":81}],93:[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]);
|
dakshshah96/cdnjs
|
ajax/libs/forerunnerdb/1.3.650/fdb-legacy.js
|
JavaScript
|
mit
| 982,325
|
// (C) Copyright 2015 Martin Dougiamas
//
// Licensed 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.
angular.module('mm.addons.mod_quiz')
/**
* Service to handle quiz autosave. Only 1 autosave can be running at the same time.
*
* @module mm.addons.mod_quiz
* @ngdoc service
* @name $mmaModQuizAutoSave
*/
.factory('$mmaModQuizAutoSave', function($log, $timeout, $mmaModQuiz, $interval, $mmQuestionHelper,
mmaModQuizCheckChangesInterval) {
$log = $log.getInstance('$mmaModQuizAutoSave');
var self = {},
autoSavePromise,
loadPreviousAnswersPromise,
checkChangesProcess,
previousAnswers,
formName,
popoverName,
offline,
connectionErrorButtonSelector;
/**
* Cancel a pending auto save.
*
* @module mm.addons.mod_quiz
* @ngdoc method
* @name $mmaModQuizAutoSave#cancelAutoSave
* @return {Void}
*/
self.cancelAutoSave = function() {
if (autoSavePromise) {
$timeout.cancel(autoSavePromise);
}
autoSavePromise = undefined;
};
/**
* Check if the answers have changed in a page.
*
* @module mm.addons.mod_quiz
* @ngdoc method
* @name $mmaModQuizAutoSave#checkChanges
* @param {Object} scope Scope.
* @param {Object} quiz Quiz.
* @param {Object} attempt Attempt.
* @return {Void}
*/
self.checkChanges = function(scope, quiz, attempt) {
var answers,
equal = true;
if (scope.showSummary || autoSavePromise) {
// Summary is being shown or we already have an auto save pending, no need to check changes.
return;
}
answers = getAnswers();
if (!previousAnswers) {
// Previous answers isn't set, set it now.
previousAnswers = answers;
} else {
// Check if answers have changed.
angular.forEach(answers, function(value, name) {
if (previousAnswers[name] != value) {
equal = false;
}
});
if (!equal) {
self.setAutoSaveTimer(scope, quiz, attempt);
previousAnswers = answers;
}
}
};
/**
* Hide the auto save error.
*
* @module mm.addons.mod_quiz
* @ngdoc method
* @name $mmaModQuizAutoSave#hideAutoSaveError
* @param {Object} scope Scope.
* @return {Void}
*/
self.hideAutoSaveError = function(scope) {
scope.autoSaveError = false;
if (scope[popoverName]) {
scope[popoverName].hide();
}
};
/**
* Get answers from a form.
*
* @return {Object} Answers.
*/
function getAnswers() {
return $mmQuestionHelper.getAnswersFromForm(document.forms[formName]);
}
/**
* Init the auto save process.
*
* @module mm.addons.mod_quiz
* @ngdoc method
* @name $mmaModQuizAutoSave#init
* @param {Object} scope Scope.
* @param {String} formNm Name of the form to get the answers from.
* @param {String} popoverNm Name of the connection error popover in the scope.
* This popover will be shown when there's a connection error.
* @param {String} connErrorButtonSel Selector to find the connection error button where to place the popover.
* @param {Boolean} offlineMode True if attempt is offline.
* @return {Void}
*/
self.init = function(scope, formNm, popoverNm, connErrorButtonSel, offlineMode) {
// Cancel previous processes.
self.cancelAutoSave();
self.stopCheckChangesProcess();
previousAnswers = undefined;
scope.autoSaveError = false;
formName = formNm;
popoverName = popoverNm;
connectionErrorButtonSelector = connErrorButtonSel;
offline = offlineMode;
};
/**
* Schedule an auto save process if it's not scheduled already.
* The auto save process expects a "preflightData" object in the scope with the preflight data.
*
* @module mm.addons.mod_quiz
* @ngdoc method
* @name $mmaModQuizAutoSave#setAutoSaveTimer
* @param {Object} scoep Scope.
* @param {Object} quiz Quiz.
* @param {Object} attempt Attempt.
* @return {Void}
*/
self.setAutoSaveTimer = function(scope, quiz, attempt) {
// Don't schedule if already shceduled or quiz is almost closed.
if (quiz.autosaveperiod && !autoSavePromise && !$mmaModQuiz.isAttemptTimeNearlyOver(quiz, attempt)) {
// Schedule save.
autoSavePromise = $timeout(function() {
var answers = getAnswers();
self.cancelAutoSave();
previousAnswers = answers; // Update previous answers to match what we're sending to the server.
$mmaModQuiz.saveAttempt(quiz, attempt, answers, scope.preflightData, offline).then(function() {
// Save successful, we can hide the connection error if it was shown.
self.hideAutoSaveError(scope);
}).catch(function(message) {
// Error auto-saving. Show error and set timer again.
$log.warn('Error auto-saving data.', message);
self.showAutoSaveError(scope);
self.setAutoSaveTimer(scope, quiz, attempt);
});
}, quiz.autosaveperiod * 1000);
}
};
/**
* Show an error popover due to an auto save error.
*
* @module mm.addons.mod_quiz
* @ngdoc method
* @name $mmaModQuizAutoSave#showAutoSaveError
* @param {Object} scope Scope.
* @return {Void}
*/
self.showAutoSaveError = function(scope) {
// Don't show popover if it was already shown.
if (!scope.autoSaveError) {
scope.autoSaveError = true;
// Wait a digest to show the popover.
// This is because we need the button to be rendered, otherwise it's not shown right.
$timeout(function() {
if (scope[popoverName]) {
scope[popoverName].show(document.querySelector(connectionErrorButtonSelector));
}
});
}
};
/**
* Start a process to periodically check changes in answers.
*
* @module mm.addons.mod_quiz
* @ngdoc method
* @name $mmaModQuizAutoSave#startCheckChangesProcess
* @param {Object} scope Scope.
* @param {Object} quiz Quiz.
* @param {Object} attempt Attempt.
* @return {Void}
*/
self.startCheckChangesProcess = function(scope, quiz, attempt) {
if (checkChangesProcess || !quiz.autosaveperiod) {
// We already have the interval in place or the quiz has autosave disabled.
return;
}
function checkChanges() {
self.checkChanges(scope, quiz, attempt);
}
previousAnswers = undefined;
// Load initial answers in 2.5 seconds.
loadPreviousAnswersPromise = $timeout(checkChanges, 2500);
// Check changes every certain time.
checkChangesProcess = $interval(checkChanges, mmaModQuizCheckChangesInterval);
};
/**
* Stops the auto save process.
*
* @module mm.addons.mod_quiz
* @ngdoc method
* @name $mmaModQuizAutoSave#stopAutoSaving
* @return {Void}
*/
self.stopAutoSaving = function() {
self.cancelAutoSave();
// Set it to true so we cannot start autosave again unless we call init().
autoSavePromise = true;
};
/**
* Stops the periodical check for changes.
*
* @module mm.addons.mod_quiz
* @ngdoc method
* @name $mmaModQuizAutoSave#stopCheckChangesProcess
* @return {Void}
*/
self.stopCheckChangesProcess = function() {
if (checkChangesProcess) {
$interval.cancel(checkChangesProcess);
}
if (loadPreviousAnswersPromise) {
$timeout.cancel(loadPreviousAnswersPromise);
}
loadPreviousAnswersPromise = undefined;
checkChangesProcess = undefined;
};
return self;
});
|
bmmg888/moodlemobile2
|
www/addons/mod/quiz/services/autosave.js
|
JavaScript
|
apache-2.0
| 8,813
|
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on('Accounts Settings', {
refresh: function(frm) {
}
});
|
hassanibi/erpnext
|
erpnext/accounts/doctype/accounts_settings/accounts_settings.js
|
JavaScript
|
gpl-3.0
| 197
|
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: ['lib/*.js', 'test/*.js'],
options: {
jshintrc: '.jshintrc'
}
},
mochaTest: {
all: {
options: {
reporter: 'spec'
},
src: ['test/*-test.js']
}
}
});
// Load the plugin(s)
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha-test');
// Tasks
grunt.registerTask('default', ['jshint', 'mochaTest']);
};
|
tsiry95/openshift-strongloop-cartridge
|
strongloop/node_modules/mailcomposer/Gruntfile.js
|
JavaScript
|
mit
| 643
|
/*
*
* 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.
*
*/
/*jshint unused:true, undef:true, browser:true */
/*global Windows:true, URL:true, module:true, require:true, WinJS:true */
var Camera = require('./Camera');
var getAppData = function () {
return Windows.Storage.ApplicationData.current;
};
var encodeToBase64String = function (buffer) {
return Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
};
var OptUnique = Windows.Storage.CreationCollisionOption.generateUniqueName;
var CapMSType = Windows.Media.Capture.MediaStreamType;
var webUIApp = Windows.UI.WebUI.WebUIApplication;
var fileIO = Windows.Storage.FileIO;
var pickerLocId = Windows.Storage.Pickers.PickerLocationId;
module.exports = {
// args will contain :
// ... it is an array, so be careful
// 0 quality:50,
// 1 destinationType:Camera.DestinationType.FILE_URI,
// 2 sourceType:Camera.PictureSourceType.CAMERA,
// 3 targetWidth:-1,
// 4 targetHeight:-1,
// 5 encodingType:Camera.EncodingType.JPEG,
// 6 mediaType:Camera.MediaType.PICTURE,
// 7 allowEdit:false,
// 8 correctOrientation:false,
// 9 saveToPhotoAlbum:false,
// 10 popoverOptions:null
// 11 cameraDirection:0
takePicture: function (successCallback, errorCallback, args) {
var sourceType = args[2];
if (sourceType != Camera.PictureSourceType.CAMERA) {
takePictureFromFile(successCallback, errorCallback, args);
} else {
takePictureFromCamera(successCallback, errorCallback, args);
}
}
};
// https://msdn.microsoft.com/en-us/library/windows/apps/ff462087(v=vs.105).aspx
var windowsVideoContainers = [".avi", ".flv", ".asx", ".asf", ".mov", ".mp4", ".mpg", ".rm", ".srt", ".swf", ".wmv", ".vob"];
var windowsPhoneVideoContainers = [".avi", ".3gp", ".3g2", ".wmv", ".3gp", ".3g2", ".mp4", ".m4v"];
// Default aspect ratio 1.78 (16:9 hd video standard)
var DEFAULT_ASPECT_RATIO = '1.8';
// Highest possible z-index supported across browsers. Anything used above is converted to this value.
var HIGHEST_POSSIBLE_Z_INDEX = 2147483647;
// Resize method
function resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType) {
var tempPhotoFileName = "";
var targetContentType = "";
if (encodingType == Camera.EncodingType.PNG) {
tempPhotoFileName = "camera_cordova_temp_return.png";
targetContentType = "image/png";
} else {
tempPhotoFileName = "camera_cordova_temp_return.jpg";
targetContentType = "image/jpeg";
}
var storageFolder = getAppData().localFolder;
file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting)
.then(function (storageFile) {
return fileIO.readBufferAsync(storageFile);
})
.then(function(buffer) {
var strBase64 = encodeToBase64String(buffer);
var imageData = "data:" + file.contentType + ";base64," + strBase64;
var image = new Image();
image.src = imageData;
image.onload = function() {
var ratio = Math.min(targetWidth / this.width, targetHeight / this.height);
var imageWidth = ratio * this.width;
var imageHeight = ratio * this.height;
var canvas = document.createElement('canvas');
var storageFileName;
canvas.width = imageWidth;
canvas.height = imageHeight;
canvas.getContext("2d").drawImage(this, 0, 0, imageWidth, imageHeight);
var fileContent = canvas.toDataURL(targetContentType).split(',')[1];
var storageFolder = getAppData().localFolder;
storageFolder.createFileAsync(tempPhotoFileName, OptUnique)
.then(function (storagefile) {
var content = Windows.Security.Cryptography.CryptographicBuffer.decodeFromBase64String(fileContent);
storageFileName = storagefile.name;
return fileIO.writeBufferAsync(storagefile, content);
})
.done(function () {
successCallback("ms-appdata:///local/" + storageFileName);
}, errorCallback);
};
})
.done(null, function(err) {
errorCallback(err);
}
);
}
// Because of asynchronous method, so let the successCallback be called in it.
function resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight) {
fileIO.readBufferAsync(file).done( function(buffer) {
var strBase64 = encodeToBase64String(buffer);
var imageData = "data:" + file.contentType + ";base64," + strBase64;
var image = new Image();
image.src = imageData;
image.onload = function() {
var ratio = Math.min(targetWidth / this.width, targetHeight / this.height);
var imageWidth = ratio * this.width;
var imageHeight = ratio * this.height;
var canvas = document.createElement('canvas');
canvas.width = imageWidth;
canvas.height = imageHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
// The resized file ready for upload
var finalFile = canvas.toDataURL(file.contentType);
// Remove the prefix such as "data:" + contentType + ";base64," , in order to meet the Cordova API.
var arr = finalFile.split(",");
var newStr = finalFile.substr(arr[0].length + 1);
successCallback(newStr);
};
}, function(err) { errorCallback(err); });
}
function takePictureFromFile(successCallback, errorCallback, args) {
// Detect Windows Phone
if (navigator.appVersion.indexOf('Windows Phone 8.1') >= 0) {
takePictureFromFileWP(successCallback, errorCallback, args);
} else {
takePictureFromFileWindows(successCallback, errorCallback, args);
}
}
function takePictureFromFileWP(successCallback, errorCallback, args) {
var mediaType = args[6],
destinationType = args[1],
targetWidth = args[3],
targetHeight = args[4],
encodingType = args[5];
/*
Need to add and remove an event listener to catch activation state
Using FileOpenPicker will suspend the app and it's required to catch the PickSingleFileAndContinue
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631755.aspx
*/
var filePickerActivationHandler = function(eventArgs) {
if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.pickFileContinuation) {
var file = eventArgs.files[0];
if (!file) {
errorCallback("User didn't choose a file.");
webUIApp.removeEventListener("activated", filePickerActivationHandler);
return;
}
if (destinationType == Camera.DestinationType.FILE_URI || destinationType == Camera.DestinationType.NATIVE_URI) {
if (targetHeight > 0 && targetWidth > 0) {
resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType);
}
else {
var storageFolder = getAppData().localFolder;
file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).done(function (storageFile) {
if(destinationType == Camera.DestinationType.NATIVE_URI) {
successCallback("ms-appdata:///local/" + storageFile.name);
}
else {
successCallback(URL.createObjectURL(storageFile));
}
}, function () {
errorCallback("Can't access localStorage folder.");
});
}
}
else {
if (targetHeight > 0 && targetWidth > 0) {
resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight);
} else {
fileIO.readBufferAsync(file).done(function (buffer) {
var strBase64 =encodeToBase64String(buffer);
successCallback(strBase64);
}, errorCallback);
}
}
webUIApp.removeEventListener("activated", filePickerActivationHandler);
}
};
var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker();
if (mediaType == Camera.MediaType.PICTURE) {
fileOpenPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);
fileOpenPicker.suggestedStartLocation = pickerLocId.picturesLibrary;
}
else if (mediaType == Camera.MediaType.VIDEO) {
fileOpenPicker.fileTypeFilter.replaceAll(windowsPhoneVideoContainers);
fileOpenPicker.suggestedStartLocation = pickerLocId.videosLibrary;
}
else {
fileOpenPicker.fileTypeFilter.replaceAll(["*"]);
fileOpenPicker.suggestedStartLocation = pickerLocId.documentsLibrary;
}
webUIApp.addEventListener("activated", filePickerActivationHandler);
fileOpenPicker.pickSingleFileAndContinue();
}
function takePictureFromFileWindows(successCallback, errorCallback, args) {
var mediaType = args[6],
destinationType = args[1],
targetWidth = args[3],
targetHeight = args[4],
encodingType = args[5];
var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker();
if (mediaType == Camera.MediaType.PICTURE) {
fileOpenPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);
fileOpenPicker.suggestedStartLocation = pickerLocId.picturesLibrary;
}
else if (mediaType == Camera.MediaType.VIDEO) {
fileOpenPicker.fileTypeFilter.replaceAll(windowsVideoContainers);
fileOpenPicker.suggestedStartLocation = pickerLocId.videosLibrary;
}
else {
fileOpenPicker.fileTypeFilter.replaceAll(["*"]);
fileOpenPicker.suggestedStartLocation = pickerLocId.documentsLibrary;
}
fileOpenPicker.pickSingleFileAsync().done(function (file) {
if (!file) {
errorCallback("User didn't choose a file.");
return;
}
if (destinationType == Camera.DestinationType.FILE_URI || destinationType == Camera.DestinationType.NATIVE_URI) {
if (targetHeight > 0 && targetWidth > 0) {
resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType);
}
else {
var storageFolder = getAppData().localFolder;
file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).done(function (storageFile) {
if(destinationType == Camera.DestinationType.NATIVE_URI) {
successCallback("ms-appdata:///local/" + storageFile.name);
}
else {
successCallback(URL.createObjectURL(storageFile));
}
}, function () {
errorCallback("Can't access localStorage folder.");
});
}
}
else {
if (targetHeight > 0 && targetWidth > 0) {
resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight);
} else {
fileIO.readBufferAsync(file).done(function (buffer) {
var strBase64 =encodeToBase64String(buffer);
successCallback(strBase64);
}, errorCallback);
}
}
}, function () {
errorCallback("User didn't choose a file.");
});
}
function takePictureFromCamera(successCallback, errorCallback, args) {
// Check if necessary API available
if (!Windows.Media.Capture.CameraCaptureUI) {
takePictureFromCameraWP(successCallback, errorCallback, args);
} else {
takePictureFromCameraWindows(successCallback, errorCallback, args);
}
}
function takePictureFromCameraWP(successCallback, errorCallback, args) {
// We are running on WP8.1 which lacks CameraCaptureUI class
// so we need to use MediaCapture class instead and implement custom UI for camera
var destinationType = args[1],
targetWidth = args[3],
targetHeight = args[4],
encodingType = args[5],
saveToPhotoAlbum = args[9],
cameraDirection = args[11],
capturePreview = null,
cameraCaptureButton = null,
cameraCancelButton = null,
capture = null,
captureSettings = null,
CaptureNS = Windows.Media.Capture,
sensor = null;
function createCameraUI() {
// create style for take and cancel buttons
var buttonStyle = "width:45%;padding: 10px 16px;font-size: 18px;line-height: 1.3333333;color: #333;background-color: #fff;border-color: #ccc; border: 1px solid transparent;border-radius: 6px; display: block; margin: 20px; z-index: 1000;border-color: #adadad;";
// Create fullscreen preview
// z-order style element for capturePreview and cameraCancelButton elts
// is necessary to avoid overriding by another page elements, -1 sometimes is not enough
capturePreview = document.createElement("video");
capturePreview.style.cssText = "position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-index: " + (HIGHEST_POSSIBLE_Z_INDEX - 1) + ";";
// Create capture button
cameraCaptureButton = document.createElement("button");
cameraCaptureButton.innerText = "Take";
cameraCaptureButton.style.cssText = buttonStyle + "position: fixed; left: 0; bottom: 0; margin: 20px; z-index: " + HIGHEST_POSSIBLE_Z_INDEX + ";";
// Create cancel button
cameraCancelButton = document.createElement("button");
cameraCancelButton.innerText = "Cancel";
cameraCancelButton.style.cssText = buttonStyle + "position: fixed; right: 0; bottom: 0; margin: 20px; z-index: " + HIGHEST_POSSIBLE_Z_INDEX + ";";
capture = new CaptureNS.MediaCapture();
captureSettings = new CaptureNS.MediaCaptureInitializationSettings();
captureSettings.streamingCaptureMode = CaptureNS.StreamingCaptureMode.video;
}
function continueVideoOnFocus() {
// if preview is defined it would be stuck, play it
if (capturePreview) {
capturePreview.play();
}
}
function startCameraPreview() {
// Search for available camera devices
// This is necessary to detect which camera (front or back) we should use
var DeviceEnum = Windows.Devices.Enumeration;
var expectedPanel = cameraDirection === 1 ? DeviceEnum.Panel.front : DeviceEnum.Panel.back;
// Add focus event handler to capture the event when user suspends the app and comes back while the preview is on
window.addEventListener("focus", continueVideoOnFocus);
DeviceEnum.DeviceInformation.findAllAsync(DeviceEnum.DeviceClass.videoCapture).then(function (devices) {
if (devices.length <= 0) {
destroyCameraPreview();
errorCallback('Camera not found');
return;
}
devices.forEach(function(currDev) {
if (currDev.enclosureLocation.panel && currDev.enclosureLocation.panel == expectedPanel) {
captureSettings.videoDeviceId = currDev.id;
}
});
captureSettings.photoCaptureSource = Windows.Media.Capture.PhotoCaptureSource.photo;
return capture.initializeAsync(captureSettings);
}).then(function () {
// create focus control if available
var VideoDeviceController = capture.videoDeviceController;
var FocusControl = VideoDeviceController.focusControl;
if (FocusControl.supported === true) {
capturePreview.addEventListener('click', function () {
// Make sure function isn't called again before previous focus is completed
if (this.getAttribute('clicked') === '1') {
return false;
} else {
this.setAttribute('clicked', '1');
}
var preset = Windows.Media.Devices.FocusPreset.autoNormal;
var parent = this;
FocusControl.setPresetAsync(preset).done(function () {
// set the clicked attribute back to '0' to allow focus again
parent.setAttribute('clicked', '0');
});
});
}
// msdn.microsoft.com/en-us/library/windows/apps/hh452807.aspx
capturePreview.msZoom = true;
capturePreview.src = URL.createObjectURL(capture);
capturePreview.play();
// Bind events to controls
sensor = Windows.Devices.Sensors.SimpleOrientationSensor.getDefault();
if (sensor !== null) {
sensor.addEventListener("orientationchanged", onOrientationChange);
}
// add click events to capture and cancel buttons
cameraCaptureButton.addEventListener('click', onCameraCaptureButtonClick);
cameraCancelButton.addEventListener('click', onCameraCancelButtonClick);
// Change default orientation
if (sensor) {
setPreviewRotation(sensor.getCurrentOrientation());
} else {
setPreviewRotation(Windows.Graphics.Display.DisplayInformation.getForCurrentView().currentOrientation);
}
// Get available aspect ratios
var aspectRatios = getAspectRatios(capture);
// Couldn't find a good ratio
if (aspectRatios.length === 0) {
destroyCameraPreview();
errorCallback('There\'s not a good aspect ratio available');
return;
}
// add elements to body
document.body.appendChild(capturePreview);
document.body.appendChild(cameraCaptureButton);
document.body.appendChild(cameraCancelButton);
if (aspectRatios.indexOf(DEFAULT_ASPECT_RATIO) > -1) {
return setAspectRatio(capture, DEFAULT_ASPECT_RATIO);
} else {
// Doesn't support 16:9 - pick next best
return setAspectRatio(capture, aspectRatios[0]);
}
}).done(null, function (err) {
destroyCameraPreview();
errorCallback('Camera intitialization error ' + err);
});
}
function destroyCameraPreview() {
// If sensor is available, remove event listener
if (sensor !== null) {
sensor.removeEventListener('orientationchanged', onOrientationChange);
}
// Pause and dispose preview element
capturePreview.pause();
capturePreview.src = null;
// Remove event listeners from buttons
cameraCaptureButton.removeEventListener('click', onCameraCaptureButtonClick);
cameraCancelButton.removeEventListener('click', onCameraCancelButtonClick);
// Remove the focus event handler
window.removeEventListener("focus", continueVideoOnFocus);
// Remove elements
[capturePreview, cameraCaptureButton, cameraCancelButton].forEach(function (elem) {
if (elem /* && elem in document.body.childNodes */) {
document.body.removeChild(elem);
}
});
// Stop and dispose media capture manager
if (capture) {
capture.stopRecordAsync();
capture = null;
}
}
function captureAction() {
var encodingProperties,
fileName,
tempFolder = getAppData().temporaryFolder;
if (encodingType == Camera.EncodingType.PNG) {
fileName = 'photo.png';
encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createPng();
} else {
fileName = 'photo.jpg';
encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createJpeg();
}
tempFolder.createFileAsync(fileName, OptUnique)
.then(function(tempCapturedFile) {
return new WinJS.Promise(function (complete) {
var photoStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
var finalStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
capture.capturePhotoToStreamAsync(encodingProperties, photoStream)
.then(function() {
return Windows.Graphics.Imaging.BitmapDecoder.createAsync(photoStream);
})
.then(function(dec) {
finalStream.size = 0; // BitmapEncoder requires the output stream to be empty
return Windows.Graphics.Imaging.BitmapEncoder.createForTranscodingAsync(finalStream, dec);
})
.then(function(enc) {
// We need to rotate the photo wrt sensor orientation
enc.bitmapTransform.rotation = orientationToRotation(sensor.getCurrentOrientation());
return enc.flushAsync();
})
.then(function() {
return tempCapturedFile.openAsync(Windows.Storage.FileAccessMode.readWrite);
})
.then(function(fileStream) {
return Windows.Storage.Streams.RandomAccessStream.copyAndCloseAsync(finalStream, fileStream);
})
.done(function() {
photoStream.close();
finalStream.close();
complete(tempCapturedFile);
}, function() {
photoStream.close();
finalStream.close();
throw new Error("An error has occured while capturing the photo.");
});
});
})
.done(function(capturedFile) {
destroyCameraPreview();
savePhoto(capturedFile, {
destinationType: destinationType,
targetHeight: targetHeight,
targetWidth: targetWidth,
encodingType: encodingType,
saveToPhotoAlbum: saveToPhotoAlbum
}, successCallback, errorCallback);
}, function(err) {
destroyCameraPreview();
errorCallback(err);
});
}
function getAspectRatios(capture) {
var videoDeviceController = capture.videoDeviceController;
var photoAspectRatios = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.photo).map(function (element) {
return (element.width / element.height).toFixed(1);
}).filter(function (element, index, array) { return (index === array.indexOf(element)); });
var videoAspectRatios = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.videoRecord).map(function (element) {
return (element.width / element.height).toFixed(1);
}).filter(function (element, index, array) { return (index === array.indexOf(element)); });
var videoPreviewAspectRatios = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.videoPreview).map(function (element) {
return (element.width / element.height).toFixed(1);
}).filter(function (element, index, array) { return (index === array.indexOf(element)); });
var allAspectRatios = [].concat(photoAspectRatios, videoAspectRatios, videoPreviewAspectRatios);
var aspectObj = allAspectRatios.reduce(function (map, item) {
if (!map[item]) {
map[item] = 0;
}
map[item]++;
return map;
}, {});
return Object.keys(aspectObj).filter(function (k) {
return aspectObj[k] === 3;
});
}
function setAspectRatio(capture, aspect) {
// Max photo resolution with desired aspect ratio
var videoDeviceController = capture.videoDeviceController;
var photoResolution = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.photo)
.filter(function (elem) {
return ((elem.width / elem.height).toFixed(1) === aspect);
})
.reduce(function (prop1, prop2) {
return (prop1.width * prop1.height) > (prop2.width * prop2.height) ? prop1 : prop2;
});
// Max video resolution with desired aspect ratio
var videoRecordResolution = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.videoRecord)
.filter(function (elem) {
return ((elem.width / elem.height).toFixed(1) === aspect);
})
.reduce(function (prop1, prop2) {
return (prop1.width * prop1.height) > (prop2.width * prop2.height) ? prop1 : prop2;
});
// Max video preview resolution with desired aspect ratio
var videoPreviewResolution = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.videoPreview)
.filter(function (elem) {
return ((elem.width / elem.height).toFixed(1) === aspect);
})
.reduce(function (prop1, prop2) {
return (prop1.width * prop1.height) > (prop2.width * prop2.height) ? prop1 : prop2;
});
return videoDeviceController.setMediaStreamPropertiesAsync(CapMSType.photo, photoResolution)
.then(function () {
return videoDeviceController.setMediaStreamPropertiesAsync(CapMSType.videoPreview, videoPreviewResolution);
})
.then(function () {
return videoDeviceController.setMediaStreamPropertiesAsync(CapMSType.videoRecord, videoRecordResolution);
});
}
/**
* When Capture button is clicked, try to capture a picture and return
*/
function onCameraCaptureButtonClick() {
// Make sure user can't click more than once
if (this.getAttribute('clicked') === '1') {
return false;
} else {
this.setAttribute('clicked', '1');
}
captureAction();
}
/**
* When Cancel button is clicked, destroy camera preview and return with error callback
*/
function onCameraCancelButtonClick() {
// Make sure user can't click more than once
if (this.getAttribute('clicked') === '1') {
return false;
} else {
this.setAttribute('clicked', '1');
}
destroyCameraPreview();
errorCallback('no image selected');
}
/**
* When the phone orientation change, get the event and change camera preview rotation
* @param {Object} e - SimpleOrientationSensorOrientationChangedEventArgs
*/
function onOrientationChange(e) {
setPreviewRotation(e.orientation);
}
/**
* Converts SimpleOrientation to a VideoRotation to remove difference between camera sensor orientation
* and video orientation
* @param {number} orientation - Windows.Devices.Sensors.SimpleOrientation
* @return {number} - Windows.Media.Capture.VideoRotation
*/
function orientationToRotation(orientation) {
// VideoRotation enumerable and BitmapRotation enumerable have the same values
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.media.capture.videorotation.aspx
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging.bitmaprotation.aspx
switch (orientation) {
// portrait
case Windows.Devices.Sensors.SimpleOrientation.notRotated:
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
// landscape
case Windows.Devices.Sensors.SimpleOrientation.rotated90DegreesCounterclockwise:
return Windows.Media.Capture.VideoRotation.none;
// portrait-flipped (not supported by WinPhone Apps)
case Windows.Devices.Sensors.SimpleOrientation.rotated180DegreesCounterclockwise:
// Falling back to portrait default
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
// landscape-flipped
case Windows.Devices.Sensors.SimpleOrientation.rotated270DegreesCounterclockwise:
return Windows.Media.Capture.VideoRotation.clockwise180Degrees;
// faceup & facedown
default:
// Falling back to portrait default
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
}
}
/**
* Rotates the current MediaCapture's video
* @param {number} orientation - Windows.Devices.Sensors.SimpleOrientation
*/
function setPreviewRotation(orientation) {
capture.setPreviewRotation(orientationToRotation(orientation));
}
try {
createCameraUI();
startCameraPreview();
} catch (ex) {
errorCallback(ex);
}
}
function takePictureFromCameraWindows(successCallback, errorCallback, args) {
var destinationType = args[1],
targetWidth = args[3],
targetHeight = args[4],
encodingType = args[5],
allowCrop = !!args[7],
saveToPhotoAlbum = args[9],
WMCapture = Windows.Media.Capture,
cameraCaptureUI = new WMCapture.CameraCaptureUI();
cameraCaptureUI.photoSettings.allowCropping = allowCrop;
if (encodingType == Camera.EncodingType.PNG) {
cameraCaptureUI.photoSettings.format = WMCapture.CameraCaptureUIPhotoFormat.png;
} else {
cameraCaptureUI.photoSettings.format = WMCapture.CameraCaptureUIPhotoFormat.jpeg;
}
// decide which max pixels should be supported by targetWidth or targetHeight.
var maxRes = null;
var UIMaxRes = WMCapture.CameraCaptureUIMaxPhotoResolution;
var totalPixels = targetWidth * targetHeight;
if (targetWidth == -1 && targetHeight == -1) {
maxRes = UIMaxRes.highestAvailable;
}
// Temp fix for CB-10539
/*else if (totalPixels <= 320 * 240) {
maxRes = UIMaxRes.verySmallQvga;
}*/
else if (totalPixels <= 640 * 480) {
maxRes = UIMaxRes.smallVga;
} else if (totalPixels <= 1024 * 768) {
maxRes = UIMaxRes.mediumXga;
} else if (totalPixels <= 3 * 1000 * 1000) {
maxRes = UIMaxRes.large3M;
} else if (totalPixels <= 5 * 1000 * 1000) {
maxRes = UIMaxRes.veryLarge5M;
} else {
maxRes = UIMaxRes.highestAvailable;
}
cameraCaptureUI.photoSettings.maxResolution = maxRes;
var cameraPicture;
// define focus handler for windows phone 10.0
var savePhotoOnFocus = function () {
window.removeEventListener("focus", savePhotoOnFocus);
// call only when the app is in focus again
savePhoto(cameraPicture, {
destinationType: destinationType,
targetHeight: targetHeight,
targetWidth: targetWidth,
encodingType: encodingType,
saveToPhotoAlbum: saveToPhotoAlbum
}, successCallback, errorCallback);
};
// if windows phone 10, add and delete focus eventHandler to capture the focus back from cameraUI to app
if (navigator.appVersion.indexOf('Windows Phone 10.0') >= 0) {
window.addEventListener("focus", savePhotoOnFocus);
}
cameraCaptureUI.captureFileAsync(WMCapture.CameraCaptureUIMode.photo).done(function (picture) {
if (!picture) {
errorCallback("User didn't capture a photo.");
// Remove the focus handler if present
window.removeEventListener("focus", savePhotoOnFocus);
return;
}
cameraPicture = picture;
// If not windows 10, call savePhoto() now. If windows 10, wait for the app to be in focus again
if (navigator.appVersion.indexOf('Windows Phone 10.0') < 0) {
savePhoto(cameraPicture, {
destinationType: destinationType,
targetHeight: targetHeight,
targetWidth: targetWidth,
encodingType: encodingType,
saveToPhotoAlbum: saveToPhotoAlbum
}, successCallback, errorCallback);
}
}, function () {
errorCallback("Fail to capture a photo.");
window.removeEventListener("focus", savePhotoOnFocus);
});
}
function savePhoto(picture, options, successCallback, errorCallback) {
// success callback for capture operation
var success = function(picture) {
if (options.destinationType == Camera.DestinationType.FILE_URI || options.destinationType == Camera.DestinationType.NATIVE_URI) {
if (options.targetHeight > 0 && options.targetWidth > 0) {
resizeImage(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight, options.encodingType);
} else {
picture.copyAsync(getAppData().localFolder, picture.name, OptUnique).done(function (copiedFile) {
successCallback("ms-appdata:///local/" + copiedFile.name);
},errorCallback);
}
} else {
if (options.targetHeight > 0 && options.targetWidth > 0) {
resizeImageBase64(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight);
} else {
fileIO.readBufferAsync(picture).done(function(buffer) {
var strBase64 = encodeToBase64String(buffer);
picture.deleteAsync().done(function() {
successCallback(strBase64);
}, function(err) {
errorCallback(err);
});
}, errorCallback);
}
}
};
if (!options.saveToPhotoAlbum) {
success(picture);
return;
} else {
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
var saveFile = function(file) {
if (file) {
// Prevent updates to the remote version of the file until we're done
Windows.Storage.CachedFileManager.deferUpdates(file);
picture.moveAndReplaceAsync(file)
.then(function() {
// Let Windows know that we're finished changing the file so
// the other app can update the remote version of the file.
return Windows.Storage.CachedFileManager.completeUpdatesAsync(file);
})
.done(function(updateStatus) {
if (updateStatus === Windows.Storage.Provider.FileUpdateStatus.complete) {
success(picture);
} else {
errorCallback("File update status is not complete.");
}
}, errorCallback);
} else {
errorCallback("Failed to select a file.");
}
};
savePicker.suggestedStartLocation = pickerLocId.picturesLibrary;
if (options.encodingType === Camera.EncodingType.PNG) {
savePicker.fileTypeChoices.insert("PNG", [".png"]);
savePicker.suggestedFileName = "photo.png";
} else {
savePicker.fileTypeChoices.insert("JPEG", [".jpg"]);
savePicker.suggestedFileName = "photo.jpg";
}
// If Windows Phone 8.1 use pickSaveFileAndContinue()
if (navigator.appVersion.indexOf('Windows Phone 8.1') >= 0) {
/*
Need to add and remove an event listener to catch activation state
Using FileSavePicker will suspend the app and it's required to catch the pickSaveFileContinuation
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631755.aspx
*/
var fileSaveHandler = function(eventArgs) {
if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.pickSaveFileContinuation) {
var file = eventArgs.file;
saveFile(file);
webUIApp.removeEventListener("activated", fileSaveHandler);
}
};
webUIApp.addEventListener("activated", fileSaveHandler);
savePicker.pickSaveFileAndContinue();
} else {
savePicker.pickSaveFileAsync()
.done(saveFile, errorCallback);
}
}
}
require("cordova/exec/proxy").add("Camera",module.exports);
|
Hwimbloh/Yeh
|
www/plugins/cordova-plugin-camera/src/windows/CameraProxy.js
|
JavaScript
|
apache-2.0
| 38,187
|
(function(factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory(require('jquery'));
} else {
factory(jQuery);
}
}(function($) {
/*! TableSorter (FORK) v2.25.0 *//*
* Client-side table sorting with ease!
* @requires jQuery v1.2.6+
*
* Copyright (c) 2007 Christian Bach
* fork maintained by Rob Garrison
*
* Examples and docs at: http://tablesorter.com
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* @type jQuery
* @name tablesorter (FORK)
* @cat Plugins/Tablesorter
* @author Christian Bach - christian.bach@polyester.se
* @contributor Rob Garrison - https://github.com/Mottie/tablesorter
*/
/*jshint browser:true, jquery:true, unused:false, expr: true */
;( function( $ ) {
'use strict';
var ts = $.tablesorter = {
version : '2.25.0',
parsers : [],
widgets : [],
defaults : {
// *** appearance
theme : 'default', // adds tablesorter-{theme} to the table for styling
widthFixed : false, // adds colgroup to fix widths of columns
showProcessing : false, // show an indeterminate timer icon in the header when the table is sorted or filtered.
headerTemplate : '{content}',// header layout template (HTML ok); {content} = innerHTML, {icon} = <i/> // class from cssIcon
onRenderTemplate : null, // function( index, template ){ return template; }, // template is a string
onRenderHeader : null, // function( index ){}, // nothing to return
// *** functionality
cancelSelection : true, // prevent text selection in the header
tabIndex : true, // add tabindex to header for keyboard accessibility
dateFormat : 'mmddyyyy', // other options: 'ddmmyyy' or 'yyyymmdd'
sortMultiSortKey : 'shiftKey', // key used to select additional columns
sortResetKey : 'ctrlKey', // key used to remove sorting on a column
usNumberFormat : true, // false for German '1.234.567,89' or French '1 234 567,89'
delayInit : false, // if false, the parsed table contents will not update until the first sort
serverSideSorting: false, // if true, server-side sorting should be performed because client-side sorting will be disabled, but the ui and events will still be used.
resort : true, // default setting to trigger a resort after an 'update', 'addRows', 'updateCell', etc has completed
// *** sort options
headers : {}, // set sorter, string, empty, locked order, sortInitialOrder, filter, etc.
ignoreCase : true, // ignore case while sorting
sortForce : null, // column(s) first sorted; always applied
sortList : [], // Initial sort order; applied initially; updated when manually sorted
sortAppend : null, // column(s) sorted last; always applied
sortStable : false, // when sorting two rows with exactly the same content, the original sort order is maintained
sortInitialOrder : 'asc', // sort direction on first click
sortLocaleCompare: false, // replace equivalent character (accented characters)
sortReset : false, // third click on the header will reset column to default - unsorted
sortRestart : false, // restart sort to 'sortInitialOrder' when clicking on previously unsorted columns
emptyTo : 'bottom', // sort empty cell to bottom, top, none, zero, emptyMax, emptyMin
stringTo : 'max', // sort strings in numerical column as max, min, top, bottom, zero
duplicateSpan : true, // colspan cells in the tbody will have duplicated content in the cache for each spanned column
textExtraction : 'basic', // text extraction method/function - function( node, table, cellIndex ){}
textAttribute : 'data-text',// data-attribute that contains alternate cell text (used in default textExtraction function)
textSorter : null, // choose overall or specific column sorter function( a, b, direction, table, columnIndex ) [alt: ts.sortText]
numberSorter : null, // choose overall numeric sorter function( a, b, direction, maxColumnValue )
// *** widget options
widgets: [], // method to add widgets, e.g. widgets: ['zebra']
widgetOptions : {
zebra : [ 'even', 'odd' ] // zebra widget alternating row class names
},
initWidgets : true, // apply widgets on tablesorter initialization
widgetClass : 'widget-{name}', // table class name template to match to include a widget
// *** callbacks
initialized : null, // function( table ){},
// *** extra css class names
tableClass : '',
cssAsc : '',
cssDesc : '',
cssNone : '',
cssHeader : '',
cssHeaderRow : '',
cssProcessing : '', // processing icon applied to header during sort/filter
cssChildRow : 'tablesorter-childRow', // class name indiciating that a row is to be attached to the its parent
cssInfoBlock : 'tablesorter-infoOnly', // don't sort tbody with this class name (only one class name allowed here!)
cssNoSort : 'tablesorter-noSort', // class name added to element inside header; clicking on it won't cause a sort
cssIgnoreRow : 'tablesorter-ignoreRow', // header row to ignore; cells within this row will not be added to c.$headers
cssIcon : 'tablesorter-icon', // if this class does not exist, the {icon} will not be added from the headerTemplate
cssIconNone : '', // class name added to the icon when there is no column sort
cssIconAsc : '', // class name added to the icon when the column has an ascending sort
cssIconDesc : '', // class name added to the icon when the column has a descending sort
// *** events
pointerClick : 'click',
pointerDown : 'mousedown',
pointerUp : 'mouseup',
// *** selectors
selectorHeaders : '> thead th, > thead td',
selectorSort : 'th, td', // jQuery selector of content within selectorHeaders that is clickable to trigger a sort
selectorRemove : '.remove-me',
// *** advanced
debug : false,
// *** Internal variables
headerList: [],
empties: {},
strings: {},
parsers: []
// removed: widgetZebra: { css: ['even', 'odd'] }
},
// internal css classes - these will ALWAYS be added to
// the table and MUST only contain one class name - fixes #381
css : {
table : 'tablesorter',
cssHasChild: 'tablesorter-hasChildRow',
childRow : 'tablesorter-childRow',
colgroup : 'tablesorter-colgroup',
header : 'tablesorter-header',
headerRow : 'tablesorter-headerRow',
headerIn : 'tablesorter-header-inner',
icon : 'tablesorter-icon',
processing : 'tablesorter-processing',
sortAsc : 'tablesorter-headerAsc',
sortDesc : 'tablesorter-headerDesc',
sortNone : 'tablesorter-headerUnSorted'
},
// labels applied to sortable headers for accessibility (aria) support
language : {
sortAsc : 'Ascending sort applied, ',
sortDesc : 'Descending sort applied, ',
sortNone : 'No sort applied, ',
sortDisabled : 'sorting is disabled',
nextAsc : 'activate to apply an ascending sort',
nextDesc : 'activate to apply a descending sort',
nextNone : 'activate to remove the sort'
},
regex : {
templateContent : /\{content\}/g,
templateIcon : /\{icon\}/g,
templateName : /\{name\}/i,
spaces : /\s+/g,
nonWord : /\W/g,
formElements : /(input|select|button|textarea)/i,
// *** sort functions ***
// regex used in natural sort
// chunk/tokenize numbers & letters
chunk : /(^([+\-]?(?:\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi,
// replace chunks @ ends
chunks : /(^\\0|\\0$)/,
hex : /^0x[0-9a-f]+$/i,
// *** formatFloat ***
comma : /,/g,
digitNonUS : /[\s|\.]/g,
digitNegativeTest : /^\s*\([.\d]+\)/,
digitNegativeReplace : /^\s*\(([.\d]+)\)/,
// *** isDigit ***
digitTest : /^[\-+(]?\d+[)]?$/,
digitReplace : /[,.'"\s]/g
},
// digit sort text location; keeping max+/- for backwards compatibility
string : {
max : 1,
min : -1,
emptymin : 1,
emptymax : -1,
zero : 0,
none : 0,
'null' : 0,
top : true,
bottom : false
},
// placeholder date parser data (globalize)
dates : {},
// These methods can be applied on table.config instance
instanceMethods : {},
/*
▄█████ ██████ ██████ ██ ██ █████▄
▀█▄ ██▄▄ ██ ██ ██ ██▄▄██
▀█▄ ██▀▀ ██ ██ ██ ██▀▀▀
█████▀ ██████ ██ ▀████▀ ██
*/
setup : function( table, c ) {
// if no thead or tbody, or tablesorter is already present, quit
if ( !table || !table.tHead || table.tBodies.length === 0 || table.hasInitialized === true ) {
if ( c.debug ) {
if ( table.hasInitialized ) {
console.warn( 'Stopping initialization. Tablesorter has already been initialized' );
} else {
console.error( 'Stopping initialization! No table, thead or tbody', table );
}
}
return;
}
var tmp = '',
$table = $( table ),
meta = $.metadata;
// initialization flag
table.hasInitialized = false;
// table is being processed flag
table.isProcessing = true;
// make sure to store the config object
table.config = c;
// save the settings where they read
$.data( table, 'tablesorter', c );
if ( c.debug ) {
console[ console.group ? 'group' : 'log' ]( 'Initializing tablesorter' );
$.data( table, 'startoveralltimer', new Date() );
}
// removing this in version 3 (only supports jQuery 1.7+)
c.supportsDataObject = ( function( version ) {
version[ 0 ] = parseInt( version[ 0 ], 10 );
return ( version[ 0 ] > 1 ) || ( version[ 0 ] === 1 && parseInt( version[ 1 ], 10 ) >= 4 );
})( $.fn.jquery.split( '.' ) );
// ensure case insensitivity
c.emptyTo = c.emptyTo.toLowerCase();
c.stringTo = c.stringTo.toLowerCase();
c.last = { sortList : [], clickedIndex : -1 };
// add table theme class only if there isn't already one there
if ( !/tablesorter\-/.test( $table.attr( 'class' ) ) ) {
tmp = ( c.theme !== '' ? ' tablesorter-' + c.theme : '' );
}
c.table = table;
c.$table = $table
.addClass( ts.css.table + ' ' + c.tableClass + tmp )
.attr( 'role', 'grid' );
c.$headers = $table.find( c.selectorHeaders );
// give the table a unique id, which will be used in namespace binding
if ( !c.namespace ) {
c.namespace = '.tablesorter' + Math.random().toString( 16 ).slice( 2 );
} else {
// make sure namespace starts with a period & doesn't have weird characters
c.namespace = '.' + c.namespace.replace( ts.regex.nonWord, '' );
}
c.$table.children().children( 'tr' ).attr( 'role', 'row' );
c.$tbodies = $table.children( 'tbody:not(.' + c.cssInfoBlock + ')' ).attr({
'aria-live' : 'polite',
'aria-relevant' : 'all'
});
if ( c.$table.children( 'caption' ).length ) {
tmp = c.$table.children( 'caption' )[ 0 ];
if ( !tmp.id ) { tmp.id = c.namespace.slice( 1 ) + 'caption'; }
c.$table.attr( 'aria-labelledby', tmp.id );
}
c.widgetInit = {}; // keep a list of initialized widgets
// change textExtraction via data-attribute
c.textExtraction = c.$table.attr( 'data-text-extraction' ) || c.textExtraction || 'basic';
// build headers
ts.buildHeaders( c );
// fixate columns if the users supplies the fixedWidth option
// do this after theme has been applied
ts.fixColumnWidth( table );
// add widgets from class name
ts.addWidgetFromClass( table );
// add widget options before parsing (e.g. grouping widget has parser settings)
ts.applyWidgetOptions( table );
// try to auto detect column type, and store in tables config
ts.setupParsers( c );
// start total row count at zero
c.totalRows = 0;
// build the cache for the tbody cells
// delayInit will delay building the cache until the user starts a sort
if ( !c.delayInit ) { ts.buildCache( c ); }
// bind all header events and methods
ts.bindEvents( table, c.$headers, true );
ts.bindMethods( c );
// get sort list from jQuery data or metadata
// in jQuery < 1.4, an error occurs when calling $table.data()
if ( c.supportsDataObject && typeof $table.data().sortlist !== 'undefined' ) {
c.sortList = $table.data().sortlist;
} else if ( meta && ( $table.metadata() && $table.metadata().sortlist ) ) {
c.sortList = $table.metadata().sortlist;
}
// apply widget init code
ts.applyWidget( table, true );
// if user has supplied a sort list to constructor
if ( c.sortList.length > 0 ) {
ts.sortOn( c, c.sortList, {}, !c.initWidgets );
} else {
ts.setHeadersCss( c );
if ( c.initWidgets ) {
// apply widget format
ts.applyWidget( table, false );
}
}
// show processesing icon
if ( c.showProcessing ) {
$table
.unbind( 'sortBegin' + c.namespace + ' sortEnd' + c.namespace )
.bind( 'sortBegin' + c.namespace + ' sortEnd' + c.namespace, function( e ) {
clearTimeout( c.timerProcessing );
ts.isProcessing( table );
if ( e.type === 'sortBegin' ) {
c.timerProcessing = setTimeout( function() {
ts.isProcessing( table, true );
}, 500 );
}
});
}
// initialized
table.hasInitialized = true;
table.isProcessing = false;
if ( c.debug ) {
console.log( 'Overall initialization time: ' + ts.benchmark( $.data( table, 'startoveralltimer' ) ) );
if ( c.debug && console.groupEnd ) { console.groupEnd(); }
}
$table.triggerHandler( 'tablesorter-initialized', table );
if ( typeof c.initialized === 'function' ) {
c.initialized( table );
}
},
bindMethods : function( c ) {
var $table = c.$table,
namespace = c.namespace,
events = ( 'sortReset update updateRows updateAll updateHeaders addRows updateCell updateComplete ' +
'sorton appendCache updateCache applyWidgetId applyWidgets refreshWidgets destroy mouseup ' +
'mouseleave ' ).split( ' ' )
.join( namespace + ' ' );
// apply easy methods that trigger bound events
$table
.unbind( events.replace( ts.regex.spaces, ' ' ) )
.bind( 'sortReset' + namespace, function( e, callback ) {
e.stopPropagation();
// using this.config to ensure functions are getting a non-cached version of the config
ts.sortReset( this.config, callback );
})
.bind( 'updateAll' + namespace, function( e, resort, callback ) {
e.stopPropagation();
ts.updateAll( this.config, resort, callback );
})
.bind( 'update' + namespace + ' updateRows' + namespace, function( e, resort, callback ) {
e.stopPropagation();
ts.update( this.config, resort, callback );
})
.bind( 'updateHeaders' + namespace, function( e, callback ) {
e.stopPropagation();
ts.updateHeaders( this.config, callback );
})
.bind( 'updateCell' + namespace, function( e, cell, resort, callback ) {
e.stopPropagation();
ts.updateCell( this.config, cell, resort, callback );
})
.bind( 'addRows' + namespace, function( e, $row, resort, callback ) {
e.stopPropagation();
ts.addRows( this.config, $row, resort, callback );
})
.bind( 'updateComplete' + namespace, function() {
this.isUpdating = false;
})
.bind( 'sorton' + namespace, function( e, list, callback, init ) {
e.stopPropagation();
ts.sortOn( this.config, list, callback, init );
})
.bind( 'appendCache' + namespace, function( e, callback, init ) {
e.stopPropagation();
ts.appendCache( this.config, init );
if ( $.isFunction( callback ) ) {
callback( this );
}
})
// $tbodies variable is used by the tbody sorting widget
.bind( 'updateCache' + namespace, function( e, callback, $tbodies ) {
e.stopPropagation();
ts.updateCache( this.config, callback, $tbodies );
})
.bind( 'applyWidgetId' + namespace, function( e, id ) {
e.stopPropagation();
ts.applyWidgetId( this, id );
})
.bind( 'applyWidgets' + namespace, function( e, init ) {
e.stopPropagation();
// apply widgets
ts.applyWidget( this, init );
})
.bind( 'refreshWidgets' + namespace, function( e, all, dontapply ) {
e.stopPropagation();
ts.refreshWidgets( this, all, dontapply );
})
.bind( 'removeWidget' + namespace, function( e, name, refreshing ) {
e.stopPropagation();
ts.removeWidget( this, name, refreshing );
})
.bind( 'destroy' + namespace, function( e, removeClasses, callback ) {
e.stopPropagation();
ts.destroy( this, removeClasses, callback );
})
.bind( 'resetToLoadState' + namespace, function( e ) {
e.stopPropagation();
// remove all widgets
ts.removeWidget( this, true, false );
// restore original settings; this clears out current settings, but does not clear
// values saved to storage.
c = $.extend( true, ts.defaults, c.originalSettings );
this.hasInitialized = false;
// setup the entire table again
ts.setup( this, c );
});
},
bindEvents : function( table, $headers, core ) {
table = $( table )[ 0 ];
var tmp,
c = table.config,
namespace = c.namespace,
downTarget = null;
if ( core !== true ) {
$headers.addClass( namespace.slice( 1 ) + '_extra_headers' );
tmp = $.fn.closest ? $headers.closest( 'table' )[ 0 ] : $headers.parents( 'table' )[ 0 ];
if ( tmp && tmp.nodeName === 'TABLE' && tmp !== table ) {
$( tmp ).addClass( namespace.slice( 1 ) + '_extra_table' );
}
}
tmp = ( c.pointerDown + ' ' + c.pointerUp + ' ' + c.pointerClick + ' sort keyup ' )
.replace( ts.regex.spaces, ' ' )
.split( ' ' )
.join( namespace + ' ' );
// apply event handling to headers and/or additional headers (stickyheaders, scroller, etc)
$headers
// http://stackoverflow.com/questions/5312849/jquery-find-self;
.find( c.selectorSort )
.add( $headers.filter( c.selectorSort ) )
.unbind( tmp )
.bind( tmp, function( e, external ) {
var $cell, cell, temp,
$target = $( e.target ),
// wrap event type in spaces, so the match doesn't trigger on inner words
type = ' ' + e.type + ' ';
// only recognize left clicks
if ( ( ( e.which || e.button ) !== 1 && !type.match( ' ' + c.pointerClick + ' | sort | keyup ' ) ) ||
// allow pressing enter
( type === ' keyup ' && e.which !== 13 ) ||
// allow triggering a click event (e.which is undefined) & ignore physical clicks
( type.match( ' ' + c.pointerClick + ' ' ) && typeof e.which !== 'undefined' ) ) {
return;
}
// ignore mouseup if mousedown wasn't on the same target
if ( type.match( ' ' + c.pointerUp + ' ' ) && downTarget !== e.target && external !== true ) {
return;
}
// set target on mousedown
if ( type.match( ' ' + c.pointerDown + ' ' ) ) {
downTarget = e.target;
// preventDefault needed or jQuery v1.3.2 and older throws an
// "Uncaught TypeError: handler.apply is not a function" error
temp = $target.jquery.split( '.' );
if ( temp[ 0 ] === '1' && temp[ 1 ] < 4 ) { e.preventDefault(); }
return;
}
downTarget = null;
// prevent sort being triggered on form elements
if ( ts.regex.formElements.test( e.target.nodeName ) ||
// nosort class name, or elements within a nosort container
$target.hasClass( c.cssNoSort ) || $target.parents( '.' + c.cssNoSort ).length > 0 ||
// elements within a button
$target.parents( 'button' ).length > 0 ) {
return !c.cancelSelection;
}
if ( c.delayInit && ts.isEmptyObject( c.cache ) ) {
ts.buildCache( c );
}
// jQuery v1.2.6 doesn't have closest()
$cell = $.fn.closest ? $( this ).closest( 'th, td' ) :
/TH|TD/.test( this.nodeName ) ? $( this ) : $( this ).parents( 'th, td' );
// reference original table headers and find the same cell
// don't use $headers or IE8 throws an error - see #987
temp = $headers.index( $cell );
c.last.clickedIndex = ( temp < 0 ) ? $cell.attr( 'data-column' ) : temp;
// use column index if $headers is undefined
cell = c.$headers[ c.last.clickedIndex ];
if ( cell && !cell.sortDisabled ) {
ts.initSort( c, cell, e );
}
});
if ( c.cancelSelection ) {
// cancel selection
$headers
.attr( 'unselectable', 'on' )
.bind( 'selectstart', false )
.css({
'user-select' : 'none',
'MozUserSelect' : 'none' // not needed for jQuery 1.8+
});
}
},
buildHeaders : function( c ) {
var $temp, icon, timer, indx;
c.headerList = [];
c.headerContent = [];
c.sortVars = [];
if ( c.debug ) {
timer = new Date();
}
// children tr in tfoot - see issue #196 & #547
// don't pass table.config to computeColumnIndex here - widgets (math) pass it to "quickly" index tbody cells
c.columns = ts.computeColumnIndex( c.$table.children( 'thead, tfoot' ).children( 'tr' ) );
// add icon if cssIcon option exists
icon = c.cssIcon ?
'<i class="' + ( c.cssIcon === ts.css.icon ? ts.css.icon : c.cssIcon + ' ' + ts.css.icon ) + '"></i>' :
'';
// redefine c.$headers here in case of an updateAll that replaces or adds an entire header cell - see #683
c.$headers = $( $.map( c.$table.find( c.selectorHeaders ), function( elem, index ) {
var configHeaders, header, column, template, tmp,
$elem = $( elem );
// ignore cell (don't add it to c.$headers) if row has ignoreRow class
if ( $elem.parent().hasClass( c.cssIgnoreRow ) ) { return; }
// make sure to get header cell & not column indexed cell
configHeaders = ts.getColumnData( c.table, c.headers, index, true );
// save original header content
c.headerContent[ index ] = $elem.html();
// if headerTemplate is empty, don't reformat the header cell
if ( c.headerTemplate !== '' && !$elem.find( '.' + ts.css.headerIn ).length ) {
// set up header template
template = c.headerTemplate
.replace( ts.regex.templateContent, $elem.html() )
.replace( ts.regex.templateIcon, $elem.find( '.' + ts.css.icon ).length ? '' : icon );
if ( c.onRenderTemplate ) {
header = c.onRenderTemplate.apply( $elem, [ index, template ] );
// only change t if something is returned
if ( header && typeof header === 'string' ) {
template = header;
}
}
$elem.html( '<div class="' + ts.css.headerIn + '">' + template + '</div>' ); // faster than wrapInner
}
if ( c.onRenderHeader ) {
c.onRenderHeader.apply( $elem, [ index, c, c.$table ] );
}
column = parseInt( $elem.attr( 'data-column' ), 10 );
elem.column = column;
tmp = ts.getData( $elem, configHeaders, 'sortInitialOrder' ) || c.sortInitialOrder;
// this may get updated numerous times if there are multiple rows
c.sortVars[ column ] = {
count : -1, // set to -1 because clicking on the header automatically adds one
order: ts.getOrder( tmp ) ?
[ 1, 0, 2 ] : // desc, asc, unsorted
[ 0, 1, 2 ], // asc, desc, unsorted
lockedOrder : false
};
tmp = ts.getData( $elem, configHeaders, 'lockedOrder' ) || false;
if ( typeof tmp !== 'undefined' && tmp !== false ) {
c.sortVars[ column ].lockedOrder = true;
c.sortVars[ column ].order = ts.getOrder( tmp ) ? [ 1, 1, 1 ] : [ 0, 0, 0 ];
}
// add cell to headerList
c.headerList[ index ] = elem;
// add to parent in case there are multiple rows
$elem
.addClass( ts.css.header + ' ' + c.cssHeader )
.parent()
.addClass( ts.css.headerRow + ' ' + c.cssHeaderRow )
.attr( 'role', 'row' );
// allow keyboard cursor to focus on element
if ( c.tabIndex ) {
$elem.attr( 'tabindex', 0 );
}
return elem;
}) );
// cache headers per column
c.$headerIndexed = [];
for ( indx = 0; indx < c.columns; indx++ ) {
// colspan in header making a column undefined
if ( ts.isEmptyObject( c.sortVars[ indx ] ) ) {
c.sortVars[ indx ] = {};
}
$temp = c.$headers.filter( '[data-column="' + indx + '"]' );
// target sortable column cells, unless there are none, then use non-sortable cells
// .last() added in jQuery 1.4; use .filter(':last') to maintain compatibility with jQuery v1.2.6
c.$headerIndexed[ indx ] = $temp.length ?
$temp.not( '.sorter-false' ).length ?
$temp.not( '.sorter-false' ).filter( ':last' ) :
$temp.filter( ':last' ) :
$();
}
c.$table.find( c.selectorHeaders ).attr({
scope: 'col',
role : 'columnheader'
});
// enable/disable sorting
ts.updateHeader( c );
if ( c.debug ) {
console.log( 'Built headers:' + ts.benchmark( timer ) );
console.log( c.$headers );
}
},
// Use it to add a set of methods to table.config which will be available for all tables.
// This should be done before table initialization
addInstanceMethods : function( methods ) {
$.extend( ts.instanceMethods, methods );
},
/*
█████▄ ▄████▄ █████▄ ▄█████ ██████ █████▄ ▄█████
██▄▄██ ██▄▄██ ██▄▄██ ▀█▄ ██▄▄ ██▄▄██ ▀█▄
██▀▀▀ ██▀▀██ ██▀██ ▀█▄ ██▀▀ ██▀██ ▀█▄
██ ██ ██ ██ ██ █████▀ ██████ ██ ██ █████▀
*/
setupParsers : function( c, $tbodies ) {
var rows, list, span, max, colIndex, indx, header, configHeaders,
noParser, parser, extractor, time, tbody, len,
table = c.table,
tbodyIndex = 0,
debug = {};
// update table bodies in case we start with an empty table
c.$tbodies = c.$table.children( 'tbody:not(.' + c.cssInfoBlock + ')' );
tbody = typeof $tbodies === 'undefined' ? c.$tbodies : $tbodies;
len = tbody.length;
if ( len === 0 ) {
return c.debug ? console.warn( 'Warning: *Empty table!* Not building a parser cache' ) : '';
} else if ( c.debug ) {
time = new Date();
console[ console.group ? 'group' : 'log' ]( 'Detecting parsers for each column' );
}
list = {
extractors: [],
parsers: []
};
while ( tbodyIndex < len ) {
rows = tbody[ tbodyIndex ].rows;
if ( rows.length ) {
colIndex = 0;
max = c.columns;
for ( indx = 0; indx < max; indx++ ) {
header = c.$headerIndexed[ colIndex ];
if ( header && header.length ) {
// get column indexed table cell
configHeaders = ts.getColumnData( table, c.headers, colIndex );
// get column parser/extractor
extractor = ts.getParserById( ts.getData( header, configHeaders, 'extractor' ) );
parser = ts.getParserById( ts.getData( header, configHeaders, 'sorter' ) );
noParser = ts.getData( header, configHeaders, 'parser' ) === 'false';
// empty cells behaviour - keeping emptyToBottom for backwards compatibility
c.empties[colIndex] = (
ts.getData( header, configHeaders, 'empty' ) ||
c.emptyTo || ( c.emptyToBottom ? 'bottom' : 'top' ) ).toLowerCase();
// text strings behaviour in numerical sorts
c.strings[colIndex] = (
ts.getData( header, configHeaders, 'string' ) ||
c.stringTo ||
'max' ).toLowerCase();
if ( noParser ) {
parser = ts.getParserById( 'no-parser' );
}
if ( !extractor ) {
// For now, maybe detect someday
extractor = false;
}
if ( !parser ) {
parser = ts.detectParserForColumn( c, rows, -1, colIndex );
}
if ( c.debug ) {
debug[ '(' + colIndex + ') ' + header.text() ] = {
parser : parser.id,
extractor : extractor ? extractor.id : 'none',
string : c.strings[ colIndex ],
empty : c.empties[ colIndex ]
};
}
list.parsers[ colIndex ] = parser;
list.extractors[ colIndex ] = extractor;
span = header[ 0 ].colSpan - 1;
if ( span > 0 ) {
colIndex += span;
max += span;
while ( span + 1 > 0 ) {
// set colspan columns to use the same parsers & extractors
list.parsers[ colIndex - span ] = parser;
list.extractors[ colIndex - span ] = extractor;
span--;
}
}
}
colIndex++;
}
}
tbodyIndex += ( list.parsers.length ) ? len : 1;
}
if ( c.debug ) {
if ( !ts.isEmptyObject( debug ) ) {
console[ console.table ? 'table' : 'log' ]( debug );
} else {
console.warn( ' No parsers detected!' );
}
console.log( 'Completed detecting parsers' + ts.benchmark( time ) );
if ( console.groupEnd ) { console.groupEnd(); }
}
c.parsers = list.parsers;
c.extractors = list.extractors;
},
addParser : function( parser ) {
var indx,
len = ts.parsers.length,
add = true;
for ( indx = 0; indx < len; indx++ ) {
if ( ts.parsers[ indx ].id.toLowerCase() === parser.id.toLowerCase() ) {
add = false;
}
}
if ( add ) {
ts.parsers.push( parser );
}
},
getParserById : function( name ) {
/*jshint eqeqeq:false */
if ( name == 'false' ) { return false; }
var indx,
len = ts.parsers.length;
for ( indx = 0; indx < len; indx++ ) {
if ( ts.parsers[ indx ].id.toLowerCase() === ( name.toString() ).toLowerCase() ) {
return ts.parsers[ indx ];
}
}
return false;
},
detectParserForColumn : function( c, rows, rowIndex, cellIndex ) {
var cur, $node, row,
indx = ts.parsers.length,
node = false,
nodeValue = '',
keepLooking = true;
while ( nodeValue === '' && keepLooking ) {
rowIndex++;
row = rows[ rowIndex ];
// stop looking after 50 empty rows
if ( row && rowIndex < 50 ) {
if ( row.className.indexOf( ts.cssIgnoreRow ) < 0 ) {
node = rows[ rowIndex ].cells[ cellIndex ];
nodeValue = ts.getElementText( c, node, cellIndex );
$node = $( node );
if ( c.debug ) {
console.log( 'Checking if value was empty on row ' + rowIndex + ', column: ' +
cellIndex + ': "' + nodeValue + '"' );
}
}
} else {
keepLooking = false;
}
}
while ( --indx >= 0 ) {
cur = ts.parsers[ indx ];
// ignore the default text parser because it will always be true
if ( cur && cur.id !== 'text' && cur.is && cur.is( nodeValue, c.table, node, $node ) ) {
return cur;
}
}
// nothing found, return the generic parser (text)
return ts.getParserById( 'text' );
},
getElementText : function( c, node, cellIndex ) {
if ( !node ) { return ''; }
var tmp,
extract = c.textExtraction || '',
// node could be a jquery object
// http://jsperf.com/jquery-vs-instanceof-jquery/2
$node = node.jquery ? node : $( node );
if ( typeof extract === 'string' ) {
// check data-attribute first when set to 'basic'; don't use node.innerText - it's really slow!
// http://www.kellegous.com/j/2013/02/27/innertext-vs-textcontent/
if ( extract === 'basic' && typeof ( tmp = $node.attr( c.textAttribute ) ) !== 'undefined' ) {
return $.trim( tmp );
}
return $.trim( node.textContent || $node.text() );
} else {
if ( typeof extract === 'function' ) {
return $.trim( extract( $node[ 0 ], c.table, cellIndex ) );
} else if ( typeof ( tmp = ts.getColumnData( c.table, extract, cellIndex ) ) === 'function' ) {
return $.trim( tmp( $node[ 0 ], c.table, cellIndex ) );
}
}
// fallback
return $.trim( $node[ 0 ].textContent || $node.text() );
},
// centralized function to extract/parse cell contents
getParsedText : function( c, cell, colIndex, txt ) {
if ( typeof txt === 'undefined' ) {
txt = ts.getElementText( c, cell, colIndex );
}
// if no parser, make sure to return the txt
var val = '' + txt,
parser = c.parsers[ colIndex ],
extractor = c.extractors[ colIndex ];
if ( parser ) {
// do extract before parsing, if there is one
if ( extractor && typeof extractor.format === 'function' ) {
txt = extractor.format( txt, c.table, cell, colIndex );
}
// allow parsing if the string is empty, previously parsing would change it to zero,
// in case the parser needs to extract data from the table cell attributes
val = parser.id === 'no-parser' ? '' :
// make sure txt is a string (extractor may have converted it)
parser.format( '' + txt, c.table, cell, colIndex );
if ( c.ignoreCase && typeof val === 'string' ) {
val = val.toLowerCase();
}
}
return val;
},
/*
▄████▄ ▄████▄ ▄████▄ ██ ██ ██████
██ ▀▀ ██▄▄██ ██ ▀▀ ██▄▄██ ██▄▄
██ ▄▄ ██▀▀██ ██ ▄▄ ██▀▀██ ██▀▀
▀████▀ ██ ██ ▀████▀ ██ ██ ██████
*/
buildCache : function( c, callback, $tbodies ) {
var cache, val, txt, rowIndex, colIndex, tbodyIndex, $tbody, $row,
cols, $cells, cell, cacheTime, totalRows, rowData, prevRowData,
colMax, span, cacheIndex, hasParser, max, len, index,
table = c.table,
parsers = c.parsers;
// update tbody variable
c.$tbodies = c.$table.children( 'tbody:not(.' + c.cssInfoBlock + ')' );
$tbody = typeof $tbodies === 'undefined' ? c.$tbodies : $tbodies,
c.cache = {};
c.totalRows = 0;
// if no parsers found, return - it's an empty table.
if ( !parsers ) {
return c.debug ? console.warn( 'Warning: *Empty table!* Not building a cache' ) : '';
}
if ( c.debug ) {
cacheTime = new Date();
}
// processing icon
if ( c.showProcessing ) {
ts.isProcessing( table, true );
}
for ( tbodyIndex = 0; tbodyIndex < $tbody.length; tbodyIndex++ ) {
colMax = []; // column max value per tbody
cache = c.cache[ tbodyIndex ] = {
normalized: [] // array of normalized row data; last entry contains 'rowData' above
// colMax: # // added at the end
};
totalRows = ( $tbody[ tbodyIndex ] && $tbody[ tbodyIndex ].rows.length ) || 0;
for ( rowIndex = 0; rowIndex < totalRows; ++rowIndex ) {
rowData = {
// order: original row order #
// $row : jQuery Object[]
child: [], // child row text (filter widget)
raw: [] // original row text
};
/** Add the table data to main data array */
$row = $( $tbody[ tbodyIndex ].rows[ rowIndex ] );
cols = [];
// if this is a child row, add it to the last row's children and continue to the next row
// ignore child row class, if it is the first row
if ( $row.hasClass( c.cssChildRow ) && rowIndex !== 0 ) {
len = cache.normalized.length - 1;
prevRowData = cache.normalized[ len ][ c.columns ];
prevRowData.$row = prevRowData.$row.add( $row );
// add 'hasChild' class name to parent row
if ( !$row.prev().hasClass( c.cssChildRow ) ) {
$row.prev().addClass( ts.css.cssHasChild );
}
// save child row content (un-parsed!)
$cells = $row.children( 'th, td' );
len = prevRowData.child.length;
prevRowData.child[ len ] = [];
// child row content does not account for colspans/rowspans; so indexing may be off
cacheIndex = 0;
max = c.columns;
for ( colIndex = 0; colIndex < max; colIndex++ ) {
cell = $cells[ colIndex ];
if ( cell ) {
prevRowData.child[ len ][ colIndex ] = ts.getParsedText( c, cell, colIndex );
span = $cells[ colIndex ].colSpan - 1;
if ( span > 0 ) {
cacheIndex += span;
max += span;
}
}
cacheIndex++;
}
// go to the next for loop
continue;
}
rowData.$row = $row;
rowData.order = rowIndex; // add original row position to rowCache
cacheIndex = 0;
max = c.columns;
for ( colIndex = 0; colIndex < max; ++colIndex ) {
cell = $row[ 0 ].cells[ colIndex ];
if ( cell && cacheIndex < c.columns ) {
hasParser = typeof parsers[ cacheIndex ] !== 'undefined';
if ( !hasParser && c.debug ) {
console.warn( 'No parser found for row: ' + rowIndex + ', column: ' + colIndex +
'; cell containing: "' + $(cell).text() + '"; does it have a header?' );
}
val = ts.getElementText( c, cell, cacheIndex );
rowData.raw[ cacheIndex ] = val; // save original row text
// save raw column text even if there is no parser set
txt = ts.getParsedText( c, cell, cacheIndex, val );
cols[ cacheIndex ] = txt;
if ( hasParser && ( parsers[ cacheIndex ].type || '' ).toLowerCase() === 'numeric' ) {
// determine column max value (ignore sign)
colMax[ cacheIndex ] = Math.max( Math.abs( txt ) || 0, colMax[ cacheIndex ] || 0 );
}
// allow colSpan in tbody
span = cell.colSpan - 1;
if ( span > 0 ) {
index = 0;
while ( index <= span ) {
// duplicate text (or not) to spanned columns
rowData.raw[ cacheIndex + index ] = c.duplicateSpan || index === 0 ? val : '';
cols[ cacheIndex + index ] = c.duplicateSpan || index === 0 ? val : '';
index++;
}
cacheIndex += span;
max += span;
}
}
cacheIndex++;
}
// ensure rowData is always in the same location (after the last column)
cols[ c.columns ] = rowData;
cache.normalized.push( cols );
}
cache.colMax = colMax;
// total up rows, not including child rows
c.totalRows += cache.normalized.length;
}
if ( c.showProcessing ) {
ts.isProcessing( table ); // remove processing icon
}
if ( c.debug ) {
len = Math.min( 5, c.cache[ 0 ].normalized.length );
console[ console.group ? 'group' : 'log' ]( 'Building cache for ' + c.totalRows +
' rows (showing ' + len + ' rows in log)' + ts.benchmark( cacheTime ) );
val = {};
for ( colIndex = 0; colIndex < c.columns; colIndex++ ) {
for ( cacheIndex = 0; cacheIndex < len; cacheIndex++ ) {
if ( !val[ 'row: ' + cacheIndex ] ) {
val[ 'row: ' + cacheIndex ] = {};
}
val[ 'row: ' + cacheIndex ][ c.$headerIndexed[ colIndex ].text() ] =
c.cache[ 0 ].normalized[ cacheIndex ][ colIndex ];
}
}
console[ console.table ? 'table' : 'log' ]( val );
if ( console.groupEnd ) { console.groupEnd(); }
}
if ( $.isFunction( callback ) ) {
callback( table );
}
},
getColumnText : function( table, column, callback, rowFilter ) {
table = $( table )[0];
var tbodyIndex, rowIndex, cache, row, tbodyLen, rowLen, raw, parsed, $cell, result,
hasCallback = typeof callback === 'function',
allColumns = column === 'all',
data = { raw : [], parsed: [], $cell: [] },
c = table.config;
if ( ts.isEmptyObject( c ) ) {
if ( c.debug ) {
console.warn( 'No cache found - aborting getColumnText function!' );
}
} else {
tbodyLen = c.$tbodies.length;
for ( tbodyIndex = 0; tbodyIndex < tbodyLen; tbodyIndex++ ) {
cache = c.cache[ tbodyIndex ].normalized;
rowLen = cache.length;
for ( rowIndex = 0; rowIndex < rowLen; rowIndex++ ) {
row = cache[ rowIndex ];
if ( rowFilter && !row[ c.columns ].$row.is( rowFilter ) ) {
continue;
}
result = true;
parsed = ( allColumns ) ? row.slice( 0, c.columns ) : row[ column ];
row = row[ c.columns ];
raw = ( allColumns ) ? row.raw : row.raw[ column ];
$cell = ( allColumns ) ? row.$row.children() : row.$row.children().eq( column );
if ( hasCallback ) {
result = callback({
tbodyIndex : tbodyIndex,
rowIndex : rowIndex,
parsed : parsed,
raw : raw,
$row : row.$row,
$cell : $cell
});
}
if ( result !== false ) {
data.parsed.push( parsed );
data.raw.push( raw );
data.$cell.push( $cell );
}
}
}
// return everything
return data;
}
},
/*
██ ██ █████▄ █████▄ ▄████▄ ██████ ██████
██ ██ ██▄▄██ ██ ██ ██▄▄██ ██ ██▄▄
██ ██ ██▀▀▀ ██ ██ ██▀▀██ ██ ██▀▀
▀████▀ ██ █████▀ ██ ██ ██ ██████
*/
setHeadersCss : function( c ) {
var $sorted, indx, column,
list = c.sortList,
len = list.length,
none = ts.css.sortNone + ' ' + c.cssNone,
css = [ ts.css.sortAsc + ' ' + c.cssAsc, ts.css.sortDesc + ' ' + c.cssDesc ],
cssIcon = [ c.cssIconAsc, c.cssIconDesc, c.cssIconNone ],
aria = [ 'ascending', 'descending' ],
// find the footer
$headers = c.$table
.find( 'tfoot tr' )
.children()
.add( $( c.namespace + '_extra_headers' ) )
.removeClass( css.join( ' ' ) );
// remove all header information
c.$headers
.removeClass( css.join( ' ' ) )
.addClass( none )
.attr( 'aria-sort', 'none' )
.find( '.' + ts.css.icon )
.removeClass( cssIcon.join( ' ' ) )
.addClass( cssIcon[ 2 ] );
for ( indx = 0; indx < len; indx++ ) {
// direction = 2 means reset!
if ( list[ indx ][ 1 ] !== 2 ) {
// multicolumn sorting updating - see #1005
// .not(function(){}) needs jQuery 1.4
// filter(function(i, el){}) <- el is undefined in jQuery v1.2.6
$sorted = c.$headers.filter( function( i ) {
// only include headers that are in the sortList (this includes colspans)
var include = true,
$el = c.$headers.eq( i ),
col = parseInt( $el.attr( 'data-column' ), 10 ),
end = col + c.$headers[ i ].colSpan;
for ( ; col < end; col++ ) {
include = include ? include || ts.isValueInArray( col, c.sortList ) > -1 : false;
}
return include;
});
// choose the :last in case there are nested columns
$sorted = $sorted
.not( '.sorter-false' )
.filter( '[data-column="' + list[ indx ][ 0 ] + '"]' + ( len === 1 ? ':last' : '' ) );
if ( $sorted.length ) {
for ( column = 0; column < $sorted.length; column++ ) {
if ( !$sorted[ column ].sortDisabled ) {
$sorted
.eq( column )
.removeClass( none )
.addClass( css[ list[ indx ][ 1 ] ] )
.attr( 'aria-sort', aria[ list[ indx ][ 1 ] ] )
.find( '.' + ts.css.icon )
.removeClass( cssIcon[ 2 ] )
.addClass( cssIcon[ list[ indx ][ 1 ] ] );
}
}
// add sorted class to footer & extra headers, if they exist
if ( $headers.length ) {
$headers
.filter( '[data-column="' + list[ indx ][ 0 ] + '"]' )
.removeClass( none )
.addClass( css[ list[ indx ][ 1 ] ] );
}
}
}
}
// add verbose aria labels
len = c.$headers.length;
for ( indx = 0; indx < len; indx++ ) {
ts.setColumnAriaLabel( c, c.$headers.eq( indx ) );
}
},
// nextSort (optional), lets you disable next sort text
setColumnAriaLabel : function( c, $header, nextSort ) {
if ( $header.length ) {
var column = parseInt( $header.attr( 'data-column' ), 10 ),
tmp = $header.hasClass( ts.css.sortAsc ) ?
'sortAsc' :
$header.hasClass( ts.css.sortDesc ) ? 'sortDesc' : 'sortNone',
txt = $.trim( $header.text() ) + ': ' + ts.language[ tmp ];
if ( $header.hasClass( 'sorter-false' ) || nextSort === false ) {
txt += ts.language.sortDisabled;
} else {
nextSort = c.sortVars[ column ].order[ ( c.sortVars[ column ].count + 1 ) % ( c.sortReset ? 3 : 2 ) ];
// if nextSort
txt += ts.language[ nextSort === 0 ? 'nextAsc' : nextSort === 1 ? 'nextDesc' : 'nextNone' ];
}
$header.attr( 'aria-label', txt );
}
},
updateHeader : function( c ) {
var index, isDisabled, $header, col,
table = c.table,
len = c.$headers.length;
for ( index = 0; index < len; index++ ) {
$header = c.$headers.eq( index );
col = ts.getColumnData( table, c.headers, index, true );
// add 'sorter-false' class if 'parser-false' is set
isDisabled = ts.getData( $header, col, 'sorter' ) === 'false' || ts.getData( $header, col, 'parser' ) === 'false';
ts.setColumnSort( c, $header, isDisabled );
}
},
setColumnSort : function( c, $header, isDisabled ) {
var id = c.table.id;
$header[ 0 ].sortDisabled = isDisabled;
$header[ isDisabled ? 'addClass' : 'removeClass' ]( 'sorter-false' )
.attr( 'aria-disabled', '' + isDisabled );
// disable tab index on disabled cells
if ( c.tabIndex ) {
if ( isDisabled ) {
$header.removeAttr( 'tabindex' );
} else {
$header.attr( 'tabindex', '0' );
}
}
// aria-controls - requires table ID
if ( id ) {
if ( isDisabled ) {
$header.removeAttr( 'aria-controls' );
} else {
$header.attr( 'aria-controls', id );
}
}
},
updateHeaderSortCount : function( c, list ) {
var col, dir, group, indx, primary, temp, val, order,
sortList = list || c.sortList,
len = sortList.length;
c.sortList = [];
for ( indx = 0; indx < len; indx++ ) {
val = sortList[ indx ];
// ensure all sortList values are numeric - fixes #127
col = parseInt( val[ 0 ], 10 );
// prevents error if sorton array is wrong
if ( col < c.columns ) {
// set order if not already defined - due to colspan header without associated header cell
// adding this check prevents a javascript error
if ( !c.sortVars[ col ].order ) {
order = c.sortVars[ col ].order = ts.getOrder( c.sortInitialOrder ) ? [ 1, 0, 2 ] : [ 0, 1, 2 ];
c.sortVars[ col ].count = 0;
}
order = c.sortVars[ col ].order;
dir = ( '' + val[ 1 ] ).match( /^(1|d|s|o|n)/ );
dir = dir ? dir[ 0 ] : '';
// 0/(a)sc (default), 1/(d)esc, (s)ame, (o)pposite, (n)ext
switch ( dir ) {
case '1' : case 'd' : // descending
dir = 1;
break;
case 's' : // same direction (as primary column)
// if primary sort is set to 's', make it ascending
dir = primary || 0;
break;
case 'o' :
temp = order[ ( primary || 0 ) % ( c.sortReset ? 3 : 2 ) ];
// opposite of primary column; but resets if primary resets
dir = temp === 0 ? 1 : temp === 1 ? 0 : 2;
break;
case 'n' :
dir = order[ ( ++c.sortVars[ col ].count ) % ( c.sortReset ? 3 : 2 ) ];
break;
default : // ascending
dir = 0;
break;
}
primary = indx === 0 ? dir : primary;
group = [ col, parseInt( dir, 10 ) || 0 ];
c.sortList.push( group );
dir = $.inArray( group[ 1 ], order ); // fixes issue #167
c.sortVars[ col ].count = dir >= 0 ? dir : group[ 1 ] % ( c.sortReset ? 3 : 2 );
}
}
},
updateAll : function( c, resort, callback ) {
var table = c.table;
table.isUpdating = true;
ts.refreshWidgets( table, true, true );
ts.buildHeaders( c );
ts.bindEvents( table, c.$headers, true );
ts.bindMethods( c );
ts.commonUpdate( c, resort, callback );
},
update : function( c, resort, callback ) {
var table = c.table;
table.isUpdating = true;
// update sorting (if enabled/disabled)
ts.updateHeader( c );
ts.commonUpdate( c, resort, callback );
},
// simple header update - see #989
updateHeaders : function( c, callback ) {
c.table.isUpdating = true;
ts.buildHeaders( c );
ts.bindEvents( c.table, c.$headers, true );
ts.resortComplete( c, callback );
},
updateCell : function( c, cell, resort, callback ) {
if ( ts.isEmptyObject( c.cache ) ) {
// empty table, do an update instead - fixes #1099
ts.updateHeader( c );
ts.commonUpdate( c, resort, callback );
return;
}
c.table.isUpdating = true;
c.$table.find( c.selectorRemove ).remove();
// get position from the dom
var tmp, indx, row, icell, cache, len,
$tbodies = c.$tbodies,
$cell = $( cell ),
// update cache - format: function( s, table, cell, cellIndex )
// no closest in jQuery v1.2.6
tbodyIndex = $tbodies
.index( $.fn.closest ? $cell.closest( 'tbody' ) : $cell.parents( 'tbody' ).filter( ':first' ) ),
tbcache = c.cache[ tbodyIndex ],
$row = $.fn.closest ? $cell.closest( 'tr' ) : $cell.parents( 'tr' ).filter( ':first' );
cell = $cell[ 0 ]; // in case cell is a jQuery object
// tbody may not exist if update is initialized while tbody is removed for processing
if ( $tbodies.length && tbodyIndex >= 0 ) {
row = $tbodies.eq( tbodyIndex ).find( 'tr' ).index( $row );
cache = tbcache.normalized[ row ];
len = $row[ 0 ].cells.length;
if ( len !== c.columns ) {
// colspan in here somewhere!
icell = 0;
tmp = false;
for ( indx = 0; indx < len; indx++ ) {
if ( !tmp && $row[ 0 ].cells[ indx ] !== cell ) {
icell += $row[ 0 ].cells[ indx ].colSpan;
} else {
tmp = true;
}
}
} else {
icell = $cell.index();
}
tmp = ts.getElementText( c, cell, icell ); // raw
cache[ c.columns ].raw[ icell ] = tmp;
tmp = ts.getParsedText( c, cell, icell, tmp );
cache[ icell ] = tmp; // parsed
cache[ c.columns ].$row = $row;
if ( ( c.parsers[ icell ].type || '' ).toLowerCase() === 'numeric' ) {
// update column max value (ignore sign)
tbcache.colMax[ icell ] = Math.max( Math.abs( tmp ) || 0, tbcache.colMax[ icell ] || 0 );
}
tmp = resort !== 'undefined' ? resort : c.resort;
if ( tmp !== false ) {
// widgets will be reapplied
ts.checkResort( c, tmp, callback );
} else {
// don't reapply widgets is resort is false, just in case it causes
// problems with element focus
ts.resortComplete( c, callback );
}
} else {
if ( c.debug ) {
console.error( 'updateCell aborted, tbody missing or not within the indicated table' );
}
c.table.isUpdating = false;
}
},
addRows : function( c, $row, resort, callback ) {
var txt, val, tbodyIndex, rowIndex, rows, cellIndex, len,
cacheIndex, rowData, cells, cell, span,
// allow passing a row string if only one non-info tbody exists in the table
valid = typeof $row === 'string' && c.$tbodies.length === 1 && /<tr/.test( $row || '' ),
table = c.table;
if ( valid ) {
$row = $( $row );
c.$tbodies.append( $row );
} else if ( !$row ||
// row is a jQuery object?
!( $row instanceof jQuery ) ||
// row contained in the table?
( $.fn.closest ? $row.closest( 'table' )[ 0 ] : $row.parents( 'table' )[ 0 ] ) !== c.table ) {
if ( c.debug ) {
console.error( 'addRows method requires (1) a jQuery selector reference to rows that have already ' +
'been added to the table, or (2) row HTML string to be added to a table with only one tbody' );
}
return false;
}
table.isUpdating = true;
if ( ts.isEmptyObject( c.cache ) ) {
// empty table, do an update instead - fixes #450
ts.updateHeader( c );
ts.commonUpdate( c, resort, callback );
} else {
rows = $row.filter( 'tr' ).attr( 'role', 'row' ).length;
tbodyIndex = c.$tbodies.index( $row.parents( 'tbody' ).filter( ':first' ) );
// fixes adding rows to an empty table - see issue #179
if ( !( c.parsers && c.parsers.length ) ) {
ts.setupParsers( c );
}
// add each row
for ( rowIndex = 0; rowIndex < rows; rowIndex++ ) {
cacheIndex = 0;
len = $row[ rowIndex ].cells.length;
cells = [];
rowData = {
child : [],
raw : [],
$row : $row.eq( rowIndex ),
order : c.cache[ tbodyIndex ].normalized.length
};
// add each cell
for ( cellIndex = 0; cellIndex < len; cellIndex++ ) {
cell = $row[ rowIndex ].cells[ cellIndex ];
txt = ts.getElementText( c, cell, cacheIndex );
rowData.raw[ cacheIndex ] = txt;
val = ts.getParsedText( c, cell, cacheIndex, txt );
cells[ cacheIndex ] = val;
if ( ( c.parsers[ cacheIndex ].type || '' ).toLowerCase() === 'numeric' ) {
// update column max value (ignore sign)
c.cache[ tbodyIndex ].colMax[ cacheIndex ] =
Math.max( Math.abs( val ) || 0, c.cache[ tbodyIndex ].colMax[ cacheIndex ] || 0 );
}
span = cell.colSpan - 1;
if ( span > 0 ) {
cacheIndex += span;
}
cacheIndex++;
}
// add the row data to the end
cells[ c.columns ] = rowData;
// update cache
c.cache[ tbodyIndex ].normalized.push( cells );
}
// resort using current settings
ts.checkResort( c, resort, callback );
}
},
updateCache : function( c, callback, $tbodies ) {
// rebuild parsers
if ( !( c.parsers && c.parsers.length ) ) {
ts.setupParsers( c, $tbodies );
}
// rebuild the cache map
ts.buildCache( c, callback, $tbodies );
},
// init flag (true) used by pager plugin to prevent widget application
// renamed from appendToTable
appendCache : function( c, init ) {
var parsed, totalRows, $tbody, $curTbody, rowIndex, tbodyIndex, appendTime,
table = c.table,
wo = c.widgetOptions,
$tbodies = c.$tbodies,
rows = [],
cache = c.cache;
// empty table - fixes #206/#346
if ( ts.isEmptyObject( cache ) ) {
// run pager appender in case the table was just emptied
return c.appender ? c.appender( table, rows ) :
table.isUpdating ? c.$table.triggerHandler( 'updateComplete', table ) : ''; // Fixes #532
}
if ( c.debug ) {
appendTime = new Date();
}
for ( tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ) {
$tbody = $tbodies.eq( tbodyIndex );
if ( $tbody.length ) {
// detach tbody for manipulation
$curTbody = ts.processTbody( table, $tbody, true );
parsed = cache[ tbodyIndex ].normalized;
totalRows = parsed.length;
for ( rowIndex = 0; rowIndex < totalRows; rowIndex++ ) {
rows.push( parsed[ rowIndex ][ c.columns ].$row );
// removeRows used by the pager plugin; don't render if using ajax - fixes #411
if ( !c.appender || ( c.pager && ( !c.pager.removeRows || !wo.pager_removeRows ) && !c.pager.ajax ) ) {
$curTbody.append( parsed[ rowIndex ][ c.columns ].$row );
}
}
// restore tbody
ts.processTbody( table, $curTbody, false );
}
}
if ( c.appender ) {
c.appender( table, rows );
}
if ( c.debug ) {
console.log( 'Rebuilt table' + ts.benchmark( appendTime ) );
}
// apply table widgets; but not before ajax completes
if ( !init && !c.appender ) {
ts.applyWidget( table );
}
if ( table.isUpdating ) {
c.$table.triggerHandler( 'updateComplete', table );
}
},
commonUpdate : function( c, resort, callback ) {
// remove rows/elements before update
c.$table.find( c.selectorRemove ).remove();
// rebuild parsers
ts.setupParsers( c );
// rebuild the cache map
ts.buildCache( c );
ts.checkResort( c, resort, callback );
},
/*
▄█████ ▄████▄ █████▄ ██████ ██ █████▄ ▄████▄
▀█▄ ██ ██ ██▄▄██ ██ ██ ██ ██ ██ ▄▄▄
▀█▄ ██ ██ ██▀██ ██ ██ ██ ██ ██ ▀██
█████▀ ▀████▀ ██ ██ ██ ██ ██ ██ ▀████▀
*/
initSort : function( c, cell, event ) {
if ( c.table.isUpdating ) {
// let any updates complete before initializing a sort
return setTimeout( function(){
ts.initSort( c, cell, event );
}, 50 );
}
var arry, indx, headerIndx, dir, temp, tmp, $header,
notMultiSort = !event[ c.sortMultiSortKey ],
table = c.table,
len = c.$headers.length,
// get current column index
col = parseInt( $( cell ).attr( 'data-column' ), 10 ),
order = c.sortVars[ col ].order;
// Only call sortStart if sorting is enabled
c.$table.triggerHandler( 'sortStart', table );
// get current column sort order
c.sortVars[ col ].count =
event[ c.sortResetKey ] ? 2 : ( c.sortVars[ col ].count + 1 ) % ( c.sortReset ? 3 : 2 );
// reset all sorts on non-current column - issue #30
if ( c.sortRestart ) {
for ( headerIndx = 0; headerIndx < len; headerIndx++ ) {
$header = c.$headers.eq( headerIndx );
tmp = parseInt( $header.attr( 'data-column' ), 10 );
// only reset counts on columns that weren't just clicked on and if not included in a multisort
if ( col !== tmp && ( notMultiSort || $header.hasClass( ts.css.sortNone ) ) ) {
c.sortVars[ tmp ].count = -1;
}
}
}
// user only wants to sort on one column
if ( notMultiSort ) {
// flush the sort list
c.sortList = [];
c.last.sortList = [];
if ( c.sortForce !== null ) {
arry = c.sortForce;
for ( indx = 0; indx < arry.length; indx++ ) {
if ( arry[ indx ][ 0 ] !== col ) {
c.sortList.push( arry[ indx ] );
}
}
}
// add column to sort list
dir = order[ c.sortVars[ col ].count ];
if ( dir < 2 ) {
c.sortList.push( [ col, dir ] );
// add other columns if header spans across multiple
if ( cell.colSpan > 1 ) {
for ( indx = 1; indx < cell.colSpan; indx++ ) {
c.sortList.push( [ col + indx, dir ] );
// update count on columns in colSpan
c.sortVars[ col + indx ].count = $.inArray( dir, order );
}
}
}
// multi column sorting
} else {
// get rid of the sortAppend before adding more - fixes issue #115 & #523
c.sortList = $.extend( [], c.last.sortList );
// the user has clicked on an already sorted column
if ( ts.isValueInArray( col, c.sortList ) >= 0 ) {
// reverse the sorting direction
for ( indx = 0; indx < c.sortList.length; indx++ ) {
tmp = c.sortList[ indx ];
if ( tmp[ 0 ] === col ) {
// order.count seems to be incorrect when compared to cell.count
tmp[ 1 ] = order[ c.sortVars[ col ].count ];
if ( tmp[1] === 2 ) {
c.sortList.splice( indx, 1 );
c.sortVars[ col ].count = -1;
}
}
}
} else {
// add column to sort list array
dir = order[ c.sortVars[ col ].count ];
if ( dir < 2 ) {
c.sortList.push( [ col, dir ] );
// add other columns if header spans across multiple
if ( cell.colSpan > 1 ) {
for ( indx = 1; indx < cell.colSpan; indx++ ) {
c.sortList.push( [ col + indx, dir ] );
// update count on columns in colSpan
c.sortVars[ col + indx ].count = $.inArray( dir, order );
}
}
}
}
}
// save sort before applying sortAppend
c.last.sortList = $.extend( [], c.sortList );
if ( c.sortList.length && c.sortAppend ) {
arry = $.isArray( c.sortAppend ) ? c.sortAppend : c.sortAppend[ c.sortList[ 0 ][ 0 ] ];
if ( !ts.isEmptyObject( arry ) ) {
for ( indx = 0; indx < arry.length; indx++ ) {
if ( arry[ indx ][ 0 ] !== col && ts.isValueInArray( arry[ indx ][ 0 ], c.sortList ) < 0 ) {
dir = arry[ indx ][ 1 ];
temp = ( '' + dir ).match( /^(a|d|s|o|n)/ );
if ( temp ) {
tmp = c.sortList[ 0 ][ 1 ];
switch ( temp[ 0 ] ) {
case 'd' :
dir = 1;
break;
case 's' :
dir = tmp;
break;
case 'o' :
dir = tmp === 0 ? 1 : 0;
break;
case 'n' :
dir = ( tmp + 1 ) % ( c.sortReset ? 3 : 2 );
break;
default:
dir = 0;
break;
}
}
c.sortList.push( [ arry[ indx ][ 0 ], dir ] );
}
}
}
}
// sortBegin event triggered immediately before the sort
c.$table.triggerHandler( 'sortBegin', table );
// setTimeout needed so the processing icon shows up
setTimeout( function() {
// set css for headers
ts.setHeadersCss( c );
ts.multisort( c );
ts.appendCache( c );
c.$table.triggerHandler( 'sortBeforeEnd', table );
c.$table.triggerHandler( 'sortEnd', table );
}, 1 );
},
// sort multiple columns
multisort : function( c ) { /*jshint loopfunc:true */
var tbodyIndex, sortTime, colMax, rows,
table = c.table,
dir = 0,
textSorter = c.textSorter || '',
sortList = c.sortList,
sortLen = sortList.length,
len = c.$tbodies.length;
if ( c.serverSideSorting || ts.isEmptyObject( c.cache ) ) {
// empty table - fixes #206/#346
return;
}
if ( c.debug ) { sortTime = new Date(); }
for ( tbodyIndex = 0; tbodyIndex < len; tbodyIndex++ ) {
colMax = c.cache[ tbodyIndex ].colMax;
rows = c.cache[ tbodyIndex ].normalized;
rows.sort( function( a, b ) {
var sortIndex, num, col, order, sort, x, y;
// rows is undefined here in IE, so don't use it!
for ( sortIndex = 0; sortIndex < sortLen; sortIndex++ ) {
col = sortList[ sortIndex ][ 0 ];
order = sortList[ sortIndex ][ 1 ];
// sort direction, true = asc, false = desc
dir = order === 0;
if ( c.sortStable && a[ col ] === b[ col ] && sortLen === 1 ) {
return a[ c.columns ].order - b[ c.columns ].order;
}
// fallback to natural sort since it is more robust
num = /n/i.test( ts.getSortType( c.parsers, col ) );
if ( num && c.strings[ col ] ) {
// sort strings in numerical columns
if ( typeof ( ts.string[ c.strings[ col ] ] ) === 'boolean' ) {
num = ( dir ? 1 : -1 ) * ( ts.string[ c.strings[ col ] ] ? -1 : 1 );
} else {
num = ( c.strings[ col ] ) ? ts.string[ c.strings[ col ] ] || 0 : 0;
}
// fall back to built-in numeric sort
// var sort = $.tablesorter['sort' + s]( a[col], b[col], dir, colMax[col], table );
sort = c.numberSorter ? c.numberSorter( a[ col ], b[ col ], dir, colMax[ col ], table ) :
ts[ 'sortNumeric' + ( dir ? 'Asc' : 'Desc' ) ]( a[ col ], b[ col ], num, colMax[ col ], col, c );
} else {
// set a & b depending on sort direction
x = dir ? a : b;
y = dir ? b : a;
// text sort function
if ( typeof textSorter === 'function' ) {
// custom OVERALL text sorter
sort = textSorter( x[ col ], y[ col ], dir, col, table );
} else if ( typeof textSorter === 'object' && textSorter.hasOwnProperty( col ) ) {
// custom text sorter for a SPECIFIC COLUMN
sort = textSorter[ col ]( x[ col ], y[ col ], dir, col, table );
} else {
// fall back to natural sort
sort = ts[ 'sortNatural' + ( dir ? 'Asc' : 'Desc' ) ]( a[ col ], b[ col ], col, c );
}
}
if ( sort ) { return sort; }
}
return a[ c.columns ].order - b[ c.columns ].order;
});
}
if ( c.debug ) {
console.log( 'Applying sort ' + sortList.toString() + ts.benchmark( sortTime ) );
}
},
resortComplete : function( c, callback ) {
if ( c.table.isUpdating ) {
c.$table.triggerHandler( 'updateComplete', c.table );
}
if ( $.isFunction( callback ) ) {
callback( c.table );
}
},
checkResort : function( c, resort, callback ) {
var sortList = $.isArray( resort ) ? resort : c.sortList,
// if no resort parameter is passed, fallback to config.resort (true by default)
resrt = typeof resort === 'undefined' ? c.resort : resort;
// don't try to resort if the table is still processing
// this will catch spamming of the updateCell method
if ( resrt !== false && !c.serverSideSorting && !c.table.isProcessing ) {
if ( sortList.length ) {
ts.sortOn( c, sortList, function() {
ts.resortComplete( c, callback );
}, true );
} else {
ts.sortReset( c, function() {
ts.resortComplete( c, callback );
ts.applyWidget( c.table, false );
} );
}
} else {
ts.resortComplete( c, callback );
ts.applyWidget( c.table, false );
}
},
sortOn : function( c, list, callback, init ) {
var table = c.table;
c.$table.triggerHandler( 'sortStart', table );
// update header count index
ts.updateHeaderSortCount( c, list );
// set css for headers
ts.setHeadersCss( c );
// fixes #346
if ( c.delayInit && ts.isEmptyObject( c.cache ) ) {
ts.buildCache( c );
}
c.$table.triggerHandler( 'sortBegin', table );
// sort the table and append it to the dom
ts.multisort( c );
ts.appendCache( c, init );
c.$table.triggerHandler( 'sortBeforeEnd', table );
c.$table.triggerHandler( 'sortEnd', table );
ts.applyWidget( table );
if ( $.isFunction( callback ) ) {
callback( table );
}
},
sortReset : function( c, callback ) {
c.sortList = [];
ts.setHeadersCss( c );
ts.multisort( c );
ts.appendCache( c );
if ( $.isFunction( callback ) ) {
callback( c.table );
}
},
getSortType : function( parsers, column ) {
return ( parsers && parsers[ column ] ) ? parsers[ column ].type || '' : '';
},
getOrder : function( val ) {
// look for 'd' in 'desc' order; return true
return ( /^d/i.test( val ) || val === 1 );
},
// Natural sort - https://github.com/overset/javascript-natural-sort (date sorting removed)
// this function will only accept strings, or you'll see 'TypeError: undefined is not a function'
// I could add a = a.toString(); b = b.toString(); but it'll slow down the sort overall
sortNatural : function( a, b ) {
if ( a === b ) { return 0; }
var aNum, bNum, aFloat, bFloat, indx, max,
regex = ts.regex;
// first try and sort Hex codes
if ( regex.hex.test( b ) ) {
aNum = parseInt( a.match( regex.hex ), 16 );
bNum = parseInt( b.match( regex.hex ), 16 );
if ( aNum < bNum ) { return -1; }
if ( aNum > bNum ) { return 1; }
}
// chunk/tokenize
aNum = a.replace( regex.chunk, '\\0$1\\0' ).replace( regex.chunks, '' ).split( '\\0' );
bNum = b.replace( regex.chunk, '\\0$1\\0' ).replace( regex.chunks, '' ).split( '\\0' );
max = Math.max( aNum.length, bNum.length );
// natural sorting through split numeric strings and default strings
for ( indx = 0; indx < max; indx++ ) {
// find floats not starting with '0', string or 0 if not defined
aFloat = isNaN( aNum[ indx ] ) ? aNum[ indx ] || 0 : parseFloat( aNum[ indx ] ) || 0;
bFloat = isNaN( bNum[ indx ] ) ? bNum[ indx ] || 0 : parseFloat( bNum[ indx ] ) || 0;
// handle numeric vs string comparison - number < string - (Kyle Adams)
if ( isNaN( aFloat ) !== isNaN( bFloat ) ) { return isNaN( aFloat ) ? 1 : -1; }
// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
if ( typeof aFloat !== typeof bFloat ) {
aFloat += '';
bFloat += '';
}
if ( aFloat < bFloat ) { return -1; }
if ( aFloat > bFloat ) { return 1; }
}
return 0;
},
sortNaturalAsc : function( a, b, col, c ) {
if ( a === b ) { return 0; }
var empty = ts.string[ ( c.empties[ col ] || c.emptyTo ) ];
if ( a === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? -1 : 1 ) : -empty || -1; }
if ( b === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? 1 : -1 ) : empty || 1; }
return ts.sortNatural( a, b );
},
sortNaturalDesc : function( a, b, col, c ) {
if ( a === b ) { return 0; }
var empty = ts.string[ ( c.empties[ col ] || c.emptyTo ) ];
if ( a === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? -1 : 1 ) : empty || 1; }
if ( b === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? 1 : -1 ) : -empty || -1; }
return ts.sortNatural( b, a );
},
// basic alphabetical sort
sortText : function( a, b ) {
return a > b ? 1 : ( a < b ? -1 : 0 );
},
// return text string value by adding up ascii value
// so the text is somewhat sorted when using a digital sort
// this is NOT an alphanumeric sort
getTextValue : function( val, num, max ) {
if ( max ) {
// make sure the text value is greater than the max numerical value (max)
var indx,
len = val ? val.length : 0,
n = max + num;
for ( indx = 0; indx < len; indx++ ) {
n += val.charCodeAt( indx );
}
return num * n;
}
return 0;
},
sortNumericAsc : function( a, b, num, max, col, c ) {
if ( a === b ) { return 0; }
var empty = ts.string[ ( c.empties[ col ] || c.emptyTo ) ];
if ( a === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? -1 : 1 ) : -empty || -1; }
if ( b === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? 1 : -1 ) : empty || 1; }
if ( isNaN( a ) ) { a = ts.getTextValue( a, num, max ); }
if ( isNaN( b ) ) { b = ts.getTextValue( b, num, max ); }
return a - b;
},
sortNumericDesc : function( a, b, num, max, col, c ) {
if ( a === b ) { return 0; }
var empty = ts.string[ ( c.empties[ col ] || c.emptyTo ) ];
if ( a === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? -1 : 1 ) : empty || 1; }
if ( b === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? 1 : -1 ) : -empty || -1; }
if ( isNaN( a ) ) { a = ts.getTextValue( a, num, max ); }
if ( isNaN( b ) ) { b = ts.getTextValue( b, num, max ); }
return b - a;
},
sortNumeric : function( a, b ) {
return a - b;
},
/*
██ ██ ██ ██ █████▄ ▄████▄ ██████ ██████ ▄█████
██ ██ ██ ██ ██ ██ ██ ▄▄▄ ██▄▄ ██ ▀█▄
██ ██ ██ ██ ██ ██ ██ ▀██ ██▀▀ ██ ▀█▄
███████▀ ██ █████▀ ▀████▀ ██████ ██ █████▀
*/
addWidget : function( widget ) {
ts.widgets.push( widget );
},
hasWidget : function( $table, name ) {
$table = $( $table );
return $table.length && $table[ 0 ].config && $table[ 0 ].config.widgetInit[ name ] || false;
},
getWidgetById : function( name ) {
var indx, widget,
len = ts.widgets.length;
for ( indx = 0; indx < len; indx++ ) {
widget = ts.widgets[ indx ];
if ( widget && widget.id && widget.id.toLowerCase() === name.toLowerCase() ) {
return widget;
}
}
},
applyWidgetOptions : function( table ) {
var indx, widget,
c = table.config,
len = c.widgets.length;
if ( len ) {
for ( indx = 0; indx < len; indx++ ) {
widget = ts.getWidgetById( c.widgets[ indx ] );
if ( widget && widget.options ) {
c.widgetOptions = $.extend( true, {}, widget.options, c.widgetOptions );
}
}
}
},
addWidgetFromClass : function( table ) {
var len, indx,
c = table.config,
// look for widgets to apply from table class
// stop using \b otherwise this matches 'ui-widget-content' & adds 'content' widget
regex = '\\s' + c.widgetClass.replace( ts.regex.templateName, '([\\w-]+)' ) + '\\s',
widgetClass = new RegExp( regex, 'g' ),
// extract out the widget id from the table class (widget id's can include dashes)
widget = ( ' ' + c.table.className + ' ' ).match( widgetClass );
if ( widget ) {
len = widget.length;
for ( indx = 0; indx < len; indx++ ) {
c.widgets.push( widget[ indx ].replace( widgetClass, '$1' ) );
}
}
},
applyWidgetId : function( table, id, init ) {
var applied, time, name,
c = table.config,
wo = c.widgetOptions,
widget = ts.getWidgetById( id );
if ( widget ) {
name = widget.id;
applied = false;
// add widget name to option list so it gets reapplied after sorting, filtering, etc
if ( $.inArray( name, c.widgets ) < 0 ) {
c.widgets.push( name );
}
if ( c.debug ) { time = new Date(); }
if ( init || !( c.widgetInit[ name ] ) ) {
// set init flag first to prevent calling init more than once (e.g. pager)
c.widgetInit[ name ] = true;
if ( table.hasInitialized ) {
// don't reapply widget options on tablesorter init
ts.applyWidgetOptions( table );
}
if ( typeof widget.init === 'function' ) {
applied = true;
if ( c.debug ) {
console[ console.group ? 'group' : 'log' ]( 'Initializing ' + name + ' widget' );
}
widget.init( table, widget, c, wo );
}
}
if ( !init && typeof widget.format === 'function' ) {
applied = true;
if ( c.debug ) {
console[ console.group ? 'group' : 'log' ]( 'Updating ' + name + ' widget' );
}
widget.format( table, c, wo, false );
}
if ( c.debug ) {
if ( applied ) {
console.log( 'Completed ' + ( init ? 'initializing ' : 'applying ' ) + name + ' widget' + ts.benchmark( time ) );
if ( console.groupEnd ) { console.groupEnd(); }
}
}
}
},
applyWidget : function( table, init, callback ) {
table = $( table )[ 0 ]; // in case this is called externally
var indx, len, names, widget, time,
c = table.config,
widgets = [];
// prevent numerous consecutive widget applications
if ( init !== false && table.hasInitialized && ( table.isApplyingWidgets || table.isUpdating ) ) {
return;
}
if ( c.debug ) { time = new Date(); }
ts.addWidgetFromClass( table );
// prevent "tablesorter-ready" from firing multiple times in a row
clearTimeout( c.timerReady );
if ( c.widgets.length ) {
table.isApplyingWidgets = true;
// ensure unique widget ids
c.widgets = $.grep( c.widgets, function( val, index ) {
return $.inArray( val, c.widgets ) === index;
});
names = c.widgets || [];
len = names.length;
// build widget array & add priority as needed
for ( indx = 0; indx < len; indx++ ) {
widget = ts.getWidgetById( names[ indx ] );
if ( widget && widget.id ) {
// set priority to 10 if not defined
if ( !widget.priority ) { widget.priority = 10; }
widgets[ indx ] = widget;
}
}
// sort widgets by priority
widgets.sort( function( a, b ) {
return a.priority < b.priority ? -1 : a.priority === b.priority ? 0 : 1;
});
// add/update selected widgets
len = widgets.length;
if ( c.debug ) {
console[ console.group ? 'group' : 'log' ]( 'Start ' + ( init ? 'initializing' : 'applying' ) + ' widgets' );
}
for ( indx = 0; indx < len; indx++ ) {
widget = widgets[ indx ];
if ( widget && widget.id ) {
ts.applyWidgetId( table, widget.id, init );
}
}
if ( c.debug && console.groupEnd ) { console.groupEnd(); }
// callback executed on init only
if ( !init && typeof callback === 'function' ) {
callback( table );
}
}
c.timerReady = setTimeout( function() {
table.isApplyingWidgets = false;
$.data( table, 'lastWidgetApplication', new Date() );
c.$table.triggerHandler( 'tablesorter-ready' );
}, 10 );
if ( c.debug ) {
widget = c.widgets.length;
console.log( 'Completed ' +
( init === true ? 'initializing ' : 'applying ' ) + widget +
' widget' + ( widget !== 1 ? 's' : '' ) + ts.benchmark( time ) );
}
},
removeWidget : function( table, name, refreshing ) {
table = $( table )[ 0 ];
var index, widget, indx, len,
c = table.config;
// if name === true, add all widgets from $.tablesorter.widgets
if ( name === true ) {
name = [];
len = ts.widgets.length;
for ( indx = 0; indx < len; indx++ ) {
widget = ts.widgets[ indx ];
if ( widget && widget.id ) {
name.push( widget.id );
}
}
} else {
// name can be either an array of widgets names,
// or a space/comma separated list of widget names
name = ( $.isArray( name ) ? name.join( ',' ) : name || '' ).toLowerCase().split( /[\s,]+/ );
}
len = name.length;
for ( index = 0; index < len; index++ ) {
widget = ts.getWidgetById( name[ index ] );
indx = $.inArray( name[ index ], c.widgets );
if ( widget && widget.remove ) {
if ( c.debug ) {
console.log( ( refreshing ? 'Refreshing' : 'Removing' ) + ' "' + name[ index ] + '" widget' );
}
widget.remove( table, c, c.widgetOptions, refreshing );
c.widgetInit[ name[ index ] ] = false;
}
// don't remove the widget from config.widget if refreshing
if ( indx >= 0 && refreshing !== true ) {
c.widgets.splice( indx, 1 );
}
}
},
refreshWidgets : function( table, doAll, dontapply ) {
table = $( table )[ 0 ]; // see issue #243
var indx, widget,
c = table.config,
curWidgets = c.widgets,
widgets = ts.widgets,
len = widgets.length,
list = [],
callback = function( table ) {
$( table ).triggerHandler( 'refreshComplete' );
};
// remove widgets not defined in config.widgets, unless doAll is true
for ( indx = 0; indx < len; indx++ ) {
widget = widgets[ indx ];
if ( widget && widget.id && ( doAll || $.inArray( widget.id, curWidgets ) < 0 ) ) {
list.push( widget.id );
}
}
ts.removeWidget( table, list.join( ',' ), true );
if ( dontapply !== true ) {
// call widget init if
ts.applyWidget( table, doAll || false, callback );
if ( doAll ) {
// apply widget format
ts.applyWidget( table, false, callback );
}
} else {
callback( table );
}
},
/*
██ ██ ██████ ██ ██ ██ ██████ ██ ██████ ▄█████
██ ██ ██ ██ ██ ██ ██ ██ ██▄▄ ▀█▄
██ ██ ██ ██ ██ ██ ██ ██ ██▀▀ ▀█▄
▀████▀ ██ ██ ██████ ██ ██ ██ ██████ █████▀
*/
benchmark : function( diff ) {
return ( ' ( ' + ( new Date().getTime() - diff.getTime() ) + 'ms )' );
},
// deprecated ts.log
log : function() {
console.log( arguments );
},
// $.isEmptyObject from jQuery v1.4
isEmptyObject : function( obj ) {
/*jshint forin: false */
for ( var name in obj ) {
return false;
}
return true;
},
isValueInArray : function( column, arry ) {
var indx,
len = arry && arry.length || 0;
for ( indx = 0; indx < len; indx++ ) {
if ( arry[ indx ][ 0 ] === column ) {
return indx;
}
}
return -1;
},
formatFloat : function( str, table ) {
if ( typeof str !== 'string' || str === '' ) { return str; }
// allow using formatFloat without a table; defaults to US number format
var num,
usFormat = table && table.config ? table.config.usNumberFormat !== false :
typeof table !== 'undefined' ? table : true;
if ( usFormat ) {
// US Format - 1,234,567.89 -> 1234567.89
str = str.replace( ts.regex.comma, '' );
} else {
// German Format = 1.234.567,89 -> 1234567.89
// French Format = 1 234 567,89 -> 1234567.89
str = str.replace( ts.regex.digitNonUS, '' ).replace( ts.regex.comma, '.' );
}
if ( ts.regex.digitNegativeTest.test( str ) ) {
// make (#) into a negative number -> (10) = -10
str = str.replace( ts.regex.digitNegativeReplace, '-$1' );
}
num = parseFloat( str );
// return the text instead of zero
return isNaN( num ) ? $.trim( str ) : num;
},
isDigit : function( str ) {
// replace all unwanted chars and match
return isNaN( str ) ?
ts.regex.digitTest.test( str.toString().replace( ts.regex.digitReplace, '' ) ) :
str !== '';
},
// computeTableHeaderCellIndexes from:
// http://www.javascripttoolbox.com/lib/table/examples.php
// http://www.javascripttoolbox.com/temp/table_cellindex.html
computeColumnIndex : function( $rows, c ) {
var i, j, k, l, cell, cells, rowIndex, rowSpan, colSpan, firstAvailCol,
// total columns has been calculated, use it to set the matrixrow
columns = c && c.columns || 0,
matrix = [],
matrixrow = new Array( columns );
for ( i = 0; i < $rows.length; i++ ) {
cells = $rows[ i ].cells;
for ( j = 0; j < cells.length; j++ ) {
cell = cells[ j ];
rowIndex = cell.parentNode.rowIndex;
rowSpan = cell.rowSpan || 1;
colSpan = cell.colSpan || 1;
if ( typeof matrix[ rowIndex ] === 'undefined' ) {
matrix[ rowIndex ] = [];
}
// Find first available column in the first row
for ( k = 0; k < matrix[ rowIndex ].length + 1; k++ ) {
if ( typeof matrix[ rowIndex ][ k ] === 'undefined' ) {
firstAvailCol = k;
break;
}
}
// jscs:disable disallowEmptyBlocks
if ( columns && cell.cellIndex === firstAvailCol ) {
// don't to anything
} else if ( cell.setAttribute ) {
// jscs:enable disallowEmptyBlocks
// add data-column (setAttribute = IE8+)
cell.setAttribute( 'data-column', firstAvailCol );
} else {
// remove once we drop support for IE7 - 1/12/2016
$( cell ).attr( 'data-column', firstAvailCol );
}
for ( k = rowIndex; k < rowIndex + rowSpan; k++ ) {
if ( typeof matrix[ k ] === 'undefined' ) {
matrix[ k ] = [];
}
matrixrow = matrix[ k ];
for ( l = firstAvailCol; l < firstAvailCol + colSpan; l++ ) {
matrixrow[ l ] = 'x';
}
}
}
}
return matrixrow.length;
},
// automatically add a colgroup with col elements set to a percentage width
fixColumnWidth : function( table ) {
table = $( table )[ 0 ];
var overallWidth, percent, $tbodies, len, index,
c = table.config,
$colgroup = c.$table.children( 'colgroup' );
// remove plugin-added colgroup, in case we need to refresh the widths
if ( $colgroup.length && $colgroup.hasClass( ts.css.colgroup ) ) {
$colgroup.remove();
}
if ( c.widthFixed && c.$table.children( 'colgroup' ).length === 0 ) {
$colgroup = $( '<colgroup class="' + ts.css.colgroup + '">' );
overallWidth = c.$table.width();
// only add col for visible columns - fixes #371
$tbodies = c.$tbodies.find( 'tr:first' ).children( ':visible' );
len = $tbodies.length;
for ( index = 0; index < len; index++ ) {
percent = parseInt( ( $tbodies.eq( index ).width() / overallWidth ) * 1000, 10 ) / 10 + '%';
$colgroup.append( $( '<col>' ).css( 'width', percent ) );
}
c.$table.prepend( $colgroup );
}
},
// get sorter, string, empty, etc options for each column from
// jQuery data, metadata, header option or header class name ('sorter-false')
// priority = jQuery data > meta > headers option > header class name
getData : function( header, configHeader, key ) {
var meta, cl4ss,
val = '',
$header = $( header );
if ( !$header.length ) { return ''; }
meta = $.metadata ? $header.metadata() : false;
cl4ss = ' ' + ( $header.attr( 'class' ) || '' );
if ( typeof $header.data( key ) !== 'undefined' ||
typeof $header.data( key.toLowerCase() ) !== 'undefined' ) {
// 'data-lockedOrder' is assigned to 'lockedorder'; but 'data-locked-order' is assigned to 'lockedOrder'
// 'data-sort-initial-order' is assigned to 'sortInitialOrder'
val += $header.data( key ) || $header.data( key.toLowerCase() );
} else if ( meta && typeof meta[ key ] !== 'undefined' ) {
val += meta[ key ];
} else if ( configHeader && typeof configHeader[ key ] !== 'undefined' ) {
val += configHeader[ key ];
} else if ( cl4ss !== ' ' && cl4ss.match( ' ' + key + '-' ) ) {
// include sorter class name 'sorter-text', etc; now works with 'sorter-my-custom-parser'
val = cl4ss.match( new RegExp( '\\s' + key + '-([\\w-]+)' ) )[ 1 ] || '';
}
return $.trim( val );
},
getColumnData : function( table, obj, indx, getCell, $headers ) {
if ( typeof obj === 'undefined' || obj === null ) { return; }
table = $( table )[ 0 ];
var $header, key,
c = table.config,
$cells = ( $headers || c.$headers ),
// c.$headerIndexed is not defined initially
$cell = c.$headerIndexed && c.$headerIndexed[ indx ] ||
$cells.filter( '[data-column="' + indx + '"]:last' );
if ( obj[ indx ] ) {
return getCell ? obj[ indx ] : obj[ $cells.index( $cell ) ];
}
for ( key in obj ) {
if ( typeof key === 'string' ) {
$header = $cell
// header cell with class/id
.filter( key )
// find elements within the header cell with cell/id
.add( $cell.find( key ) );
if ( $header.length ) {
return obj[ key ];
}
}
}
return;
},
// *** Process table ***
// add processing indicator
isProcessing : function( $table, toggle, $headers ) {
$table = $( $table );
var c = $table[ 0 ].config,
// default to all headers
$header = $headers || $table.find( '.' + ts.css.header );
if ( toggle ) {
// don't use sortList if custom $headers used
if ( typeof $headers !== 'undefined' && c.sortList.length > 0 ) {
// get headers from the sortList
$header = $header.filter( function() {
// get data-column from attr to keep compatibility with jQuery 1.2.6
return this.sortDisabled ?
false :
ts.isValueInArray( parseFloat( $( this ).attr( 'data-column' ) ), c.sortList ) >= 0;
});
}
$table.add( $header ).addClass( ts.css.processing + ' ' + c.cssProcessing );
} else {
$table.add( $header ).removeClass( ts.css.processing + ' ' + c.cssProcessing );
}
},
// detach tbody but save the position
// don't use tbody because there are portions that look for a tbody index (updateCell)
processTbody : function( table, $tb, getIt ) {
table = $( table )[ 0 ];
if ( getIt ) {
table.isProcessing = true;
$tb.before( '<colgroup class="tablesorter-savemyplace"/>' );
return $.fn.detach ? $tb.detach() : $tb.remove();
}
var holdr = $( table ).find( 'colgroup.tablesorter-savemyplace' );
$tb.insertAfter( holdr );
holdr.remove();
table.isProcessing = false;
},
clearTableBody : function( table ) {
$( table )[ 0 ].config.$tbodies.children().detach();
},
// used when replacing accented characters during sorting
characterEquivalents : {
'a' : '\u00e1\u00e0\u00e2\u00e3\u00e4\u0105\u00e5', // áàâãäąå
'A' : '\u00c1\u00c0\u00c2\u00c3\u00c4\u0104\u00c5', // ÁÀÂÃÄĄÅ
'c' : '\u00e7\u0107\u010d', // çćč
'C' : '\u00c7\u0106\u010c', // ÇĆČ
'e' : '\u00e9\u00e8\u00ea\u00eb\u011b\u0119', // éèêëěę
'E' : '\u00c9\u00c8\u00ca\u00cb\u011a\u0118', // ÉÈÊËĚĘ
'i' : '\u00ed\u00ec\u0130\u00ee\u00ef\u0131', // íìİîïı
'I' : '\u00cd\u00cc\u0130\u00ce\u00cf', // ÍÌİÎÏ
'o' : '\u00f3\u00f2\u00f4\u00f5\u00f6\u014d', // óòôõöō
'O' : '\u00d3\u00d2\u00d4\u00d5\u00d6\u014c', // ÓÒÔÕÖŌ
'ss': '\u00df', // ß (s sharp)
'SS': '\u1e9e', // ẞ (Capital sharp s)
'u' : '\u00fa\u00f9\u00fb\u00fc\u016f', // úùûüů
'U' : '\u00da\u00d9\u00db\u00dc\u016e' // ÚÙÛÜŮ
},
replaceAccents : function( str ) {
var chr,
acc = '[',
eq = ts.characterEquivalents;
if ( !ts.characterRegex ) {
ts.characterRegexArray = {};
for ( chr in eq ) {
if ( typeof chr === 'string' ) {
acc += eq[ chr ];
ts.characterRegexArray[ chr ] = new RegExp( '[' + eq[ chr ] + ']', 'g' );
}
}
ts.characterRegex = new RegExp( acc + ']' );
}
if ( ts.characterRegex.test( str ) ) {
for ( chr in eq ) {
if ( typeof chr === 'string' ) {
str = str.replace( ts.characterRegexArray[ chr ], chr );
}
}
}
return str;
},
// restore headers
restoreHeaders : function( table ) {
var index, $cell,
c = $( table )[ 0 ].config,
$headers = c.$table.find( c.selectorHeaders ),
len = $headers.length;
// don't use c.$headers here in case header cells were swapped
for ( index = 0; index < len; index++ ) {
$cell = $headers.eq( index );
// only restore header cells if it is wrapped
// because this is also used by the updateAll method
if ( $cell.find( '.' + ts.css.headerIn ).length ) {
$cell.html( c.headerContent[ index ] );
}
}
},
destroy : function( table, removeClasses, callback ) {
table = $( table )[ 0 ];
if ( !table.hasInitialized ) { return; }
// remove all widgets
ts.removeWidget( table, true, false );
var events,
$t = $( table ),
c = table.config,
debug = c.debug,
$h = $t.find( 'thead:first' ),
$r = $h.find( 'tr.' + ts.css.headerRow ).removeClass( ts.css.headerRow + ' ' + c.cssHeaderRow ),
$f = $t.find( 'tfoot:first > tr' ).children( 'th, td' );
if ( removeClasses === false && $.inArray( 'uitheme', c.widgets ) >= 0 ) {
// reapply uitheme classes, in case we want to maintain appearance
$t.triggerHandler( 'applyWidgetId', [ 'uitheme' ] );
$t.triggerHandler( 'applyWidgetId', [ 'zebra' ] );
}
// remove widget added rows, just in case
$h.find( 'tr' ).not( $r ).remove();
// disable tablesorter - not using .unbind( namespace ) because namespacing was
// added in jQuery v1.4.3 - see http://api.jquery.com/event.namespace/
events = 'sortReset update updateRows updateAll updateHeaders updateCell addRows updateComplete sorton ' +
'appendCache updateCache applyWidgetId applyWidgets refreshWidgets removeWidget destroy mouseup mouseleave ' +
'keypress sortBegin sortEnd resetToLoadState '.split( ' ' )
.join( c.namespace + ' ' );
$t
.removeData( 'tablesorter' )
.unbind( events.replace( ts.regex.spaces, ' ' ) );
c.$headers
.add( $f )
.removeClass( [ ts.css.header, c.cssHeader, c.cssAsc, c.cssDesc, ts.css.sortAsc, ts.css.sortDesc, ts.css.sortNone ].join( ' ' ) )
.removeAttr( 'data-column' )
.removeAttr( 'aria-label' )
.attr( 'aria-disabled', 'true' );
$r
.find( c.selectorSort )
.unbind( ( 'mousedown mouseup keypress '.split( ' ' ).join( c.namespace + ' ' ) ).replace( ts.regex.spaces, ' ' ) );
ts.restoreHeaders( table );
$t.toggleClass( ts.css.table + ' ' + c.tableClass + ' tablesorter-' + c.theme, removeClasses === false );
// clear flag in case the plugin is initialized again
table.hasInitialized = false;
delete table.config.cache;
if ( typeof callback === 'function' ) {
callback( table );
}
if ( debug ) {
console.log( 'tablesorter has been removed' );
}
}
};
$.fn.tablesorter = function( settings ) {
return this.each( function() {
var table = this,
// merge & extend config options
c = $.extend( true, {}, ts.defaults, settings, ts.instanceMethods );
// save initial settings
c.originalSettings = settings;
// create a table from data (build table widget)
if ( !table.hasInitialized && ts.buildTable && this.nodeName !== 'TABLE' ) {
// return the table (in case the original target is the table's container)
ts.buildTable( table, c );
} else {
ts.setup( table, c );
}
});
};
// set up debug logs
if ( !( window.console && window.console.log ) ) {
// access $.tablesorter.logs for browsers that don't have a console...
ts.logs = [];
/*jshint -W020 */
console = {};
console.log = console.warn = console.error = console.table = function() {
var arg = arguments.length > 1 ? arguments : arguments[0];
ts.logs.push({ date: Date.now(), log: arg });
};
}
// add default parsers
ts.addParser({
id : 'no-parser',
is : function() {
return false;
},
format : function() {
return '';
},
type : 'text'
});
ts.addParser({
id : 'text',
is : function() {
return true;
},
format : function( str, table ) {
var c = table.config;
if ( str ) {
str = $.trim( c.ignoreCase ? str.toLocaleLowerCase() : str );
str = c.sortLocaleCompare ? ts.replaceAccents( str ) : str;
}
return str;
},
type : 'text'
});
ts.regex.nondigit = /[^\w,. \-()]/g;
ts.addParser({
id : 'digit',
is : function( str ) {
return ts.isDigit( str );
},
format : function( str, table ) {
var num = ts.formatFloat( ( str || '' ).replace( ts.regex.nondigit, '' ), table );
return str && typeof num === 'number' ? num :
str ? $.trim( str && table.config.ignoreCase ? str.toLocaleLowerCase() : str ) : str;
},
type : 'numeric'
});
ts.regex.currencyReplace = /[+\-,. ]/g;
ts.regex.currencyTest = /^\(?\d+[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]|[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]\d+\)?$/;
ts.addParser({
id : 'currency',
is : function( str ) {
str = ( str || '' ).replace( ts.regex.currencyReplace, '' );
// test for £$€¤¥¢
return ts.regex.currencyTest.test( str );
},
format : function( str, table ) {
var num = ts.formatFloat( ( str || '' ).replace( ts.regex.nondigit, '' ), table );
return str && typeof num === 'number' ? num :
str ? $.trim( str && table.config.ignoreCase ? str.toLocaleLowerCase() : str ) : str;
},
type : 'numeric'
});
// too many protocols to add them all https://en.wikipedia.org/wiki/URI_scheme
// now, this regex can be updated before initialization
ts.regex.urlProtocolTest = /^(https?|ftp|file):\/\//;
ts.regex.urlProtocolReplace = /(https?|ftp|file):\/\//;
ts.addParser({
id : 'url',
is : function( str ) {
return ts.regex.urlProtocolTest.test( str );
},
format : function( str ) {
return str ? $.trim( str.replace( ts.regex.urlProtocolReplace, '' ) ) : str;
},
parsed : true, // filter widget flag
type : 'text'
});
ts.regex.dash = /-/g;
ts.regex.isoDate = /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}/;
ts.addParser({
id : 'isoDate',
is : function( str ) {
return ts.regex.isoDate.test( str );
},
format : function( str, table ) {
var date = str ? new Date( str.replace( ts.regex.dash, '/' ) ) : str;
return date instanceof Date && isFinite( date ) ? date.getTime() : str;
},
type : 'numeric'
});
ts.regex.percent = /%/g;
ts.regex.percentTest = /(\d\s*?%|%\s*?\d)/;
ts.addParser({
id : 'percent',
is : function( str ) {
return ts.regex.percentTest.test( str ) && str.length < 15;
},
format : function( str, table ) {
return str ? ts.formatFloat( str.replace( ts.regex.percent, '' ), table ) : str;
},
type : 'numeric'
});
// added image parser to core v2.17.9
ts.addParser({
id : 'image',
is : function( str, table, node, $node ) {
return $node.find( 'img' ).length > 0;
},
format : function( str, table, cell ) {
return $( cell ).find( 'img' ).attr( table.config.imgAttr || 'alt' ) || str;
},
parsed : true, // filter widget flag
type : 'text'
});
ts.regex.dateReplace = /(\S)([AP]M)$/i; // used by usLongDate & time parser
ts.regex.usLongDateTest1 = /^[A-Z]{3,10}\.?\s+\d{1,2},?\s+(\d{4})(\s+\d{1,2}:\d{2}(:\d{2})?(\s+[AP]M)?)?$/i;
ts.regex.usLongDateTest2 = /^\d{1,2}\s+[A-Z]{3,10}\s+\d{4}/i;
ts.addParser({
id : 'usLongDate',
is : function( str ) {
// two digit years are not allowed cross-browser
// Jan 01, 2013 12:34:56 PM or 01 Jan 2013
return ts.regex.usLongDateTest1.test( str ) || ts.regex.usLongDateTest2.test( str );
},
format : function( str, table ) {
var date = str ? new Date( str.replace( ts.regex.dateReplace, '$1 $2' ) ) : str;
return date instanceof Date && isFinite( date ) ? date.getTime() : str;
},
type : 'numeric'
});
// testing for ##-##-#### or ####-##-##, so it's not perfect; time can be included
ts.regex.shortDateTest = /(^\d{1,2}[\/\s]\d{1,2}[\/\s]\d{4})|(^\d{4}[\/\s]\d{1,2}[\/\s]\d{1,2})/;
// escaped "-" because JSHint in Firefox was showing it as an error
ts.regex.shortDateReplace = /[\-.,]/g;
// XXY covers MDY & DMY formats
ts.regex.shortDateXXY = /(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/;
ts.regex.shortDateYMD = /(\d{4})[\/\s](\d{1,2})[\/\s](\d{1,2})/;
ts.convertFormat = function( dateString, format ) {
dateString = ( dateString || '' )
.replace( ts.regex.spaces, ' ' )
.replace( ts.regex.shortDateReplace, '/' );
if ( format === 'mmddyyyy' ) {
dateString = dateString.replace( ts.regex.shortDateXXY, '$3/$1/$2' );
} else if ( format === 'ddmmyyyy' ) {
dateString = dateString.replace( ts.regex.shortDateXXY, '$3/$2/$1' );
} else if ( format === 'yyyymmdd' ) {
dateString = dateString.replace( ts.regex.shortDateYMD, '$1/$2/$3' );
}
var date = new Date( dateString );
return date instanceof Date && isFinite( date ) ? date.getTime() : '';
};
ts.addParser({
id : 'shortDate', // 'mmddyyyy', 'ddmmyyyy' or 'yyyymmdd'
is : function( str ) {
str = ( str || '' ).replace( ts.regex.spaces, ' ' ).replace( ts.regex.shortDateReplace, '/' );
return ts.regex.shortDateTest.test( str );
},
format : function( str, table, cell, cellIndex ) {
if ( str ) {
var c = table.config,
$header = c.$headerIndexed[ cellIndex ],
format = $header.length && $header.data( 'dateFormat' ) ||
ts.getData( $header, ts.getColumnData( table, c.headers, cellIndex ), 'dateFormat' ) ||
c.dateFormat;
// save format because getData can be slow...
if ( $header.length ) {
$header.data( 'dateFormat', format );
}
return ts.convertFormat( str, format ) || str;
}
return str;
},
type : 'numeric'
});
// match 24 hour time & 12 hours time + am/pm - see http://regexr.com/3c3tk
ts.regex.timeTest = /^([1-9]|1[0-2]):([0-5]\d)(\s[AP]M)|((?:[01]\d|[2][0-4]):[0-5]\d)$/i;
ts.regex.timeMatch = /([1-9]|1[0-2]):([0-5]\d)(\s[AP]M)|((?:[01]\d|[2][0-4]):[0-5]\d)/i;
ts.addParser({
id : 'time',
is : function( str ) {
return ts.regex.timeTest.test( str );
},
format : function( str, table ) {
// isolate time... ignore month, day and year
var temp,
timePart = ( str || '' ).match( ts.regex.timeMatch ),
orig = new Date( str ),
// no time component? default to 00:00 by leaving it out, but only if str is defined
time = str && ( timePart !== null ? timePart[ 0 ] : '00:00 AM' ),
date = time ? new Date( '2000/01/01 ' + time.replace( ts.regex.dateReplace, '$1 $2' ) ) : time;
if ( date instanceof Date && isFinite( date ) ) {
temp = orig instanceof Date && isFinite( orig ) ? orig.getTime() : 0;
// if original string was a valid date, add it to the decimal so the column sorts in some kind of order
// luckily new Date() ignores the decimals
return temp ? parseFloat( date.getTime() + '.' + orig.getTime() ) : date.getTime();
}
return str;
},
type : 'numeric'
});
ts.addParser({
id : 'metadata',
is : function() {
return false;
},
format : function( str, table, cell ) {
var c = table.config,
p = ( !c.parserMetadataName ) ? 'sortValue' : c.parserMetadataName;
return $( cell ).metadata()[ p ];
},
type : 'numeric'
});
/*
██████ ██████ █████▄ █████▄ ▄████▄
▄█▀ ██▄▄ ██▄▄██ ██▄▄██ ██▄▄██
▄█▀ ██▀▀ ██▀▀██ ██▀▀█ ██▀▀██
██████ ██████ █████▀ ██ ██ ██ ██
*/
// add default widgets
ts.addWidget({
id : 'zebra',
priority : 90,
format : function( table, c, wo ) {
var $visibleRows, $row, count, isEven, tbodyIndex, rowIndex, len,
child = new RegExp( c.cssChildRow, 'i' ),
$tbodies = c.$tbodies.add( $( c.namespace + '_extra_table' ).children( 'tbody:not(.' + c.cssInfoBlock + ')' ) );
for ( tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ) {
// loop through the visible rows
count = 0;
$visibleRows = $tbodies.eq( tbodyIndex ).children( 'tr:visible' ).not( c.selectorRemove );
len = $visibleRows.length;
for ( rowIndex = 0; rowIndex < len; rowIndex++ ) {
$row = $visibleRows.eq( rowIndex );
// style child rows the same way the parent row was styled
if ( !child.test( $row[ 0 ].className ) ) { count++; }
isEven = ( count % 2 === 0 );
$row
.removeClass( wo.zebra[ isEven ? 1 : 0 ] )
.addClass( wo.zebra[ isEven ? 0 : 1 ] );
}
}
},
remove : function( table, c, wo, refreshing ) {
if ( refreshing ) { return; }
var tbodyIndex, $tbody,
$tbodies = c.$tbodies,
toRemove = ( wo.zebra || [ 'even', 'odd' ] ).join( ' ' );
for ( tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ){
$tbody = ts.processTbody( table, $tbodies.eq( tbodyIndex ), true ); // remove tbody
$tbody.children().removeClass( toRemove );
ts.processTbody( table, $tbody, false ); // restore tbody
}
}
});
})( jQuery );
return $.tablesorter;
}));
|
lucky1603/PmsApp
|
public/tablesorter-master/dist/js/jquery.tablesorter.js
|
JavaScript
|
bsd-3-clause
| 100,890
|
// ---- Angular Hammer ----
// Copyright (c) 2014 Ryan S Mullins <ryan@ryanmullins.org>
// Licensed under the MIT Software License
(function () {
'use strict';
// Checking to make sure Hammer and Angular are defined
var angular, Hammer;
if (typeof angular === 'undefined') {
if (typeof require !== 'undefined' && require) {
angular = require('angular');
} else if (typeof window.angular !== 'undefined') {
angular = window.angular;
} else {
return console.log('ERROR: Angular Hammer could not find or require() a reference to angular');
}
}
if (typeof Hammer === 'undefined') {
if (typeof require !== 'undefined' && require) {
try {
Hammer = require('hammerjs');
} catch (e) {
try {
Hammer = require('hammer');
} catch (e) {
return console.log('ERROR: Angular Hammer could not require() a reference to Hammer');
}
}
} else if (typeof window.Hammer !== 'undefined') {
Hammer = window.Hammer;
} else {
return console.log('ERROR: Angular Hammer could not find or require() a reference to Hammer');
}
}
/**
* Mapping of the gesture event names with the Angular attribute directive
* names. Follows the form: <directiveName>:<eventName>.
*
* @type {Array}
*/
var gestureTypes = [
'hmCustom:custom',
'hmSwipe:swipe',
'hmSwipeleft:swipeleft',
'hmSwiperight:swiperight',
'hmSwipeup:swipeup',
'hmSwipedown:swipedown',
'hmPan:pan',
'hmPanstart:panstart',
'hmPanmove:panmove',
'hmPanend:panend',
'hmPancancel:pancancel',
'hmPanleft:panleft',
'hmPanright:panright',
'hmPanup:panup',
'hmPandown:pandown',
'hmPress:press',
'hmRotate:rotate',
'hmRotatestart:rotatestart',
'hmRotatemove:rotatemove',
'hmRotateend:rotateend',
'hmRotatecancel:rotatecancel',
'hmPinch:pinch',
'hmPinchstart:pinchstart',
'hmPinchmove:pinchmove',
'hmPinchend:pinchend',
'hmPinchcancel:pinchcancel',
'hmPinchin:pinchin',
'hmPinchout:pinchout',
'hmTap:tap',
'hmDoubletap:doubletap'
];
// ---- Module Definition ----
/**
* @module hmTouchEvents
* @description Angular.js module for adding Hammer.js event listeners to HTML
* elements using attribute directives
* @requires angular
* @requires hammer
*/
angular.module('hmTouchEvents', []);
/**
* Iterates through each gesture type mapping and creates a directive for
* each of the
*
* @param {String} type Mapping in the form of <directiveName>:<eventName>
* @return None
*/
angular.forEach(gestureTypes, function (type) {
var directive = type.split(':'),
directiveName = directive[0],
eventName = directive[1];
angular.module('hmTouchEvents')
.directive(directiveName, ['$parse', '$window', function ($parse, $window) {
return {
'restrict' : 'A',
'link' : function (scope, element, attrs) {
var handlerName = attrs[directiveName],
handlerExpr = $parse(handlerName),
handler = function (event) {
event.element = element;
var phase = scope.$root.$$phase,
fn = function () {
handlerExpr(scope, {$event: event});
};
if (scope[handlerName]) {
scope[handlerName](event);
} else {
if (phase === '$apply' || phase === '$digest') {
fn();
} else {
scope.$apply(fn);
}
}
},
managerOpts = angular.fromJson(attrs.hmManagerOptions),
recognizerOpts = angular.fromJson(attrs.hmRecognizerOptions),
hammer = element.data('hammer');
// Check for Hammer and required functionality
// If no Hammer, maybe bind tap and doubletap to click and dblclick
if (!Hammer || !$window.addEventListener) {
if (directiveName === 'hmTap') {
element.bind('click', handler);
}
if (directiveName === 'hmDoubleTap') {
element.bind('dblclick', handler);
}
return;
}
// Hammer exists, check for a manager and set up the recognizers.
if (!hammer) {
hammer = new Hammer.Manager(element[0], managerOpts);
element.data('hammer', hammer);
}
if (eventName === 'custom') {
// Handling custom events
// Custom events require you to define hmRecognizerOptions. If you
// do not define the this attribute no custom handlers will be created
if (angular.isArray(recognizerOpts)) {
// The recognizer options may be stored in an array. In this
// case, Angular Hammer iterates through the array of options
// trying to find an occurrence of the options.type in the event
// name. If it find the type in the event name, it applies those
// options to the recognizer for events with that name. If it
// does not find the type in the event name it moves on.
angular.forEach(recognizerOpts, function (options) {
setupRecognizerWithOptions(hammer, options);
hammer.on(options.event, handler);
scope.$on('$destroy', function () {
hammer.destroy();
});
});
} else if (angular.isObject(recognizerOpts)) {
// Recognizer options may be stored as an object. In this case,
// Angular Hammer applies the options directly to the manager
// instance for this element.
setupRecognizerWithOptions(hammer, recognizerOpts);
hammer.on(options.event, handler);
scope.$on('$destroy', function () {
hammer.destroy();
});
}
} else {
// Handling the standard events
if (angular.isArray(recognizerOpts)) {
// The recognizer options may be stored in an array. In this
// case, Angular Hammer iterates through the array of options
// trying to find an occurrence of the options.type in the event
// name. If it find the type in the event name, it applies those
// options to the recognizer for events with that name. If it
// does not find the type in the event name it moves on.
angular.forEach(recognizerOpts, function (options) {
if (eventName.indexOf(options.type) > -1) {
setupRecognizerWithOptions(hammer, options);
}
});
} else if (angular.isObject(recognizerOpts) &&
eventName.indexOf(recognizerOpts.type) > -1) {
// Recognizer options may be stored as an object. In this case,
// Angular Hammer checks to make sure that the options type
// property is found in the event name. If the options are
// designated for this general type of event, Angular Hammer
// applies the options directly to the manager instance for
// this element.
setupRecognizerWithOptions(hammer, recognizerOpts);
} else {
// If no options are supplied, or the supplied options do not
// match any of the above conditions, Angular Hammer sets up
// the default options that a manager instantiated using
// Hammer() would have.
recognizerOpts = {'type':eventName};
if (recognizerOpts.type.indexOf('doubletap') > -1) {
recognizerOpts.event = recognizerOpts.type;
recognizerOpts.taps = 2;
if (hammer.get('tap')) {
recognizerOpts.recognizeWith = 'tap';
}
}
if (recognizerOpts.type.indexOf('pan') > -1 &&
hammer.get('swipe')) {
recognizerOpts.recognizeWith = 'swipe';
}
if (recognizerOpts.type.indexOf('pinch') > -1 &&
hammer.get('rotate')) {
recognizerOpts.recognizeWith = 'rotate';
}
setupRecognizerWithOptions(hammer, recognizerOpts);
}
hammer.on(eventName, handler);
scope.$on('$destroy', function () {
hammer.destroy();
});
}
}
};
}]);
});
// ---- Private Functions -----
/**
* Adds a gesture recognizer to a given manager. The type of recognizer to
* add is determined by the value of the options.type property.
*
* @param {Object} manager Hammer.js manager object assigned to an element
* @param {Object} options Options that define the recognizer to add
* @return {Object} Reference to the new gesture recognizer, if successful,
* null otherwise.
*/
function addRecognizer (manager, options) {
var recognizer;
if (options.type) {
if (options.type.indexOf('pan') > -1) {
recognizer = new Hammer.Pan(options);
}
if (options.type.indexOf('pinch') > -1) {
recognizer = new Hammer.Pinch(options);
}
if (options.type.indexOf('press') > -1) {
recognizer = new Hammer.Press(options);
}
if (options.type.indexOf('rotate') > -1) {
recognizer = new Hammer.Rotate(options);
}
if (options.type.indexOf('swipe') > -1) {
recognizer = new Hammer.Swipe(options);
}
if (options.type.indexOf('tap') > -1) {
recognizer = new Hammer.Tap(options);
}
}
if (manager && recognizer) {
manager.add(recognizer);
return recognizer;
}
}
/**
* Applies the passed options object to the appropriate gesture recognizer.
* Recognizers are created if they do not already exist. See the README for a
* description of the options object that can be passed to this function.
*
* @param {Object} manager Hammer.js manager object assigned to an element
* @param {Object} options Options applied to a recognizer managed by manager
* @return None
*/
function setupRecognizerWithOptions (manager, options) {
var recognizer = manager.get(options.type);
if (!recognizer) {
recognizer = addRecognizer(manager, options);
}
if (options) {
if (options.directions) {
options.direction = parseDirections(options.directions);
}
recognizer.set(options);
}
if (options.recognizeWith) {
recognizer.recognizeWith(options.recognizeWith);
}
if (options.dropRecognizeWith) {
recognizer.dropRecognizeWith(options.dropRecognizeWith);
}
if (options.requireFailure) {
recognizer.requireFailure(options.requireFailure);
}
if (options.dropRequireFailure) {
recognizer.dropRequireFailure(options.dropRequireFailure);
}
}
/**
* Parses the value of the directions property of any Angular Hammer options
* object and converts them into the standard Hammer.js directions values.
*
* @param {String} dirs Direction names separated by '|' characters
* @return {Number} Hammer.js direction value
*/
function parseDirections (dirs) {
var directions = 0;
angular.forEach(dirs.split('|'), function (direction) {
if (Hammer.hasOwnProperty(direction)) {
directions = directions | Hammer[direction];
}
});
return directions;
}
})();
|
kiwi89/cdnjs
|
ajax/libs/RyanMullins-angular-hammer/2.1.2/angular.hammer.js
|
JavaScript
|
mit
| 12,022
|
(function($, UI) {
"use strict";
var active = false, hoverIdle;
UI.component('dropdown', {
defaults: {
'mode' : 'hover',
'remaintime' : 800,
'justify' : false,
'boundary' : UI.$win,
'delay' : 0
},
remainIdle: false,
boot: function() {
var triggerevent = UI.support.touch ? "click" : "mouseenter";
// init code
UI.$html.on(triggerevent+".dropdown.uikit", "[data-@-dropdown]", function(e) {
var ele = UI.$(this);
if (!ele.data("dropdown")) {
var dropdown = UI.dropdown(ele, UI.Utils.options(ele.attr("data-@-dropdown")));
if (triggerevent=="click" || (triggerevent=="mouseenter" && dropdown.options.mode=="hover")) {
dropdown.element.trigger(triggerevent);
}
if(dropdown.element.find('.@-dropdown').length) {
e.preventDefault();
}
}
});
},
init: function() {
var $this = this;
this.dropdown = this.find('.@-dropdown');
this.centered = this.dropdown.hasClass('@-dropdown-center');
this.justified = this.options.justify ? UI.$(this.options.justify) : false;
this.boundary = UI.$(this.options.boundary);
this.flipped = this.dropdown.hasClass('@-dropdown-flip');
if (!this.boundary.length) {
this.boundary = UI.$win;
}
if (this.options.mode == "click" || UI.support.touch) {
this.on("click", function(e) {
var $target = UI.$(e.target);
if (!$target.parents(".@-dropdown").length) {
if ($target.is("a[href='#']") || $target.parent().is("a[href='#']") || ($this.dropdown.length && !$this.dropdown.is(":visible")) ){
e.preventDefault();
}
$target.blur();
}
if (!$this.element.hasClass('@-open')) {
$this.show();
} else {
if ($target.is("a:not(.js-@-prevent)") || $target.is(".@-dropdown-close") || !$this.dropdown.find(e.target).length) {
$this.hide();
}
}
});
} else {
this.on("mouseenter", function(e) {
if ($this.remainIdle) {
clearTimeout($this.remainIdle);
}
if (hoverIdle) {
clearTimeout(hoverIdle);
}
hoverIdle = setTimeout($this.show.bind($this), $this.options.delay);
}).on("mouseleave", function() {
if (hoverIdle) {
clearTimeout(hoverIdle);
}
$this.remainIdle = setTimeout(function() {
$this.hide();
}, $this.options.remaintime);
}).on("click", function(e){
var $target = $(e.target);
if ($this.remainIdle) {
clearTimeout($this.remainIdle);
}
if ($target.is("a[href='#']") || $target.parent().is("a[href='#']")){
e.preventDefault();
}
$this.show();
});
}
},
show: function(){
UI.$html.off("click.outer.dropdown");
if (active && active[0] != this.element[0]) {
active.removeClass('@-open');
}
if (hoverIdle) {
clearTimeout(hoverIdle);
}
this.checkDimensions();
this.element.addClass('@-open');
this.trigger('show.uk.dropdown', [this]);
UI.Utils.checkDisplay(this.dropdown, true);
active = this.element;
this.registerOuterClick();
},
hide: function() {
this.element.removeClass('@-open');
this.remainIdle = false;
if (active && active[0] == this.element[0]) active = false;
},
registerOuterClick: function(){
var $this = this;
UI.$html.off("click.outer.dropdown");
setTimeout(function() {
UI.$html.on("click.outer.dropdown", function(e) {
if (hoverIdle) {
clearTimeout(hoverIdle);
}
var $target = UI.$(e.target);
if (active && active[0] == $this.element[0] && ($target.is("a:not(.js-@-prevent)") || $target.is(".@-dropdown-close") || !$this.dropdown.find(e.target).length)) {
$this.hide();
UI.$html.off("click.outer.dropdown");
}
});
}, 10);
},
checkDimensions: function() {
if (!this.dropdown.length) return;
if (this.justified && this.justified.length) {
this.dropdown.css("min-width", "");
}
var $this = this,
dropdown = this.dropdown.css("margin-" + UI.langdirection, ""),
offset = dropdown.show().offset(),
width = dropdown.outerWidth(),
boundarywidth = this.boundary.width(),
boundaryoffset = this.boundary.offset() ? this.boundary.offset().left:0;
// centered dropdown
if (this.centered) {
dropdown.css("margin-" + UI.langdirection, (parseFloat(width) / 2 - dropdown.parent().width() / 2) * -1);
offset = dropdown.offset();
// reset dropdown
if ((width + offset.left) > boundarywidth || offset.left < 0) {
dropdown.css("margin-" + UI.langdirection, "");
offset = dropdown.offset();
}
}
// justify dropdown
if (this.justified && this.justified.length) {
var jwidth = this.justified.outerWidth();
dropdown.css("min-width", jwidth);
if (UI.langdirection == 'right') {
var right1 = boundarywidth - (this.justified.offset().left + jwidth),
right2 = boundarywidth - (dropdown.offset().left + dropdown.outerWidth());
dropdown.css("margin-right", right1 - right2);
} else {
dropdown.css("margin-left", this.justified.offset().left - offset.left);
}
offset = dropdown.offset();
}
if ((width + (offset.left-boundaryoffset)) > boundarywidth) {
dropdown.addClass('@-dropdown-flip');
offset = dropdown.offset();
}
if ((offset.left-boundaryoffset) < 0) {
dropdown.addClass("@-dropdown-stack");
if (dropdown.hasClass('@-dropdown-flip')) {
if (!this.flipped) {
dropdown.removeClass('@-dropdown-flip');
offset = dropdown.offset();
dropdown.addClass('@-dropdown-flip');
}
setTimeout(function(){
if ((dropdown.offset().left-boundaryoffset) < 0 || !$this.flipped && (dropdown.outerWidth() + (offset.left-boundaryoffset)) < boundarywidth) {
dropdown.removeClass('@-dropdown-flip');
}
}, 0);
}
this.trigger('stack.uk.dropdown', [this]);
}
dropdown.css("display", "");
}
});
})(jQuery, UIkit);
|
mubassirhayat/uikit
|
src/js/core/dropdown.js
|
JavaScript
|
mit
| 8,096
|
/*
Highcharts JS v5.0.8 (2017-03-08)
Plugin for displaying a message when there is no data visible in chart.
(c) 2010-2016 Highsoft AS
Author: Oystein Moseng
License: www.highcharts.com/license
*/
(function(d){"object"===typeof module&&module.exports?module.exports=d:d(Highcharts)})(function(d){(function(c){function d(){return!!this.points.length}function f(){this.hasData()?this.hideNoData():this.showNoData()}var g=c.seriesTypes,e=c.Chart.prototype,h=c.getOptions(),k=c.extend,l=c.each;k(h.lang,{noData:"No data to display"});h.noData={position:{x:0,y:0,align:"center",verticalAlign:"middle"}};l(["pie","gauge","waterfall","bubble","treemap"],function(a){g[a]&&(g[a].prototype.hasData=d)});c.Series.prototype.hasData=
function(){return this.visible&&void 0!==this.dataMax&&void 0!==this.dataMin};e.showNoData=function(a){var b=this.options;a=a||b.lang.noData;b=b.noData;this.noDataLabel||(this.noDataLabel=this.renderer.label(a,0,0,null,null,null,b.useHTML,null,"no-data"),this.noDataLabel.add(),this.noDataLabel.align(k(this.noDataLabel.getBBox(),b.position),!1,"plotBox"))};e.hideNoData=function(){this.noDataLabel&&(this.noDataLabel=this.noDataLabel.destroy())};e.hasData=function(){for(var a=this.series,b=a.length;b--;)if(a[b].hasData()&&
!a[b].options.isInternal)return!0;return!1};e.callbacks.push(function(a){c.addEvent(a,"load",f);c.addEvent(a,"redraw",f)})})(d)});
|
seogi1004/cdnjs
|
ajax/libs/highstock/5.0.8/js/modules/no-data-to-display.js
|
JavaScript
|
mit
| 1,386
|
/*
* Farsi (Persian) translation
* By Mohaqa
* 03-10-2007, 06:23 PM
*/
Ext.UpdateManager.defaults.indicatorText = '<div class="loading-indicator">در حال بارگذاری ...</div>';
if(Ext.View){
Ext.View.prototype.emptyText = "";
}
if(Ext.grid.GridPanel){
Ext.grid.GridPanel.prototype.ddText = "{0} رکورد انتخاب شده";
}
if(Ext.TabPanelItem){
Ext.TabPanelItem.prototype.closeText = "بستن";
}
if(Ext.form.Field){
Ext.form.Field.prototype.invalidText = "مقدار فیلد صحیح نیست";
}
if(Ext.LoadMask){
Ext.LoadMask.prototype.msg = "در حال بارگذاری ...";
}
Date.monthNames = [
"ژانویه",
"فوریه",
"مارس",
"آپریل",
"می",
"ژوئن",
"جولای",
"آگوست",
"سپتامبر",
"اکتبر",
"نوامبر",
"دسامبر"
];
Date.monthNumbers = {
Jan : 0,
Feb : 1,
Mar : 2,
Apr : 3,
May : 4,
Jun : 5,
Jul : 6,
Aug : 7,
Sep : 8,
Oct : 9,
Nov : 10,
Dec : 11
};
Date.dayNames = [
"یکشنبه",
"دوشنبه",
"سه شنبه",
"چهارشنبه",
"پنجشنبه",
"جمعه",
"شنبه"
];
if(Ext.MessageBox){
Ext.MessageBox.buttonText = {
ok : "تایید",
cancel : "بازگشت",
yes : "بله",
no : "خیر"
};
}
if(Ext.util.Format){
Ext.util.Format.date = function(v, format){
if(!v) return "";
if(!(v instanceof Date)) v = new Date(Date.parse(v));
return v.dateFormat(format || "Y/m/d");
};
}
if(Ext.DatePicker){
Ext.apply(Ext.DatePicker.prototype, {
todayText : "امروز",
minText : "این تاریخ قبل از محدوده مجاز است",
maxText : "این تاریخ پس از محدوده مجاز است",
disabledDaysText : "",
disabledDatesText : "",
monthNames : Date.monthNames,
dayNames : Date.dayNames,
nextText : 'ماه بعد (Control + Right)',
prevText : 'ماه قبل (Control+Left)',
monthYearText : 'یک ماه را انتخاب کنید (Control+Up/Down برای انتقال در سال)',
todayTip : "{0} (Spacebar)",
format : "y/m/d",
okText : " OK ",
cancelText : "Cancel",
startDay : 0
});
}
if(Ext.PagingToolbar){
Ext.apply(Ext.PagingToolbar.prototype, {
beforePageText : "صفحه",
afterPageText : "از {0}",
firstText : "صفحه اول",
prevText : "صفحه قبل",
nextText : "صفحه بعد",
lastText : "صفحه آخر",
refreshText : "بازخوانی",
displayMsg : "نمایش {0} - {1} of {2}",
emptyMsg : 'داده ای برای نمایش وجود ندارد'
});
}
if(Ext.form.TextField){
Ext.apply(Ext.form.TextField.prototype, {
minLengthText : "حداقل طول این فیلد برابر است با {0}",
maxLengthText : "حداکثر طول این فیلد برابر است با {0}",
blankText : "این فیلد باید مقداری داشته باشد",
regexText : "",
emptyText : null
});
}
if(Ext.form.NumberField){
Ext.apply(Ext.form.NumberField.prototype, {
minText : "حداقل مقدار این فیلد برابر است با {0}",
maxText : "حداکثر مقدار این فیلد برابر است با {0}",
nanText : "{0} یک عدد نیست"
});
}
if(Ext.form.DateField){
Ext.apply(Ext.form.DateField.prototype, {
disabledDaysText : "غیرفعال",
disabledDatesText : "غیرفعال",
minText : "تاریخ باید پس از {0} باشد",
maxText : "تاریخ باید پس از {0} باشد",
invalidText : "{0} تاریخ صحیحی نیست - فرمت صحیح {1}",
format : "y/m/d"
});
}
if(Ext.form.ComboBox){
Ext.apply(Ext.form.ComboBox.prototype, {
loadingText : "در حال بارگذاری ...",
valueNotFoundText : undefined
});
}
if(Ext.form.VTypes){
Ext.apply(Ext.form.VTypes, {
emailText : 'مقدار این فیلد باید یک ایمیل با این فرمت باشد "user@domain.com"',
urlText : 'مقدار این آدرس باید یک آدرس سایت با این فرمت باشد "http:/'+'/www.domain.com"',
alphaText : 'مقدار این فیلد باید فقط از حروف الفبا و _ تشکیل شده باشد ',
alphanumText : 'مقدار این فیلد باید فقط از حروف الفبا، اعداد و _ تشکیل شده باشد'
});
}
if(Ext.form.HtmlEditor){
Ext.apply(Ext.form.HtmlEditor.prototype, {
createLinkText : 'لطفا آدرس لینک را وارد کنید:',
buttonTips : {
bold : {
title: 'تیره (Ctrl+B)',
text: 'متن انتخاب شده را تیره می کند.',
cls: 'x-html-editor-tip'
},
italic : {
title: 'ایتالیک (Ctrl+I)',
text: 'متن انتخاب شده را ایتالیک می کند.',
cls: 'x-html-editor-tip'
},
underline : {
title: 'زیرخط (Ctrl+U)',
text: 'زیر هر نوشته یک خط نمایش می دهد.',
cls: 'x-html-editor-tip'
},
increasefontsize : {
title: 'افزایش اندازه',
text: 'اندازه فونت را افزایش می دهد.',
cls: 'x-html-editor-tip'
},
decreasefontsize : {
title: 'کاهش اندازه',
text: 'اندازه متن را کاهش می دهد.',
cls: 'x-html-editor-tip'
},
backcolor : {
title: 'رنگ زمینه متن',
text: 'برای تغییر رنگ زمینه متن استفاده می شود.',
cls: 'x-html-editor-tip'
},
forecolor : {
title: 'رنگ قلم',
text: 'رنگ قلم متن را تغییر می دهد.',
cls: 'x-html-editor-tip'
},
justifyleft : {
title: 'چیدن متن از سمت چپ',
text: 'متن از سمت چپ چیده شده می شود.',
cls: 'x-html-editor-tip'
},
justifycenter : {
title: 'متن در وسط ',
text: 'نمایش متن در قسمت وسط صفحه و رعابت سمت چپ و راست.',
cls: 'x-html-editor-tip'
},
justifyright : {
title: 'چیدن متن از سمت راست',
text: 'متن از سمت راست پیده خواهد شد.',
cls: 'x-html-editor-tip'
},
insertunorderedlist : {
title: 'لیست همراه با علامت',
text: 'یک لیست جدید ایجاد می کند.',
cls: 'x-html-editor-tip'
},
insertorderedlist : {
title: 'لیست عددی',
text: 'یک لیست عددی ایجاد می کند. ',
cls: 'x-html-editor-tip'
},
createlink : {
title: 'لینک',
text: 'متن انتخاب شده را به لینک تبدیل کنید.',
cls: 'x-html-editor-tip'
},
sourceedit : {
title: 'ویرایش سورس',
text: 'رفتن به حالت ویرایش سورس.',
cls: 'x-html-editor-tip'
}
}
});
}
if(Ext.grid.GridView){
Ext.apply(Ext.grid.GridView.prototype, {
sortAscText : "مرتب سازی افزایشی",
sortDescText : "مرتب سازی کاهشی",
lockText : "قفل ستون ها",
unlockText : "بازکردن ستون ها",
columnsText : "ستون ها"
});
}
if(Ext.grid.PropertyColumnModel){
Ext.apply(Ext.grid.PropertyColumnModel.prototype, {
nameText : "نام",
valueText : "مقدار",
dateFormat : "Y/m/d"
});
}
if(Ext.layout.BorderLayout && Ext.layout.BorderLayout.SplitRegion){
Ext.apply(Ext.layout.BorderLayout.SplitRegion.prototype, {
splitTip : "درگ برای تغییر اندازه.",
collapsibleSplitTip : "برای تغییر اندازه درگ کنید."
});
}
|
tranSMART-Foundation/transmartApp
|
web-app/js/ext/build/locale/ext-lang-fa.js
|
JavaScript
|
gpl-3.0
| 8,235
|
define(
[
'jquery', 'underscore', 'squire'
],
function ($, _, Squire) {
'use strict';
describe('FileUploader', function () {
var FileUploaderTemplate = readFixtures(
'metadata-file-uploader-entry.underscore'
),
FileUploaderItemTemplate = readFixtures(
'metadata-file-uploader-item.underscore'
),
locator = 'locator',
modelStub = {
default_value: 'http://example.org/test_1',
display_name: 'File Upload',
explicitly_set: false,
field_name: 'file_upload',
help: 'Specifies the name for this component.',
type: 'FileUploader',
value: 'http://example.org/test_1'
},
self, injector;
var setValue = function (view, value) {
view.setValueInEditor(value);
view.updateModel();
};
var createPromptSpy = function (name) {
var spy = jasmine.createSpyObj(name, ['constructor', 'show', 'hide']);
spy.constructor.andReturn(spy);
spy.show.andReturn(spy);
spy.extend = jasmine.createSpy().andReturn(spy.constructor);
return spy;
};
beforeEach(function () {
self = this;
this.addMatchers({
assertValueInView: function(expected) {
var value = this.actual.getValueFromEditor();
return this.env.equals_(value, expected);
},
assertCanUpdateView: function (expected) {
var view = this.actual,
value;
view.setValueInEditor(expected);
value = view.getValueFromEditor();
return this.env.equals_(value, expected);
},
assertClear: function (modelValue) {
var env = this.env,
view = this.actual,
model = view.model;
return model.getValue() === null &&
env.equals_(model.getDisplayValue(), modelValue) &&
env.equals_(view.getValueFromEditor(), modelValue);
},
assertUpdateModel: function (originalValue, newValue) {
var env = this.env,
view = this.actual,
model = view.model,
expectOriginal;
view.setValueInEditor(newValue);
expectOriginal = env.equals_(model.getValue(), originalValue);
view.updateModel();
return expectOriginal &&
env.equals_(model.getValue(), newValue);
},
verifyButtons: function (upload, download, index) {
var view = this.actual,
uploadBtn = view.$('.upload-setting'),
downloadBtn = view.$('.download-setting');
upload = upload ? uploadBtn.length : !uploadBtn.length;
download = download ? downloadBtn.length : !downloadBtn.length;
return upload && download;
}
});
appendSetFixtures($('<script>', {
id: 'metadata-file-uploader-entry',
type: 'text/template'
}).text(FileUploaderTemplate));
appendSetFixtures($('<script>', {
id: 'metadata-file-uploader-item',
type: 'text/template'
}).text(FileUploaderItemTemplate));
this.uploadSpies = createPromptSpy('UploadDialog');
injector = new Squire();
injector.mock('js/views/uploads', function () {
return self.uploadSpies.constructor;
});
injector.mock('js/views/video/transcripts/metadata_videolist');
injector.mock('js/views/video/translations_editor');
runs(function() {
injector.require([
'js/models/metadata', 'js/views/metadata'
],
function(MetadataModel, MetadataView) {
var model = new MetadataModel($.extend(true, {}, modelStub));
self.view = new MetadataView.FileUploader({
model: model,
locator: locator
});
});
});
waitsFor(function() {
return self.view;
}, 'FileUploader was not created', 2000);
});
afterEach(function () {
injector.clean();
injector.remove();
});
it('returns the initial value upon initialization', function () {
expect(this.view).assertValueInView('http://example.org/test_1');
expect(this.view).verifyButtons(true, true);
});
it('updates its value correctly', function () {
expect(this.view).assertCanUpdateView('http://example.org/test_2');
});
it('upload works correctly', function () {
var options;
setValue(this.view, '');
expect(this.view).verifyButtons(true, false);
this.view.$el.find('.upload-setting').click();
expect(this.uploadSpies.constructor).toHaveBeenCalled();
expect(this.uploadSpies.show).toHaveBeenCalled();
options = this.uploadSpies.constructor.mostRecentCall.args[0];
options.onSuccess({
'asset': {
'url': 'http://example.org/test_3'
}
});
expect(this.view).verifyButtons(true, true);
expect(this.view.getValueFromEditor()).toEqual('http://example.org/test_3');
});
it('has a clear method to revert to the model default', function () {
setValue(this.view, 'http://example.org/test_5');
this.view.clear();
expect(this.view).assertClear('http://example.org/test_1');
});
it('has an update model method', function () {
expect(this.view).assertUpdateModel(null, 'http://example.org/test_6');
});
});
});
|
simbs/edx-platform
|
cms/static/js/spec/video/file_uploader_editor_spec.js
|
JavaScript
|
agpl-3.0
| 6,370
|
/**
* UI-Router Extras: Sticky states, Future States, Deep State Redirect, Transition promise
* @version v0.0.11-pre1-BROKEN!!!
* 0.0.11-pre1 is broken, please use 0.0.11-pre2
* @link http://christopherthielen.github.io/ui-router-extras/
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
(function (window, angular, undefined) {
angular.module("ct.ui.router.extras", [ 'ui.router' ]);
var DEBUG = false;
var forEach = angular.forEach;
var extend = angular.extend;
var isArray = angular.isArray;
var map = function (collection, callback) {
"use strict";
var result = [];
forEach(collection, function (item, index) {
result.push(callback(item, index));
});
return result;
};
var keys = function (collection) {
"use strict";
return map(collection, function (collection, key) {
return key;
});
};
var filter = function (collection, callback) {
"use strict";
var result = [];
forEach(collection, function (item, index) {
if (callback(item, index)) {
result.push(item);
}
});
return result;
};
var filterObj = function (collection, callback) {
"use strict";
var result = {};
forEach(collection, function (item, index) {
if (callback(item, index)) {
result[index] = item;
}
});
return result;
};
// Duplicates code in UI-Router common.js
function ancestors(first, second) {
var path = [];
for (var n in first.path) {
if (first.path[n] !== second.path[n]) break;
path.push(first.path[n]);
}
return path;
}
// Duplicates code in UI-Router common.js
function objectKeys(object) {
if (Object.keys) {
return Object.keys(object);
}
var result = [];
angular.forEach(object, function (val, key) {
result.push(key);
});
return result;
}
// Duplicates code in UI-Router common.js
function arraySearch(array, value) {
if (Array.prototype.indexOf) {
return array.indexOf(value, Number(arguments[2]) || 0);
}
var len = array.length >>> 0, from = Number(arguments[2]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0) from += len;
for (; from < len; from++) {
if (from in array && array[from] === value) return from;
}
return -1;
}
// Duplicates code in UI-Router common.js
// Added compatibility code (isArray check) to support both 0.2.x and 0.3.x series of UI-Router.
function inheritParams(currentParams, newParams, $current, $to) {
var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];
for (var i in parents) {
if (!parents[i].params) continue;
// This test allows compatibility with 0.2.x and 0.3.x (optional and object params)
parentParams = isArray(parents[i].params) ? parents[i].params : objectKeys(parents[i].params);
if (!parentParams.length) continue;
for (var j in parentParams) {
if (arraySearch(inheritList, parentParams[j]) >= 0) continue;
inheritList.push(parentParams[j]);
inherited[parentParams[j]] = currentParams[parentParams[j]];
}
}
return extend({}, inherited, newParams);
}
function inherit(parent, extra) {
return extend(new (extend(function () { }, {prototype: parent}))(), extra);
}
var ignoreDsr;
function resetIgnoreDsr() {
ignoreDsr = undefined;
}
// Decorate $state.transitionTo to gain access to the last transition.options variable.
// This is used to process the options.ignoreDsr option
angular.module("ct.ui.router.extras").config([ "$provide", function ($provide) {
var $state_transitionTo;
$provide.decorator("$state", ['$delegate', '$q', function ($state, $q) {
$state_transitionTo = $state.transitionTo;
$state.transitionTo = function (to, toParams, options) {
if (options.ignoreDsr) {
ignoreDsr = options.ignoreDsr;
}
return $state_transitionTo.apply($state, arguments).then(
function (result) {
resetIgnoreDsr();
return result;
},
function (err) {
resetIgnoreDsr();
return $q.reject(err);
}
);
};
return $state;
}]);
}]);
angular.module("ct.ui.router.extras").service("$deepStateRedirect", [ '$rootScope', '$state', '$injector', function ($rootScope, $state, $injector) {
var lastSubstate = {};
var deepStateRedirectsByName = {};
var REDIRECT = "Redirect", ANCESTOR_REDIRECT = "AncestorRedirect";
function computeDeepStateStatus(state) {
var name = state.name;
if (deepStateRedirectsByName.hasOwnProperty(name))
return deepStateRedirectsByName[name];
recordDeepStateRedirectStatus(name);
}
function getConfig(state) {
var declaration = state.deepStateRedirect;
if (!declaration) return { dsr: false };
var dsrCfg = { dsr: true };
if (angular.isFunction(declaration))
dsrCfg.fn = declaration;
else if (angular.isObject(declaration))
dsrCfg = angular.extend(dsrCfg, declaration);
return dsrCfg;
}
function recordDeepStateRedirectStatus(stateName) {
var state = $state.get(stateName);
if (!state) return false;
var cfg = getConfig(state);
if (cfg.dsr) {
deepStateRedirectsByName[state.name] = REDIRECT;
if (lastSubstate[stateName] === undefined)
lastSubstate[stateName] = {};
}
var parent = state.$$state && state.$$state().parent;
if (parent) {
var parentStatus = recordDeepStateRedirectStatus(parent.self.name);
if (parentStatus && deepStateRedirectsByName[state.name] === undefined) {
deepStateRedirectsByName[state.name] = ANCESTOR_REDIRECT;
}
}
return deepStateRedirectsByName[state.name] || false;
}
function getParamsString(params, dsrParams) {
function safeString(input) { return !input ? input : input.toString(); }
if (dsrParams === true) dsrParams = Object.keys(params);
if (dsrParams === null || dsrParams === undefined) dsrParams = [];
var paramsToString = {};
angular.forEach(dsrParams.sort(), function(name) { paramsToString[name] = safeString(params[name]); });
return angular.toJson(paramsToString);
}
$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
if (ignoreDsr || computeDeepStateStatus(toState) !== REDIRECT) return;
// We're changing directly to one of the redirect (tab) states.
// Get the DSR key for this state by calculating the DSRParams option
var cfg = getConfig(toState);
var key = getParamsString(toParams, cfg.params);
var redirect = lastSubstate[toState.name][key];
// we have a last substate recorded
var isDSR = (redirect && redirect.state != toState.name ? true : false);
if (isDSR && cfg.fn)
isDSR = $injector.invoke(cfg.fn, toState);
if (!isDSR) return;
event.preventDefault();
$state.go(redirect.state, redirect.params);
});
$rootScope.$on("$stateChangeSuccess", function (event, toState, toParams, fromState, fromParams) {
var deepStateStatus = computeDeepStateStatus(toState);
if (deepStateStatus) {
var name = toState.name;
angular.forEach(lastSubstate, function (redirect, dsrState) {
// update Last-SubState¶ms for each DSR that this transition matches.
var cfg = getConfig($state.get(dsrState));
var key = getParamsString(toParams, cfg.params);
if (name == dsrState || name.indexOf(dsrState + ".") != -1) {
lastSubstate[dsrState][key] = { state: name, params: angular.copy(toParams) };
}
});
}
});
return {
reset: function(stateOrName) {
if (!stateOrName) {
angular.forEach(lastSubstate, function(redirect, dsrState) { lastSubstate[dsrState] = {}; });
} else {
var state = $state.get(stateOrName);
if (!state) throw new Error("Unknown state: " + stateOrName);
if (lastSubstate[state.name])
lastSubstate[state.name] = {};
}
}
};
}]);
angular.module("ct.ui.router.extras").run(['$deepStateRedirect', function ($deepStateRedirect) {
// Make sure $deepStateRedirect is instantiated
}]);
$StickyStateProvider.$inject = [ '$stateProvider' ];
function $StickyStateProvider($stateProvider) {
// Holds all the states which are inactivated. Inactivated states can be either sticky states, or descendants of sticky states.
var inactiveStates = {}; // state.name -> (state)
var stickyStates = {}; // state.name -> true
var $state;
// Called by $stateProvider.registerState();
// registers a sticky state with $stickyStateProvider
this.registerStickyState = function (state) {
stickyStates[state.name] = state;
// console.log("Registered sticky state: ", state);
};
this.enableDebug = function (enabled) {
DEBUG = enabled;
};
this.$get = [ '$rootScope', '$state', '$stateParams', '$injector', '$log',
function ($rootScope, $state, $stateParams, $injector, $log) {
// Each inactive states is either a sticky state, or a child of a sticky state.
// This function finds the closest ancestor sticky state, then find that state's parent.
// Map all inactive states to their closest parent-to-sticky state.
function mapInactives() {
var mappedStates = {};
angular.forEach(inactiveStates, function (state, name) {
var stickyAncestors = getStickyStateStack(state);
for (var i = 0; i < stickyAncestors.length; i++) {
var parent = stickyAncestors[i].parent;
mappedStates[parent.name] = mappedStates[parent.name] || [];
mappedStates[parent.name].push(state);
}
if (mappedStates['']) {
// This is necessary to compute Transition.inactives when there are sticky states are children to root state.
mappedStates['__inactives'] = mappedStates['']; // jshint ignore:line
}
});
return mappedStates;
}
// Given a state, returns all ancestor states which are sticky.
// Walks up the view's state's ancestry tree and locates each ancestor state which is marked as sticky.
// Returns an array populated with only those ancestor sticky states.
function getStickyStateStack(state) {
var stack = [];
if (!state) return stack;
do {
if (state.sticky) stack.push(state);
state = state.parent;
} while (state);
stack.reverse();
return stack;
}
// Used by processTransition to determine if what kind of sticky state transition this is.
// returns { from: (bool), to: (bool) }
function getStickyTransitionType(fromPath, toPath, keep) {
if (fromPath[keep] === toPath[keep]) return { from: false, to: false };
var stickyFromState = keep < fromPath.length && fromPath[keep].self.sticky;
var stickyToState = keep < toPath.length && toPath[keep].self.sticky;
return { from: stickyFromState, to: stickyToState };
}
// Returns a sticky transition type necessary to enter the state.
// Transition can be: reactivate, updateStateParams, or enter
// Note: if a state is being reactivated but params dont match, we treat
// it as a Exit/Enter, thus the special "updateStateParams" transition.
// If a parent inactivated state has "updateStateParams" transition type, then
// all descendant states must also be exit/entered, thus the first line of this function.
function getEnterTransition(state, stateParams, ancestorParamsChanged) {
if (ancestorParamsChanged) return "updateStateParams";
var inactiveState = inactiveStates[state.self.name];
if (!inactiveState) return "enter";
// if (inactiveState.locals == null || inactiveState.locals.globals == null) debugger;
var paramsMatch = equalForKeys(stateParams, inactiveState.locals.globals.$stateParams, state.ownParams);
// if (DEBUG) $log.debug("getEnterTransition: " + state.name + (paramsMatch ? ": reactivate" : ": updateStateParams"));
return paramsMatch ? "reactivate" : "updateStateParams";
}
// Given a state and (optional) stateParams, returns the inactivated state from the inactive sticky state registry.
function getInactivatedState(state, stateParams) {
var inactiveState = inactiveStates[state.name];
if (!inactiveState) return null;
if (!stateParams) return inactiveState;
var paramsMatch = equalForKeys(stateParams, inactiveState.locals.globals.$stateParams, state.ownParams);
return paramsMatch ? inactiveState : null;
}
// Duplicates logic in $state.transitionTo, primarily to find the pivot state (i.e., the "keep" value)
function equalForKeys(a, b, keys) {
if (!keys) {
keys = [];
for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility
}
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized
}
return true;
}
var stickySupport = {
getInactiveStates: function () {
var states = [];
angular.forEach(inactiveStates, function (state) {
states.push(state);
});
return states;
},
getInactiveStatesByParent: function () {
return mapInactives();
},
// Main API for $stickyState, used by $state.
// Processes a potential transition, returns an object with the following attributes:
// {
// inactives: Array of all states which will be inactive if the transition is completed. (both previously and newly inactivated)
// enter: Enter transition type for all added states. This is a sticky array to "toStates" array in $state.transitionTo.
// exit: Exit transition type for all removed states. This is a sticky array to "fromStates" array in $state.transitionTo.
// }
processTransition: function (transition) {
// This object is returned
var result = { inactives: [], enter: [], exit: [], keep: 0 };
var fromPath = transition.fromState.path,
fromParams = transition.fromParams,
toPath = transition.toState.path,
toParams = transition.toParams,
options = transition.options;
var keep = 0, state = toPath[keep];
if (options.inherit) {
toParams = inheritParams($stateParams, toParams || {}, $state.$current, transition.toState);
}
while (state && state === fromPath[keep] && equalForKeys(toParams, fromParams, state.ownParams)) {
state = toPath[++keep];
}
result.keep = keep;
var idx, deepestUpdatedParams, deepestReactivate, reactivatedStatesByName = {}, pType = getStickyTransitionType(fromPath, toPath, keep);
var ancestorUpdated = false; // When ancestor params change, treat reactivation as exit/enter
// Calculate the "enter" transitions for new states in toPath
// Enter transitions will be either "enter", "reactivate", or "updateStateParams" where
// enter: full resolve, no special logic
// reactivate: use previous locals
// updateStateParams: like 'enter', except exit the inactive state before entering it.
for (idx = keep; idx < toPath.length; idx++) {
var enterTrans = !pType.to ? "enter" : getEnterTransition(toPath[idx], transition.toParams, ancestorUpdated);
ancestorUpdated = (ancestorUpdated || enterTrans == 'updateStateParams');
result.enter[idx] = enterTrans;
// If we're reactivating a state, make a note of it, so we can remove that state from the "inactive" list
if (enterTrans == 'reactivate')
deepestReactivate = reactivatedStatesByName[toPath[idx].name] = toPath[idx];
if (enterTrans == 'updateStateParams')
deepestUpdatedParams = toPath[idx];
}
deepestReactivate = deepestReactivate ? deepestReactivate.self.name + "." : "";
deepestUpdatedParams = deepestUpdatedParams ? deepestUpdatedParams.self.name + "." : "";
// Inactive states, before the transition is processed, mapped to the parent to the sticky state.
var inactivesByParent = mapInactives();
// root ("") is always kept. Find the remaining names of the kept path.
var keptStateNames = [""].concat(map(fromPath.slice(0, keep), function (state) {
return state.self.name;
}));
// Locate currently and newly inactive states (at pivot and above) and store them in the output array 'inactives'.
angular.forEach(keptStateNames, function (name) {
var inactiveChildren = inactivesByParent[name];
for (var i = 0; inactiveChildren && i < inactiveChildren.length; i++) {
var child = inactiveChildren[i];
// Don't organize state as inactive if we're about to reactivate it.
if (!reactivatedStatesByName[child.name] &&
(!deepestReactivate || (child.self.name.indexOf(deepestReactivate) !== 0)) &&
(!deepestUpdatedParams || (child.self.name.indexOf(deepestUpdatedParams) !== 0)))
result.inactives.push(child);
}
});
// Calculate the "exit" transition for states not kept, in fromPath.
// Exit transition can be one of:
// exit: standard state exit logic
// inactivate: register state as an inactive state
for (idx = keep; idx < fromPath.length; idx++) {
var exitTrans = "exit";
if (pType.from) {
// State is being inactivated, note this in result.inactives array
result.inactives.push(fromPath[idx]);
exitTrans = "inactivate";
}
result.exit[idx] = exitTrans;
}
return result;
},
// Adds a state to the inactivated sticky state registry.
stateInactivated: function (state) {
// Keep locals around.
inactiveStates[state.self.name] = state;
// Notify states they are being Inactivated (i.e., a different
// sticky state tree is now active).
state.self.status = 'inactive';
if (state.self.onInactivate)
$injector.invoke(state.self.onInactivate, state.self, state.locals.globals);
},
// Removes a previously inactivated state from the inactive sticky state registry
stateReactivated: function (state) {
if (inactiveStates[state.self.name]) {
delete inactiveStates[state.self.name];
}
state.self.status = 'entered';
// if (state.locals == null || state.locals.globals == null) debugger;
if (state.self.onReactivate)
$injector.invoke(state.self.onReactivate, state.self, state.locals.globals);
},
// Exits all inactivated descendant substates when the ancestor state is exited.
// When transitionTo is exiting a state, this function is called with the state being exited. It checks the
// registry of inactivated states for descendants of the exited state and also exits those descendants. It then
// removes the locals and de-registers the state from the inactivated registry.
stateExiting: function (exiting, exitQueue, onExit) {
var exitingNames = {};
angular.forEach(exitQueue, function (state) {
exitingNames[state.self.name] = true;
});
angular.forEach(inactiveStates, function (inactiveExiting, name) {
// TODO: Might need to run the inactivations in the proper depth-first order?
if (!exitingNames[name] && inactiveExiting.includes[exiting.name]) {
if (DEBUG) $log.debug("Exiting " + name + " because it's a substate of " + exiting.name + " and wasn't found in ", exitingNames);
if (inactiveExiting.self.onExit)
$injector.invoke(inactiveExiting.self.onExit, inactiveExiting.self, inactiveExiting.locals.globals);
angular.forEach(inactiveExiting.locals, function(localval, key) {
delete inactivePseudoState.locals[key];
});
inactiveExiting.locals = null;
inactiveExiting.self.status = 'exited';
delete inactiveStates[name];
}
});
if (onExit)
$injector.invoke(onExit, exiting.self, exiting.locals.globals);
exiting.locals = null;
exiting.self.status = 'exited';
delete inactiveStates[exiting.self.name];
},
// Removes a previously inactivated state from the inactive sticky state registry
stateEntering: function (entering, params, onEnter) {
var inactivatedState = getInactivatedState(entering);
if (inactivatedState && !getInactivatedState(entering, params)) {
var savedLocals = entering.locals;
this.stateExiting(inactivatedState);
entering.locals = savedLocals;
}
entering.self.status = 'entered';
if (onEnter)
$injector.invoke(onEnter, entering.self, entering.locals.globals);
},
reset: function reset(inactiveState, params) {
var state = $state.get(inactiveState);
var exiting = getInactivatedState(state, params);
if (!exiting) return false;
stickySupport.stateExiting(exiting);
$rootScope.$broadcast("$viewContentLoading");
return true;
}
};
return stickySupport;
}];
}
angular.module("ct.ui.router.extras").provider("$stickyState", $StickyStateProvider);
/**
* Sticky States makes entire state trees "sticky". Sticky state trees are retained until their parent state is
* exited. This can be useful to allow multiple modules, peers to each other, each module having its own independent
* state tree. The peer modules can be activated and inactivated without any loss of their internal context, including
* DOM content such as unvalidated/partially filled in forms, and even scroll position.
*
* DOM content is retained by declaring a named ui-view in the parent state, and filling it in with a named view from the
* sticky state.
*
* Technical overview:
*
* ---PATHS---
* UI-Router uses state paths to manage entering and exiting of individual states. Each state "A.B.C.X" has its own path, starting
* from the root state ("") and ending at the state "X". The path is composed the final state "X"'s ancestors, e.g.,
* [ "", "A", "B", "C", "X" ].
*
* When a transition is processed, the previous path (fromState.path) is compared with the requested destination path
* (toState.path). All states that the from and to paths have in common are "kept" during the transition. The last
* "kept" element in the path is the "pivot".
*
* ---VIEWS---
* A View in UI-Router consists of a controller and a template. Each view belongs to one state, and a state can have many
* views. Each view plugs into a ui-view element in the DOM of one of the parent state's view(s).
*
* View context is managed in UI-Router using a 'state locals' concept. When a state's views are fully loaded, those views
* are placed on the states 'locals' object. Each locals object prototypally inherits from its parent state's locals object.
* This means that state "A.B.C.X"'s locals object also has all of state "A.B.C"'s locals as well as those from "A.B" and "A".
* The root state ("") defines no views, but it is included in the protypal inheritance chain.
*
* The locals object is used by the ui-view directive to load the template, render the content, create the child scope,
* initialize the controller, etc. The ui-view directives caches the locals in a closure variable. If the locals are
* identical (===), then the ui-view directive exits early, and does no rendering.
*
* In stock UI-Router, when a state is exited, that state's locals object is deleted and those views are cleaned up by
* the ui-view directive shortly.
*
* ---Sticky States---
* UI-Router Extras keeps views for inactive states live, even when UI-Router thinks it has exited them. It does this
* by creating a pseudo state called "__inactives" that is the parent of the root state. It also then defines a locals
* object on the "__inactives" state, which the root state protoypally inherits from. By doing this, views for inactive
* states are accessible through locals object's protoypal inheritance chain from any state in the system.
*
* ---Transitions---
* UI-Router Extras decorates the $state.transitionTo function. While a transition is in progress, the toState and
* fromState internal state representations are modified in order to coerce stock UI-Router's transitionTo() into performing
* the appropriate operations. When the transition promise is completed, the original toState and fromState values are
* restored.
*
* Stock UI-Router's $state.transitionTo function uses toState.path and fromState.path to manage entering and exiting
* states. UI-Router Extras takes advantage of those internal implementation details and prepares a toState.path and
* fromState.path which coerces UI-Router into entering and exiting the correct states, or more importantly, not entering
* and not exiting inactive or sticky states. It also replaces state.self.onEnter and state.self.onExit for elements in
* the paths when they are being inactivated or reactivated.
*/
// ------------------------ Sticky State module-level variables -----------------------------------------------
var _StickyState; // internal reference to $stickyStateProvider
var internalStates = {}; // Map { statename -> InternalStateObj } holds internal representation of all states
var root, // Root state, internal representation
pendingTransitions = [], // One transition may supersede another. This holds references to all pending transitions
pendingRestore, // The restore function from the superseded transition
inactivePseudoState, // This pseudo state holds all the inactive states' locals (resolved state data, such as views etc)
versionHeuristics = { // Heuristics used to guess the current UI-Router Version
hasParamSet: false
};
// Creates a blank surrogate state
function SurrogateState(type) {
return {
resolve: { },
locals: {
globals: root && root.locals && root.locals.globals
},
views: { },
self: { },
params: { },
ownParams: ( versionHeuristics.hasParamSet ? { $$equals: function() { return true; } } : []),
surrogateType: type
};
}
// ------------------------ Sticky State registration and initialization code ----------------------------------
// Grab a copy of the $stickyState service for use by the transition management code
angular.module("ct.ui.router.extras").run(["$stickyState", function ($stickyState) {
_StickyState = $stickyState;
}]);
angular.module("ct.ui.router.extras").config(
[ "$provide", "$stateProvider", '$stickyStateProvider', '$urlMatcherFactoryProvider',
function ($provide, $stateProvider, $stickyStateProvider, $urlMatcherFactoryProvider) {
versionHeuristics.hasParamSet = !!$urlMatcherFactoryProvider.ParamSet;
// inactivePseudoState (__inactives) holds all the inactive locals which includes resolved states data, i.e., views, scope, etc
inactivePseudoState = angular.extend(new SurrogateState("__inactives"), { self: { name: '__inactives' } });
// Reset other module scoped variables. This is to primarily to flush any previous state during karma runs.
root = pendingRestore = undefined;
pendingTransitions = [];
// Decorate any state attribute in order to get access to the internal state representation.
$stateProvider.decorator('parent', function (state, parentFn) {
// Capture each internal UI-Router state representations as opposed to the user-defined state object.
// The internal state is, e.g., the state returned by $state.$current as opposed to $state.current
internalStates[state.self.name] = state;
// Add an accessor for the internal state from the user defined state
state.self.$$state = function () {
return internalStates[state.self.name];
};
// Register the ones marked as "sticky"
if (state.self.sticky === true) {
$stickyStateProvider.registerStickyState(state.self);
}
return parentFn(state);
});
var $state_transitionTo; // internal reference to the real $state.transitionTo function
// Decorate the $state service, so we can decorate the $state.transitionTo() function with sticky state stuff.
$provide.decorator("$state", ['$delegate', '$log', '$q', function ($state, $log, $q) {
// Note: this code gets run only on the first state that is decorated
root = $state.$current;
internalStates[""] = root;
root.parent = inactivePseudoState; // Make inactivePsuedoState the parent of root. "wat"
inactivePseudoState.parent = undefined; // Make inactivePsuedoState the real root.
root.locals = inherit(inactivePseudoState.locals, root.locals); // make root locals extend the __inactives locals.
delete inactivePseudoState.locals.globals;
// Hold on to the real $state.transitionTo in a module-scope variable.
$state_transitionTo = $state.transitionTo;
// ------------------------ Decorated transitionTo implementation begins here ---------------------------
$state.transitionTo = function (to, toParams, options) {
// TODO: Move this to module.run?
// TODO: I'd rather have root.locals prototypally inherit from inactivePseudoState.locals
// Link root.locals and inactives.locals. Do this at runtime, after root.locals has been set.
if (!inactivePseudoState.locals)
inactivePseudoState.locals = root.locals;
var idx = pendingTransitions.length;
if (pendingRestore) {
pendingRestore();
if (DEBUG) {
$log.debug("Restored paths from pending transition");
}
}
var fromState = $state.$current, fromParams = $state.params;
var rel = options && options.relative || $state.$current; // Not sure if/when $state.$current is appropriate here.
var toStateSelf = $state.get(to, rel); // exposes findState relative path functionality, returns state.self
var savedToStatePath, savedFromStatePath, stickyTransitions;
var reactivated = [], exited = [], terminalReactivatedState;
var noop = function () {
};
// Sticky states works by modifying the internal state objects of toState and fromState, especially their .path(s).
// The restore() function is a closure scoped function that restores those states' definitions to their original values.
var restore = function () {
if (savedToStatePath) {
toState.path = savedToStatePath;
savedToStatePath = null;
}
if (savedFromStatePath) {
fromState.path = savedFromStatePath;
savedFromStatePath = null;
}
angular.forEach(restore.restoreFunctions, function (restoreFunction) {
restoreFunction();
});
// Restore is done, now set the restore function to noop in case it gets called again.
restore = noop;
// pendingRestore keeps track of a transition that is in progress. It allows the decorated transitionTo
// method to be re-entrant (for example, when superceding a transition, i.e., redirect). The decorated
// transitionTo checks right away if there is a pending transition in progress and restores the paths
// if so using pendingRestore.
pendingRestore = null;
pendingTransitions.splice(idx, 1); // Remove this transition from the list
};
// All decorated transitions have their toState.path and fromState.path replaced. Surrogate states also make
// additional changes to the states definition before handing the transition off to UI-Router. In particular,
// certain types of surrogate states modify the state.self object's onEnter or onExit callbacks.
// Those surrogate states must then register additional restore steps using restore.addRestoreFunction(fn)
restore.restoreFunctions = [];
restore.addRestoreFunction = function addRestoreFunction(fn) {
this.restoreFunctions.push(fn);
};
// --------------------- Surrogate State Functions ------------------------
// During a transition, the .path arrays in toState and fromState are replaced. Individual path elements
// (states) which aren't being "kept" are replaced with surrogate elements (states). This section of the code
// has factory functions for all the different types of surrogate states.
function stateReactivatedSurrogatePhase1(state) {
var surrogate = angular.extend(new SurrogateState("reactivate_phase1"), { locals: state.locals });
surrogate.self = angular.extend({}, state.self);
return surrogate;
}
function stateReactivatedSurrogatePhase2(state) {
var surrogate = angular.extend(new SurrogateState("reactivate_phase2"), state);
var oldOnEnter = surrogate.self.onEnter;
surrogate.resolve = {}; // Don't re-resolve when reactivating states (fixes issue #22)
// TODO: Not 100% sure if this is necessary. I think resolveState will load the views if I don't do this.
surrogate.views = {}; // Don't re-activate controllers when reactivating states (fixes issue #22)
surrogate.self.onEnter = function () {
// ui-router sets locals on the surrogate to a blank locals (because we gave it nothing to resolve)
// Re-set it back to the already loaded state.locals here.
surrogate.locals = state.locals;
_StickyState.stateReactivated(state);
};
restore.addRestoreFunction(function () {
state.self.onEnter = oldOnEnter;
});
return surrogate;
}
function stateInactivatedSurrogate(state) {
var surrogate = new SurrogateState("inactivate");
surrogate.self = state.self;
var oldOnExit = state.self.onExit;
surrogate.self.onExit = function () {
_StickyState.stateInactivated(state);
};
restore.addRestoreFunction(function () {
state.self.onExit = oldOnExit;
});
return surrogate;
}
function stateEnteredSurrogate(state, toParams) {
var oldOnEnter = state.self.onEnter;
state.self.onEnter = function () {
_StickyState.stateEntering(state, toParams, oldOnEnter);
};
restore.addRestoreFunction(function () {
state.self.onEnter = oldOnEnter;
});
return state;
}
function stateExitedSurrogate(state) {
var oldOnExit = state.self.onExit;
state.self.onExit = function () {
_StickyState.stateExiting(state, exited, oldOnExit);
};
restore.addRestoreFunction(function () {
state.self.onExit = oldOnExit;
});
return state;
}
// --------------------- decorated .transitionTo() logic starts here ------------------------
if (toStateSelf) {
var toState = internalStates[toStateSelf.name]; // have the state, now grab the internal state representation
if (toState) {
// Save the toState and fromState paths to be restored using restore()
savedToStatePath = toState.path;
savedFromStatePath = fromState.path;
var currentTransition = {toState: toState, toParams: toParams || {}, fromState: fromState, fromParams: fromParams || {}, options: options};
pendingTransitions.push(currentTransition); // TODO: See if a list of pending transitions is necessary.
pendingRestore = restore;
// $StickyStateProvider.processTransition analyzes the states involved in the pending transition. It
// returns an object that tells us:
// 1) if we're involved in a sticky-type transition
// 2) what types of exit transitions will occur for each "exited" path element
// 3) what types of enter transitions will occur for each "entered" path element
// 4) which states will be inactive if the transition succeeds.
stickyTransitions = _StickyState.processTransition(currentTransition);
if (DEBUG) debugTransition($log, currentTransition, stickyTransitions);
// Begin processing of surrogate to and from paths.
var surrogateToPath = toState.path.slice(0, stickyTransitions.keep);
var surrogateFromPath = fromState.path.slice(0, stickyTransitions.keep);
// Clear out and reload inactivePseudoState.locals each time transitionTo is called
angular.forEach(inactivePseudoState.locals, function (local, name) {
if (name.indexOf("@") != -1) delete inactivePseudoState.locals[name];
});
// Find all states that will be inactive once the transition succeeds. For each of those states,
// place its view-locals on the __inactives pseudostate's .locals. This allows the ui-view directive
// to access them and render the inactive views.
for (var i = 0; i < stickyTransitions.inactives.length; i++) {
var iLocals = stickyTransitions.inactives[i].locals;
angular.forEach(iLocals, function (view, name) {
if (iLocals.hasOwnProperty(name) && name.indexOf("@") != -1) { // Only grab this state's "view" locals
inactivePseudoState.locals[name] = view; // Add all inactive views not already included.
}
});
}
// Find all the states the transition will be entering. For each entered state, check entered-state-transition-type
// Depending on the entered-state transition type, place the proper surrogate state on the surrogate toPath.
angular.forEach(stickyTransitions.enter, function (value, idx) {
var surrogate;
if (value === "reactivate") {
// Reactivated states require TWO surrogates. The "phase 1 reactivated surrogates" are added to both
// to.path and from.path, and as such, are considered to be "kept" by UI-Router.
// This is required to get UI-Router to add the surrogate locals to the protoypal locals object
surrogate = stateReactivatedSurrogatePhase1(toState.path[idx]);
surrogateToPath.push(surrogate);
surrogateFromPath.push(surrogate); // so toPath[i] === fromPath[i]
// The "phase 2 reactivated surrogate" is added to the END of the .path, after all the phase 1
// surrogates have been added.
reactivated.push(stateReactivatedSurrogatePhase2(toState.path[idx]));
terminalReactivatedState = surrogate;
} else if (value === "updateStateParams") {
// If the state params have been changed, we need to exit any inactive states and re-enter them.
surrogate = stateEnteredSurrogate(toState.path[idx]);
surrogateToPath.push(surrogate);
terminalReactivatedState = surrogate;
} else if (value === "enter") {
// Standard enter transition. We still wrap it in a surrogate.
surrogateToPath.push(stateEnteredSurrogate(toState.path[idx]));
}
});
// Find all the states the transition will be exiting. For each exited state, check the exited-state-transition-type.
// Depending on the exited-state transition type, place a surrogate state on the surrogate fromPath.
angular.forEach(stickyTransitions.exit, function (value, idx) {
var exiting = fromState.path[idx];
if (value === "inactivate") {
surrogateFromPath.push(stateInactivatedSurrogate(exiting));
exited.push(exiting);
} else if (value === "exit") {
surrogateFromPath.push(stateExitedSurrogate(exiting));
exited.push(exiting);
}
});
// Add surrogate for reactivated to ToPath again, this time without a matching FromPath entry
// This is to get ui-router to call the surrogate's onEnter callback.
if (reactivated.length) {
angular.forEach(reactivated, function (surrogate) {
surrogateToPath.push(surrogate);
});
}
// In some cases, we may be some state, but not its children states. If that's the case, we have to
// exit all the children of the deepest reactivated state.
if (terminalReactivatedState) {
var prefix = terminalReactivatedState.self.name + ".";
var inactiveStates = _StickyState.getInactiveStates();
var inactiveOrphans = [];
inactiveStates.forEach(function (exiting) {
if (exiting.self.name.indexOf(prefix) === 0) {
inactiveOrphans.push(exiting);
}
});
inactiveOrphans.sort();
inactiveOrphans.reverse();
// Add surrogate exited states for all orphaned descendants of the Deepest Reactivated State
surrogateFromPath = surrogateFromPath.concat(map(inactiveOrphans, function (exiting) {
return stateExitedSurrogate(exiting);
}));
exited = exited.concat(inactiveOrphans);
}
// Replace the .path variables. toState.path and fromState.path are now ready for a sticky transition.
toState.path = surrogateToPath;
fromState.path = surrogateFromPath;
var pathMessage = function (state) {
return (state.surrogateType ? state.surrogateType + ":" : "") + state.self.name;
};
if (DEBUG) $log.debug("SurrogateFromPath: ", map(surrogateFromPath, pathMessage));
if (DEBUG) $log.debug("SurrogateToPath: ", map(surrogateToPath, pathMessage));
}
}
// toState and fromState are all set up; now run stock UI-Router's $state.transitionTo().
var transitionPromise = $state_transitionTo.apply($state, arguments);
// Add post-transition promise handlers, then return the promise to the original caller.
return transitionPromise.then(function transitionSuccess(state) {
// First, restore toState and fromState to their original values.
restore();
if (DEBUG) debugViewsAfterSuccess($log, internalStates[state.name], $state);
state.status = 'active'; // TODO: This status is used in statevis.js, and almost certainly belongs elsewhere.
return state;
}, function transitionFailed(err) {
restore();
if (DEBUG &&
err.message !== "transition prevented" &&
err.message !== "transition aborted" &&
err.message !== "transition superseded") {
$log.debug("transition failed", err);
console.log(err.stack);
}
return $q.reject(err);
});
};
return $state;
}]);
}
]
);
function debugTransition($log, currentTransition, stickyTransition) {
function message(path, index, state) {
return (path[index] ? path[index].toUpperCase() + ": " + state.self.name : "(" + state.self.name + ")");
}
var inactiveLogVar = map(stickyTransition.inactives, function (state) {
return state.self.name;
});
var enterLogVar = map(currentTransition.toState.path, function (state, index) {
return message(stickyTransition.enter, index, state);
});
var exitLogVar = map(currentTransition.fromState.path, function (state, index) {
return message(stickyTransition.exit, index, state);
});
var transitionMessage = currentTransition.fromState.self.name + ": " +
angular.toJson(currentTransition.fromParams) + ": " +
" -> " +
currentTransition.toState.self.name + ": " +
angular.toJson(currentTransition.toParams);
$log.debug(" Current transition: ", transitionMessage);
$log.debug("Before transition, inactives are: : ", map(_StickyState.getInactiveStates(), function (s) {
return s.self.name;
}));
$log.debug("After transition, inactives will be: ", inactiveLogVar);
$log.debug("Transition will exit: ", exitLogVar);
$log.debug("Transition will enter: ", enterLogVar);
}
function debugViewsAfterSuccess($log, currentState, $state) {
$log.debug("Current state: " + currentState.self.name + ", inactive states: ", map(_StickyState.getInactiveStates(), function (s) {
return s.self.name;
}));
var viewMsg = function (local, name) {
return "'" + name + "' (" + local.$$state.name + ")";
};
var statesOnly = function (local, name) {
return name != 'globals' && name != 'resolve';
};
var viewsForState = function (state) {
var views = map(filterObj(state.locals, statesOnly), viewMsg).join(", ");
return "(" + (state.self.name ? state.self.name : "root") + ".locals" + (views.length ? ": " + views : "") + ")";
};
var message = viewsForState(currentState);
var parent = currentState.parent;
while (parent && parent !== currentState) {
if (parent.self.name === "") {
// Show the __inactives before showing root state.
message = viewsForState($state.$current.path[0]) + " / " + message;
}
message = viewsForState(parent) + " / " + message;
currentState = parent;
parent = currentState.parent;
}
$log.debug("Views: " + message);
}
angular.module('ct.ui.router.extras').provider('$futureState',
[ '$stateProvider', '$urlRouterProvider', '$urlMatcherFactoryProvider',
function _futureStateProvider($stateProvider, $urlRouterProvider, $urlMatcherFactory) {
var stateFactories = {}, futureStates = {};
var transitionPending = false, resolveFunctions = [], initPromise, initDone = false;
var provider = this;
// This function registers a promiseFn, to be resolved before the url/state matching code
// will reject a route. The promiseFn is injected/executed using the runtime $injector.
// The function should return a promise.
// When all registered promises are resolved, then the route is re-sync'ed.
// Example: function($http) {
// return $http.get('//server.com/api/DynamicFutureStates').then(function(data) {
// angular.forEach(data.futureStates, function(fstate) { $futureStateProvider.futureState(fstate); });
// };
// }
this.addResolve = function (promiseFn) {
resolveFunctions.push(promiseFn);
};
// Register a state factory function for a particular future-state type. This factory, given a future-state object,
// should create a ui-router state.
// The factory function is injected/executed using the runtime $injector. The future-state is injected as 'futureState'.
// Example:
// $futureStateProvider.stateFactory('test', function(futureState) {
// return {
// name: futureState.stateName,
// url: futureState.urlFragment,
// template: '<h3>Future State Template</h3>',
// controller: function() {
// console.log("Entered state " + futureState.stateName);
// }
// }
// });
this.stateFactory = function (futureStateType, factory) {
stateFactories[futureStateType] = factory;
};
this.futureState = function (futureState) {
if (futureState.stateName) // backwards compat for now
futureState.name = futureState.stateName;
if (futureState.urlPrefix) // backwards compat for now
futureState.url = "^" + futureState.urlPrefix;
futureStates[futureState.name] = futureState;
var parentMatcher, parentName = futureState.name.split(/\./).slice(0, -1).join("."),
realParent = findState(futureState.parent || parentName);
if (realParent) {
parentMatcher = realParent.url;
} else {
var futureParent = findState((futureState.parent || parentName), true);
if (!futureParent) throw new Error("Couldn't determine parent state of future state. FutureState:" + angular.toJson(futureState));
var pattern = futureParent.urlMatcher.source.replace(/\*rest$/, "");
parentMatcher = $urlMatcherFactory.compile(pattern);
futureState.parentFutureState = futureParent;
}
futureState.urlMatcher = futureState.url.charAt(0) === "^" ?
$urlMatcherFactory.compile(futureState.url.substring(1) + "*rest") :
parentMatcher.concat(futureState.url + "*rest");
};
this.get = function () {
return angular.extend({}, futureStates);
};
function findState(stateOrName, findFutureState) {
var statename = angular.isObject(stateOrName) ? stateOrName.name : stateOrName;
return !findFutureState ? internalStates[statename] : futureStates[statename];
}
/* options is an object with at least a name or url attribute */
function findFutureState($state, options) {
if (options.name) {
var nameComponents = options.name.split(/\./);
if (options.name.charAt(0) === '.')
nameComponents[0] = $state.current.name;
while (nameComponents.length) {
var stateName = nameComponents.join(".");
if ($state.get(stateName, { relative: $state.current }))
return null; // State is already defined; nothing to do
if (futureStates[stateName])
return futureStates[stateName];
nameComponents.pop();
}
}
if (options.url) {
var matches = [];
for(var future in futureStates) {
if (futureStates[future].urlMatcher.exec(options.url)) {
matches.push(futureStates[future]);
}
}
// Find most specific by ignoring matching parents from matches
var copy = matches.slice(0);
for (var i = matches.length - 1; i >= 0; i--) {
for (var j = 0; j < copy.length; j++) {
if (matches[i] === copy[j].parentFutureState) matches.splice(i, 1);
}
}
return matches[0];
}
}
function lazyLoadState($injector, futureState) {
if (!futureState) {
var deferred = $q.defer();
deferred.reject("No lazyState passed in " + futureState);
return deferred.promise;
}
var promise = $q.when(true), parentFuture = futureState.parentFutureState;
if (parentFuture && futureStates[parentFuture.name]) {
promise = lazyLoadState($injector, futureStates[parentFuture.name]);
}
var type = futureState.type;
var factory = stateFactories[type];
if (!factory) throw Error("No state factory for futureState.type: " + (futureState && futureState.type));
return promise
.then(function() {
return $injector.invoke(factory, factory, { futureState: futureState });
})
.finally(function() {
delete(futureStates[futureState.name]);
});
}
var otherwiseFunc = [ '$log', '$location',
function otherwiseFunc($log, $location) {
$log.debug("Unable to map " + $location.path());
}];
function futureState_otherwise($injector, $location) {
var resyncing = false;
var lazyLoadMissingState =
['$rootScope', '$urlRouter', '$state',
function lazyLoadMissingState($rootScope, $urlRouter, $state) {
if (!initDone) {
// Asynchronously load state definitions, then resync URL
initPromise().then(function initialResync() {
resyncing = true;
$urlRouter.sync();
resyncing = false;
});
initDone = true;
return;
}
var futureState = findFutureState($state, { url: $location.path() });
if (!futureState) {
return $injector.invoke(otherwiseFunc);
}
transitionPending = true;
// Config loaded. Asynchronously lazy-load state definition from URL fragment, if mapped.
lazyLoadState($injector, futureState).then(function lazyLoadedStateCallback(state) {
// TODO: Should have a specific resolve value that says 'dont register a state because I already did'
if (state && (!$state.get(state) || (state.name && !$state.get(state.name))))
$stateProvider.state(state);
resyncing = true;
$urlRouter.sync();
resyncing = false;
transitionPending = false;
}, function lazyLoadStateAborted() {
transitionPending = false;
return $injector.invoke(otherwiseFunc);
});
}];
if (transitionPending) return;
var nextFn = resyncing ? otherwiseFunc : lazyLoadMissingState;
return $injector.invoke(nextFn);
}
$urlRouterProvider.otherwise(futureState_otherwise);
$urlRouterProvider.otherwise = function(rule) {
if (angular.isString(rule)) {
var redirect = rule;
rule = function () { return redirect; };
}
else if (!angular.isFunction(rule)) throw new Error("'rule' must be a function");
otherwiseFunc = rule;
return $urlRouterProvider;
};
var serviceObject = {
getResolvePromise: function () {
return initPromise();
}
};
// Used in .run() block to init
this.$get = [ '$injector', '$state', '$q', '$rootScope', '$urlRouter', '$timeout', '$log',
function futureStateProvider_get($injector, $state, $q, $rootScope, $urlRouter, $timeout, $log) {
function init() {
$rootScope.$on("$stateNotFound", function futureState_notFound(event, unfoundState, fromState, fromParams) {
if (transitionPending) return;
$log.debug("event, unfoundState, fromState, fromParams", event, unfoundState, fromState, fromParams);
var futureState = findFutureState($state, { name: unfoundState.to });
if (!futureState) return;
event.preventDefault();
transitionPending = true;
var promise = lazyLoadState($injector, futureState);
promise.then(function (state) {
// TODO: Should have a specific resolve value that says 'dont register a state because I already did'
if (state && (!$state.get(state) || (state.name && !$state.get(state.name))))
$stateProvider.state(state);
$state.go(unfoundState.to, unfoundState.toParams);
transitionPending = false;
}, function (error) {
console.log("failed to lazy load state ", error);
$state.go(fromState, fromParams);
transitionPending = false;
});
});
// Do this better. Want to load remote config once, before everything else
if (!initPromise) {
var promises = [];
angular.forEach(resolveFunctions, function (promiseFn) {
promises.push($injector.invoke(promiseFn));
});
initPromise = function () {
return $q.all(promises);
};
// initPromise = _.once(function flattenFutureStates() {
// var allPromises = $q.all(promises);
// return allPromises.then(function(data) {
// return _.flatten(data);
// });
// });
}
// TODO: analyze this. I'm calling $urlRouter.sync() in two places for retry-initial-transition.
// TODO: I should only need to do this once. Pick the better place and remove the extra resync.
initPromise().then(function retryInitialState() {
$timeout(function () {
if ($state.transition) {
$state.transition.then($urlRouter.sync, $urlRouter.sync);
} else {
$urlRouter.sync();
}
});
});
}
init();
serviceObject.state = $stateProvider.state;
serviceObject.futureState = provider.futureState;
serviceObject.get = provider.get;
return serviceObject;
}];
}]);
angular.module('ct.ui.router.extras').run(['$futureState',
// Just inject $futureState so it gets initialized.
function ($futureState) {
}
]);
angular.module('ct.ui.router.extras').service("$previousState",
[ '$rootScope', '$state',
function ($rootScope, $state) {
var previous = null;
var memos = {};
var lastPrevious = null;
$rootScope.$on("$stateChangeStart", function (evt, toState, toStateParams, fromState, fromStateParams) {
// State change is starting. Keep track of the CURRENT previous state in case we have to restore it
lastPrevious = previous;
previous = { state: fromState, params: fromStateParams };
});
$rootScope.$on("$stateChangeError", function () {
// State change did not occur due to an error. Restore the previous previous state.
previous = lastPrevious;
lastPrevious = null;
});
$rootScope.$on("$stateChangeSuccess", function () {
lastPrevious = null;
});
var $previousState = {
get: function (memoName) {
return memoName ? memos[memoName] : previous;
},
go: function (memoName, options) {
var to = $previousState.get(memoName);
return $state.go(to.state, to.params, options);
},
memo: function (memoName, defaultStateName, defaultStateParams) {
memos[memoName] = previous || { state: $state.get(defaultStateName), params: defaultStateParams };
},
forget: function (memoName) {
delete memos[memoName];
}
};
return $previousState;
}
]
);
angular.module('ct.ui.router.extras').run(['$previousState', function ($previousState) {
// Inject $previousState so it can register $rootScope events
}]);
angular.module("ct.ui.router.extras").config( [ "$provide", function ($provide) {
// Decorate the $state service, so we can replace $state.transitionTo()
$provide.decorator("$state", ['$delegate', '$rootScope', '$q', '$injector',
function ($state, $rootScope, $q, $injector) {
// Keep an internal reference to the real $state.transitionTo function
var $state_transitionTo = $state.transitionTo;
// $state.transitionTo can be re-entered. Keep track of re-entrant stack
var transitionDepth = -1;
var tDataStack = [];
var restoreFnStack = [];
// This function decorates the $injector, adding { $transition$: tData } to invoke() and instantiate() locals.
// It returns a function that restores $injector to its previous state.
function decorateInjector(tData) {
var oldinvoke = $injector.invoke;
var oldinstantiate = $injector.instantiate;
$injector.invoke = function (fn, self, locals) {
return oldinvoke(fn, self, angular.extend({$transition$: tData}, locals));
};
$injector.instantiate = function (fn, locals) {
return oldinstantiate(fn, angular.extend({$transition$: tData}, locals));
};
return function restoreItems() {
$injector.invoke = oldinvoke;
$injector.instantiate = oldinstantiate;
};
}
function popStack() {
restoreFnStack.pop()();
tDataStack.pop();
transitionDepth--;
}
// This promise callback (for when the real transitionTo is successful) runs the restore function for the
// current stack level, then broadcasts the $transitionSuccess event.
function transitionSuccess(deferred, tSuccess) {
return function successFn(data) {
popStack();
$rootScope.$broadcast("$transitionSuccess", tSuccess);
return deferred.resolve(data);
};
}
// This promise callback (for when the real transitionTo fails) runs the restore function for the
// current stack level, then broadcasts the $transitionError event.
function transitionFailure(deferred, tFail) {
return function failureFn(error) {
popStack();
$rootScope.$broadcast("$transitionError", tFail, error);
return deferred.reject(error);
};
}
// Decorate $state.transitionTo.
$state.transitionTo = function (to, toParams, options) {
// Create a deferred/promise which can be used earlier than UI-Router's transition promise.
var deferred = $q.defer();
// Place the promise in a transition data, and place it on the stack to be used in $stateChangeStart
var tData = tDataStack[++transitionDepth] = {
promise: deferred.promise
};
// placeholder restoreFn in case transitionTo doesn't reach $stateChangeStart (state not found, etc)
restoreFnStack[transitionDepth] = function() { };
// Invoke the real $state.transitionTo
var tPromise = $state_transitionTo.apply($state, arguments);
// insert our promise callbacks into the chain.
return tPromise.then(transitionSuccess(deferred, tData), transitionFailure(deferred, tData));
};
// This event is handled synchronously in transitionTo call stack
$rootScope.$on("$stateChangeStart", function (evt, toState, toParams, fromState, fromParams) {
var depth = transitionDepth;
// To/From is now normalized by ui-router. Add this information to the transition data object.
var tData = angular.extend(tDataStack[depth], {
to: { state: toState, params: toParams },
from: { state: fromState, params: fromParams }
});
var restoreFn = decorateInjector(tData);
restoreFnStack[depth] = restoreFn;
$rootScope.$broadcast("$transitionStart", tData);
}
);
return $state;
}]);
}
]
);
})(window, window.angular);
|
wil93/cdnjs
|
ajax/libs/ui-router-extras/0.0.11-pre1/ct-ui-router-extras.js
|
JavaScript
|
mit
| 64,111
|
/**
* Unbind all event handlers before tearing down the page
*/
AJAX.registerTeardown('tbl_tracking.js', function () {
$('body').off('click', '#versionsForm.ajax button[name="submit_mult"], #versionsForm.ajax input[name="submit_mult"]');
$('body').off('click', 'a.delete_version_anchor.ajax');
$('body').off('click', 'a.delete_entry_anchor.ajax');
});
/**
* Bind event handlers
*/
AJAX.registerOnload('tbl_tracking.js', function () {
$('#versions tr:first th').append($('<div class="sorticon"></div>'));
$('#versions').tablesorter({
sortList: [[1, 0]],
headers: {
0: {sorter: false},
1: {sorter: "integer"},
5: {sorter: false},
6: {sorter: false}
}
});
if ($('#ddl_versions tbody tr').length > 0) {
$('#ddl_versions tr:first th').append($('<div class="sorticon"></div>'));
$('#ddl_versions').tablesorter({
sortList: [[0, 0]],
headers: {
0: {sorter: "integer"},
3: {sorter: false},
4: {sorter: false}
}
});
}
if ($('#dml_versions tbody tr').length > 0) {
$('#dml_versions tr:first th').append($('<div class="sorticon"></div>'));
$('#dml_versions').tablesorter({
sortList: [[0, 0]],
headers: {
0: {sorter: "integer"},
3: {sorter: false},
4: {sorter: false}
}
});
}
/**
* Handles multi submit for tracking versions
*/
$('body').on('click', '#versionsForm.ajax button[name="submit_mult"], #versionsForm.ajax input[name="submit_mult"]', function (e) {
e.preventDefault();
var $button = $(this);
var $form = $button.parent('form');
var submitData = $form.serialize() + '&ajax_request=true&ajax_page_request=true&submit_mult=' + $button.val();
if ($button.val() == 'delete_version') {
var question = PMA_messages.strDeleteTrackingVersionMultiple;
$button.PMA_confirm(question, $form.attr('action'), function (url) {
PMA_ajaxShowMessage();
AJAX.source = $form;
$.post(url, submitData, AJAX.responseHandler);
});
} else {
PMA_ajaxShowMessage();
AJAX.source = $form;
$.post($form.attr('action'), submitData, AJAX.responseHandler);
}
});
/**
* Ajax Event handler for 'Delete version'
*/
$('body').on('click', 'a.delete_version_anchor.ajax', function (e) {
e.preventDefault();
var $anchor = $(this);
var question = PMA_messages.strDeleteTrackingVersion;
$anchor.PMA_confirm(question, $anchor.attr('href'), function (url) {
PMA_ajaxShowMessage();
AJAX.source = $anchor;
$.get(url, {'ajax_page_request': true, 'ajax_request': true}, AJAX.responseHandler);
});
});
/**
* Ajax Event handler for 'Delete tracking report entry'
*/
$('body').on('click', 'a.delete_entry_anchor.ajax', function (e) {
e.preventDefault();
var $anchor = $(this);
var question = PMA_messages.strDeletingTrackingEntry;
$anchor.PMA_confirm(question, $anchor.attr('href'), function (url) {
PMA_ajaxShowMessage();
AJAX.source = $anchor;
$.get(url, {'ajax_page_request': true, 'ajax_request': true}, AJAX.responseHandler);
});
});
});
|
Dokaponteam/ITF_Project
|
xampp/phpMyAdmin/js/tbl_tracking.js
|
JavaScript
|
mit
| 3,522
|