code
stringlengths
2
1.05M
/*! * medium-editor-insert-plugin v0.3.1 - jQuery insert plugin for MediumEditor * * https://github.com/orthes/medium-editor-insert-plugin * * Copyright (c) 2014 Pavel Linkesch (http://linkesch.sk) * Released under the MIT license */ (function ($) { $.fn.mediumInsert.registerAddon('embeds', { /** * Embed default options */ defaults: { urlPlaceholder: 'Paste or type a link' //,oembedProxy: 'http://medium.iframe.ly/api/oembed?iframe=1' }, /** * Embeds initial function * @return {void} */ init : function (options) { this.options = $.extend(this.defaults, options); this.$el = $.fn.mediumInsert.insert.$el; this.setEmbedButtonEvents(); this.preparePreviousEmbeds(); }, insertButton : function (buttonLabels) { var label = 'Embed'; if (buttonLabels === 'fontawesome' || typeof buttonLabels === 'object' && !!(buttonLabels.fontawesome)) { label = '<i class="fa fa-code"></i>'; } if (typeof buttonLabels === 'object' && buttonLabels.embed) { label = buttonLabels.embed; } return '<button data-addon="embeds" data-action="add" class="medium-editor-action mediumInsert-action">' + label + '</button>'; }, /** * Add embed to $placeholder * @param {element} $placeholder $placeholder to add embed to * @return {void} */ add : function ($placeholder) { $.fn.mediumInsert.insert.deselect(); var formHtml = '<div class="medium-editor-toolbar medium-editor-toolbar-active medium-editor-toolbar-form-anchor mediumInsert-embedsWire" style="display: block;"><input type="text" value="" placeholder="' + this.options.urlPlaceholder + '" class="mediumInsert-embedsText medium-editor-toolbar-anchor-input"></div>'; $(formHtml).appendTo($placeholder.prev()); setTimeout(function () { $placeholder.prev().find('input').focus(); }, 50); $.fn.mediumInsert.insert.deselect(); this.currentPlaceholder = $placeholder; $(".mediumInsert-embedsText").focus(); }, /** * Make existing embeds interactive * * @return {void} */ preparePreviousEmbeds: function () { this.$el.find('.mediumInsert-embeds').each(function() { var $parent = $(this).parent(); $parent.html('<div class="mediumInsert-placeholder" draggable="true">' + $parent.html() + '</div>'); }); }, setEmbedButtonEvents : function () { var that = this; $(document).on('keypress', 'input.mediumInsert-embedsText', function (e) { if ((e.which && e.which === 13) || (e.keyCode && e.keyCode === 13)) { that.setEnterActionEvents(); that.removeToolbar(); } }); this.$el .on('blur', '.mediumInsert-embedsText', function () { that.removeToolbar(); }) // Fix #72 // Workaround for CTRL+V not working in FF, when cleanPastedHTML and forcePlainText options on editor are set to true, // because editor steals the event and doesn't pass it to the plugin // https://github.com/orthes/medium-editor-insert-plugin/issues/72 .on('paste', '.mediumInsert-embedsText', function (e) { if ($.fn.mediumInsert.insert.isFirefox && e.originalEvent.clipboardData) { $(this).val(e.originalEvent.clipboardData.getData('text/plain')); } }); }, setEnterActionEvents : function () { var that = this; if ($.fn.mediumInsert.settings.enabled === false) { return false; } var url = $("input.mediumInsert-embedsText").val(); if (!url) { return false; } function processEmbedTag(embed_tag) { if (!embed_tag) { alert('Incorrect URL format specified'); return false; } else { var returnedTag = embed_tag; var tagId = new Date().getTime(); embed_tag = $('<div class="mediumInsert-embeds" id="' + tagId + '"></div>').append(embed_tag); that.currentPlaceholder.append(embed_tag); that.currentPlaceholder.closest('[data-medium-element]').trigger('keyup').trigger('input'); if(returnedTag.indexOf("facebook") !== -1) { if (typeof(FB) !== 'undefined') { setTimeout(function() { FB.XFBML.parse();}, 2000); } } } } if (this.options.oembedProxy) { that.getOEmbedHTML(url, function(error, oebmed) { var html = !error && oebmed && oebmed.html; if (oebmed && !oebmed.html && oebmed.type === 'photo' && oebmed.url) { html = '<img src="' + oebmed.url + '" />'; } processEmbedTag(html); }); } else { var embed_tag = that.convertUrlToEmbedTag(url); return processEmbedTag(embed_tag); } }, removeToolbar : function () { $(".mediumInsert-embedsWire").remove(); }, getOEmbedHTML: function(url, cb) { $.ajax({ url: this.options.oembedProxy, dataType: "json", data: { url: url }, success: function(data, textStatus, jqXHR) { cb(null, data, jqXHR); }, error: function(jqXHR, textStatus, errorThrown) { var responseJSON = (function() { try { return JSON.parse(jqXHR.responseText); } catch(e) {} }()); cb((responseJSON && responseJSON.error) || jqXHR.status || errorThrown.message, responseJSON, jqXHR); } }); }, convertUrlToEmbedTag : function (url) { // We didn't get something we expect so let's get out of here. if (!(new RegExp(['youtube', 'yout.be', 'vimeo', 'facebook', 'instagram'].join("|")).test(url))) return false; var embed_tag = url.replace(/\n?/g, '').replace(/^((http(s)?:\/\/)?(www\.)?(youtube\.com|youtu\.be)\/(watch\?v=|v\/)?)([a-zA-Z0-9\-_]+)(.*)?$/, '<div class="video"><iframe width="420" height="315" src="//www.youtube.com/embed/$7" frameborder="0" allowfullscreen></iframe></div>') .replace(/^http:\/\/vimeo\.com(\/.+)?\/([0-9]+)$/, '<iframe src="//player.vimeo.com/video/$2" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>') //.replace(/^https:\/\/twitter\.com\/(\w+)\/status\/(\d+)\/?$/, '<blockquote class="twitter-tweet" align="center" lang="en"><a href="https://twitter.com/$1/statuses/$2"></a></blockquote><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>') .replace(/^https:\/\/www\.facebook\.com\/(video.php|photo.php)\?v=(\d+).+$/, '<div class="fb-post" data-href="https://www.facebook.com/photo.php?v=$2"><div class="fb-xfbml-parse-ignore"><a href="https://www.facebook.com/photo.php?v=$2">Post</a></div></div>') .replace(/^http:\/\/instagram\.com\/p\/(.+)\/?$/, '<span class="instagram"><iframe src="//instagram.com/p/$1/embed/" width="612" height="710" frameborder="0" scrolling="no" allowtransparency="true"></iframe></span>'); return (/<("[^"]*"|'[^']*'|[^'">])*>/).test(embed_tag) ? embed_tag : false; } }); }(jQuery));
var unitlessNumbers={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexOrder:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,fontWeight:!0,gridRow:!0,gridRowEnd:!0,gridRowGap:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnGap:!0,gridColumnStart:!0,lineClamp:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0,scale:!0,scaleX:!0,scaleY:!0,scaleZ:!0,shadowOpacity:!0},prefixes=["ms","Moz","O","Webkit"],prefixKey=function(e,r){return e+r.charAt(0).toUpperCase()+r.substring(1)};Object.keys(unitlessNumbers).forEach(function(r){prefixes.forEach(function(e){unitlessNumbers[prefixKey(e,r)]=unitlessNumbers[r]})});export default unitlessNumbers;
!function(a,b,c){var d=b.Rollbar;if(d){var e="0.0.8";d.configure({notifier:{plugins:{jquery:{version:e}}}});var f=function(a){d.error(a),b.console&&b.console.log(a.message+" [reported to Rollbar]")};a(c).ajaxError(function(a,b,c,e){var f=b.status,g=c.url,h=c.type;if(f){var i;e&&e.hasOwnProperty("stack")&&(i=e);var j={status:f,url:g,type:h,isAjax:!0};d.warning("jQuery ajax error for "+h,j,i)}});var g=a.fn.ready;a.fn.ready=function(a){return g.call(this,function(b){try{a(b)}catch(c){f(c)}})};var h=a.event.add;a.event.add=function(b,c,d,e,g){var i,j=function(a){return function(){try{return a.apply(this,arguments)}catch(b){f(b)}}};return d.handler?(i=d.handler,d.handler=j(d.handler)):(i=d,d=j(d)),d.guid=i.guid?i.guid:i.guid=a.guid++,h.call(this,b,c,d,e,g)}}}(jQuery,window,document);
// Copyright Joyent, Inc. and other Node contributors. // // 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. // A bit simpler than readable streams. // Implement an async ._write(chunk, cb), and it'll handle all // the drain event emission and buffering. module.exports = Writable; Writable.WritableState = WritableState; var util = require('util'); var assert = require('assert'); var Stream = require('stream'); var Duplex = require('./duplex.js'); util.inherits(Writable, Stream); function WritableState(options, stream) { options = options || {}; // the point at which write() starts returning false this.highWaterMark = options.hasOwnProperty('highWaterMark') ? options.highWaterMark : 16 * 1024; // the point that it has to get to before we call _write(chunk,cb) // default to pushing everything out as fast as possible. this.lowWaterMark = options.hasOwnProperty('lowWaterMark') ? options.lowWaterMark : 0; // cast to ints. assert(typeof this.lowWaterMark === 'number'); assert(typeof this.highWaterMark === 'number'); this.lowWaterMark = ~~this.lowWaterMark; this.highWaterMark = ~~this.highWaterMark; assert(this.lowWaterMark >= 0); assert(this.highWaterMark >= this.lowWaterMark, this.highWaterMark + '>=' + this.lowWaterMark); this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' has emitted this.finished = false; // when 'finish' is being emitted this.finishing = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. this.decodeStrings = options.hasOwnProperty('decodeStrings') ? options.decodeStrings : true; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. this.sync = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function(er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.buffer = []; } function Writable(options) { // Writable ctor is applied to Duplexes, though they're not // instanceof Writable, they're instanceof Readable. if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); this._writableState = new WritableState(options, this); // legacy. this.writable = true; Stream.call(this); } // Override this method or _write(chunk, cb) Writable.prototype.write = function(chunk, encoding, cb) { var state = this._writableState; if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (state.ended) { var er = new Error('write after end'); if (typeof cb === 'function') cb(er); this.emit('error', er); return; } var l = chunk.length; if (false === state.decodeStrings) chunk = [chunk, encoding || 'utf8']; else if (typeof chunk === 'string' || encoding) { chunk = new Buffer(chunk + '', encoding); l = chunk.length; } state.length += l; var ret = state.length < state.highWaterMark; if (ret === false) state.needDrain = true; // if we're already writing something, then just put this // in the queue, and wait our turn. if (state.writing) { state.buffer.push([chunk, cb]); return ret; } state.writing = true; state.sync = true; state.writelen = l; state.writecb = cb; this._write(chunk, state.onwrite); state.sync = false; return ret; }; function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; var l = state.writelen; state.writing = false; state.writelen = null; state.writecb = null; if (er) { if (cb) { if (sync) process.nextTick(function() { cb(er); }); else cb(er); } else stream.emit('error', er); return; } state.length -= l; if (cb) { // don't call the cb until the next tick if we're in sync mode. // also, defer if we're about to write some more right now. if (sync || state.buffer.length) process.nextTick(cb); else cb(); } if (state.length === 0 && (state.ended || state.ending)) { // emit 'finish' at the very end. state.finishing = true; stream.emit('finish'); state.finished = true; return; } // if there's something in the buffer waiting, then do that, too. if (state.buffer.length) { var chunkCb = state.buffer.shift(); var chunk = chunkCb[0]; cb = chunkCb[1]; if (false === state.decodeStrings) l = chunk[0].length; else l = chunk.length; state.writelen = l; state.writecb = cb; state.writechunk = chunk; state.writing = true; stream._write(chunk, state.onwrite); } if (state.length <= state.lowWaterMark && state.needDrain) { // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. process.nextTick(function() { if (!state.needDrain) return; state.needDrain = false; stream.emit('drain'); }); } } Writable.prototype._write = function(chunk, cb) { process.nextTick(function() { cb(new Error('not implemented')); }); }; Writable.prototype.end = function(chunk, encoding) { var state = this._writableState; // ignore unnecessary end() calls. if (state.ending || state.ended || state.finished) return; state.ending = true; if (chunk) this.write(chunk, encoding); else if (state.length === 0) { state.finishing = true; this.emit('finish'); state.finished = true; } state.ended = true; };
define( ({ 'bold': 'Halvfet', 'copy': 'Kopiera', 'cut': 'Klipp ut', 'delete': 'Ta bort', 'indent': 'Indrag', 'insertHorizontalRule': 'Horisontell linje', 'insertOrderedList': 'Numrerad lista', 'insertUnorderedList': 'Punktlista', 'italic': 'Kursiv', 'justifyCenter': 'Centrera', 'justifyFull': 'Marginaljustera', 'justifyLeft': 'Vänsterjustera', 'justifyRight': 'Högerjustera', 'outdent': 'Utdrag', 'paste': 'Klistra in', 'redo': 'Gör om', 'removeFormat': 'Ta bort format', 'selectAll': 'Markera allt', 'strikethrough': 'Genomstruken', 'subscript': 'Nedsänkt', 'superscript': 'Upphöjt', 'underline': 'Understruken', 'undo': 'Ångra', 'unlink': 'Ta bort länk', 'createLink': 'Skapa länk', 'toggleDir': 'Växla riktning', 'insertImage': 'Infoga bild', 'insertTable': 'Infoga/redigera tabell', 'toggleTableBorder': 'Växla tabellinjer', 'deleteTable': 'Ta bort tabell', 'tableProp': 'Tabellegenskap', 'htmlToggle': 'HTML-källkod', 'foreColor': 'Förgrundsfärg', 'hiliteColor': 'Bakgrundsfärg', 'plainFormatBlock': 'Styckeformat', 'formatBlock': 'Styckeformat', 'fontSize': 'Teckenstorlek', 'fontName': 'Teckensnitt', 'tabIndent': 'Tabbindrag', "fullScreen": "Växla helskärm", "viewSource": "Visa HTML-kod", "print": "Skriv ut", "newPage": "Ny sida", /* Error messages */ 'systemShortcut': 'Åtgärden ${0} är endast tillgänglig i webbläsaren via ett tangentbordskommando. Använd ${1}.', 'ctrlKey':'Ctrl+${0}', 'appleKey':'\u2318${0}' // "command" or open-apple key on Macintosh }) );
/* * * Date.addLocale(<code>) adds this locale to Sugar. * To set the locale globally, simply call: * * Date.setLocale('es'); * * var locale = Date.getLocale(<code>) will return this object, which * can be tweaked to change the behavior of parsing/formatting in the locales. * * locale.addFormat adds a date format (see this file for examples). * Special tokens in the date format will be parsed out into regex tokens: * * {0} is a reference to an entry in locale.tokens. Output: (?:the)? * {unit} is a reference to all units. Output: (day|week|month|...) * {unit3} is a reference to a specific unit. Output: (hour) * {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week) * {unit?} "?" makes that token optional. Output: (day|week|month)? * * {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow) * * All spaces are optional and will be converted to "\s*" * * Locale arrays months, weekdays, units, numbers, as well as the "src" field for * all entries in the modifiers array follow a special format indicated by a colon: * * minute:|s = minute|minutes * thicke:n|r = thicken|thicker * * Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples * of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in: * * units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays'] * * When matched, the index will be found using: * * units.indexOf(match) % 7; * * Resulting in the correct index with any number of alternates for that entry. * */ Date.addLocale('es', { 'plural': true, 'months': 'enero,febrero,marzo,abril,mayo,junio,julio,agosto,septiembre,octubre,noviembre,diciembre', 'weekdays': 'domingo,lunes,martes,miércoles|miercoles,jueves,viernes,sábado|sabado', 'units': 'milisegundo:|s,segundo:|s,minuto:|s,hora:|s,día|días|dia|dias,semana:|s,mes:|es,año|años|ano|anos', 'numbers': 'uno,dos,tres,cuatro,cinco,seis,siete,ocho,nueve,diez', 'tokens': 'el,de', 'short':'{d} {month} {yyyy}', 'long': '{d} {month} {yyyy} {H}:{mm}', 'full': '{Weekday} {d} {month} {yyyy} {H}:{mm}:{ss}', 'past': '{sign} {num} {unit}', 'future': '{num} {unit} {sign}', 'duration': '{num} {unit}', 'timeMarker': 'a las', 'ampm': 'am,pm', 'modifiers': [ { 'name': 'day', 'src': 'anteayer', 'value': -2 }, { 'name': 'day', 'src': 'ayer', 'value': -1 }, { 'name': 'day', 'src': 'hoy', 'value': 0 }, { 'name': 'day', 'src': 'mañana|manana', 'value': 1 }, { 'name': 'sign', 'src': 'hace', 'value': -1 }, { 'name': 'sign', 'src': 'de ahora', 'value': 1 }, { 'name': 'shift', 'src': 'pasad:o|a', 'value': -1 }, { 'name': 'shift', 'src': 'próximo|próxima|proximo|proxima', 'value': 1 } ], 'dateParse': [ '{sign} {num} {unit}', '{num} {unit} {sign}', '{0?} {unit=5-7} {shift}', '{0?} {shift} {unit=5-7}' ], 'timeParse': [ '{shift} {weekday}', '{weekday} {shift}', '{date?} {1?} {month} {1?} {year?}' ] });
/* YUI 3.17.0 (build ce55cc9) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('axis-category-base', function (Y, NAME) { /** * Provides functionality for the handling of category axis data for a chart. * * @module charts * @submodule axis-category-base */ var Y_Lang = Y.Lang; /** * CategoryImpl contains logic for managing category data. CategoryImpl is used by the following classes: * <ul> * <li>{{#crossLink "CategoryAxisBase"}}{{/crossLink}}</li> * <li>{{#crossLink "CategoryAxis"}}{{/crossLink}}</li> * </ul> * * @class CategoryImpl * @constructor * @submodule axis-category-base */ function CategoryImpl() { } CategoryImpl.NAME = "categoryImpl"; CategoryImpl.ATTRS = { /** * Pattern used by the `labelFunction` to format a label. The default `labelFunction` values for * `CategoryAxis` and `CategoryAxisBase` do not accept a format object. This value can be used by * a custom method. * * @attribute labelFormat * @type Object */ labelFormat: { value: null }, /** * Determines whether and offset is automatically calculated for the edges of the axis. * * @attribute calculateEdgeOffset * @type Boolean */ calculateEdgeOffset: { value: true } /** * Method used for formatting a label. This attribute allows for the default label formatting method to overridden. * The method use would need to implement the arguments below and return a `String` or `HTMLElement`. * <dl> * <dt>val</dt><dd>Label to be formatted. (`String`)</dd> * <dt>format</dt><dd>Template for formatting label. (optional)</dd> * </dl> * * @attribute labelFunction * @type Function */ }; CategoryImpl.prototype = { /** * Formats a label based on the axis type and optionally specified format. * * @method formatLabel * @param {Object} value * @return String */ formatLabel: function(val) { return val; }, /** * Object storing key data. * * @property _indices * @private */ _indices: null, /** * Constant used to generate unique id. * * @property GUID * @type String * @private */ GUID: "yuicategoryaxis", /** * Type of data used in `Data`. * * @property _dataType * @readOnly * @private */ _type: "category", /** * Calculates the maximum and minimum values for the `Data`. * * @method _updateMinAndMax * @private */ _updateMinAndMax: function() { this._dataMaximum = Math.max(this.get("data").length - 1, 0); this._dataMinimum = 0; }, /** * Gets an array of values based on a key. * * @method _getKeyArray * @param {String} key Value key associated with the data array. * @param {Array} data Array in which the data resides. * @return Array * @private */ _getKeyArray: function(key, data) { var i = 0, obj, keyArr = [], labels = [], len = data.length; if(!this._indices) { this._indices = {}; } for(; i < len; ++i) { obj = data[i]; keyArr[i] = i; labels[i] = obj[key]; } this._indices[key] = keyArr; return labels; }, /** * Returns an array of values based on an identifier key. * * @method getDataByKey * @param {String} value value used to identify the array * @return Array */ getDataByKey: function (value) { if(!this._indices) { this.get("keys"); } var keys = this._indices; if(keys && keys[value]) { return keys[value]; } return null; }, /** * Returns the total number of majorUnits that will appear on an axis. * * @method getTotalMajorUnits * @param {Object} majorUnit Object containing properties related to the majorUnit. * @param {Number} len Length of the axis. * @return Number */ getTotalMajorUnits: function() { return this.get("data").length; }, /** * Returns a coordinate corresponding to a data values. * * @method _getCoordFromValue * @param {Number} min The minimum for the axis. * @param {Number} max The maximum for the axis. * @param {Number} length The distance that the axis spans. * @param {Number} dataValue A value used to ascertain the coordinate. * @param {Number} offset Value in which to offset the coordinates. * @param {Boolean} reverse Indicates whether the coordinates should start from * the end of an axis. Only used in the numeric implementation. * @return Number * @private */ _getCoordFromValue: function(min, max, length, dataValue, offset) { var range, multiplier, valuecoord; if(Y_Lang.isNumber(dataValue)) { range = max - min; multiplier = length/range; valuecoord = (dataValue - min) * multiplier; valuecoord = offset + valuecoord; } else { valuecoord = NaN; } return valuecoord; }, /** * Returns a value based of a key value and an index. * * @method getKeyValueAt * @param {String} key value used to look up the correct array * @param {Number} index within the array * @return String */ getKeyValueAt: function(key, index) { var value = NaN, keys = this.get("keys"); if(keys[key] && keys[key][index]) { value = keys[key][index]; } return value; } }; Y.CategoryImpl = CategoryImpl; /** * CategoryAxisBase manages category data for an axis. * * @class CategoryAxisBase * @constructor * @extends AxisBase * @uses CategoryImpl * @param {Object} config (optional) Configuration parameters. * @submodule axis-category-base */ Y.CategoryAxisBase = Y.Base.create("categoryAxisBase", Y.AxisBase, [Y.CategoryImpl]); }, '3.17.0', {"requires": ["axis-base"]});
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'removeformat', 'en-gb', { toolbar: 'Remove Format' } );
'use strict'; const assert = require('assert'); let battle; describe('Magic Room', function () { afterEach(function () { battle.destroy(); }); it('should negate residual healing events', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: "Lopunny", ability: 'limber', item: 'leftovers', moves: ['bellydrum']}]); battle.join('p2', 'Guest 2', 1, [{species: "Giratina", ability: 'pressure', moves: ['magicroom']}]); battle.commitDecisions(); assert.strictEqual(battle.p1.active[0].hp, Math.ceil(battle.p1.active[0].maxhp / 2)); }); it('should prevent items from being consumed', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: "Lopunny", ability: 'limber', item: 'chopleberry', moves: ['magicroom']}]); battle.join('p2', 'Guest 2', 1, [{species: "Golem", ability: 'noguard', moves: ['lowkick']}]); battle.commitDecisions(); assert.strictEqual(battle.p1.active[0].item, 'chopleberry'); }); it('should ignore the effects of items that disable moves', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: "Lopunny", ability: 'limber', item: 'assaultvest', moves: ['protect']}]); battle.join('p2', 'Guest 2', 1, [{species: "Golem", ability: 'noguard', moves: ['magicroom']}]); battle.commitDecisions(); battle.commitDecisions(); assert.strictEqual(battle.p1.active[0].lastMove, 'protect'); }); it('should cause Fling to fail', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: "Lopunny", ability: 'limber', item: 'seaincense', moves: ['fling']}]); battle.join('p2', 'Guest 2', 1, [{species: "Sableye", ability: 'prankster', moves: ['magicroom']}]); battle.commitDecisions(); assert.strictEqual(battle.p1.active[0].item, 'seaincense'); }); it('should not prevent Pokemon from Mega Evolving', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: "Lopunny", ability: 'limber', item: 'lopunnite', moves: ['bulkup']}]); battle.join('p2', 'Guest 2', 1, [{species: "Golem", ability: 'noguard', moves: ['magicroom', 'rest']}]); battle.commitDecisions(); battle.choose('p1', 'move 1 mega'); battle.choose('p2', 'move 2'); assert.strictEqual(battle.p1.active[0].template.speciesid, 'lopunnymega'); }); it('should not prevent Primal Reversion', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [ {species: "Zapdos", ability: 'pressure', moves: ['voltswitch']}, {species: "Groudon", ability: 'drought', item: 'redorb', moves: ['protect']}, ]); battle.join('p2', 'Guest 2', 1, [{species: "Meowstic", ability: 'prankster', moves: ['magicroom']}]); battle.commitDecisions(); battle.choose('p1', 'switch 2'); assert.strictEqual(battle.p1.active[0].template.speciesid, 'groudonprimal'); }); });
run_spec(__dirname, ["typescript", "babel", "flow"]);
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); //>>description: Creates collapsible content blocks. //>>label: Collapsible //>>group: Widgets //>>css.structure: ../css/structure/jquery.mobile.collapsible.css //>>css.theme: ../css/themes/default/jquery.mobile.theme.css define( [ "jquery", // Deprecated as of 1.4.0 and will be removed in 1.5.0 // We only need this dependency so we get the $.widget shim from page, so we // can use $.mobile.collapsible.initSelector in collapsibleset. As of 1.5.0 // we will assume that all children of the collapsibleset are to be turned // into collapsibles. "./page", "../jquery.mobile.core", "../jquery.mobile.widget" ], function( jQuery ) { //>>excludeEnd("jqmBuildExclude"); (function( $, undefined ) { var rInitialLetter = /([A-Z])/g; $.widget( "mobile.collapsible", { options: { enhanced: false, expandCueText: null, collapseCueText: null, collapsed: true, heading: "h1,h2,h3,h4,h5,h6,legend", collapsedIcon: null, expandedIcon: null, iconpos: null, theme: null, contentTheme: null, inset: null, corners: null, mini: null }, _create: function() { var elem = this.element, ui = { accordion: elem .closest( ":jqmData(role='collapsible-set')" + ( $.mobile.collapsibleset ? ", :mobile-collapsibleset" : "" ) ) .addClass( "ui-collapsible-set" ) }; $.extend( this, { _ui: ui }); if ( this.options.enhanced ) { ui.heading = $( ".ui-collapsible-heading", this.element[ 0 ] ); ui.content = ui.heading.next(); ui.anchor = $( "a", ui.heading[ 0 ] ).first(); ui.status = ui.anchor.children( ".ui-collapsible-heading-status" ); } else { this._enhance( elem, ui ); } this._on( ui.heading, { "tap": function() { ui.heading.find( "a" ).first().addClass( $.mobile.activeBtnClass ); }, "click": function( event ) { this._handleExpandCollapse( !ui.heading.hasClass( "ui-collapsible-heading-collapsed" ) ); event.preventDefault(); event.stopPropagation(); } }); }, // Adjust the keys inside options for inherited values _getOptions: function( options ) { var key, accordion = this._ui.accordion, accordionWidget = this._ui.accordionWidget; // Copy options options = $.extend( {}, options ); if ( accordion.length && !accordionWidget ) { this._ui.accordionWidget = accordionWidget = accordion.data( "mobile-collapsibleset" ); } for ( key in options ) { // Retrieve the option value first from the options object passed in and, if // null, from the parent accordion or, if that's null too, or if there's no // parent accordion, then from the defaults. options[ key ] = ( options[ key ] != null ) ? options[ key ] : ( accordionWidget ) ? accordionWidget.options[ key ] : accordion.length ? $.mobile.getAttribute( accordion[ 0 ], key.replace( rInitialLetter, "-$1" ).toLowerCase() ): null; if ( null == options[ key ] ) { options[ key ] = $.mobile.collapsible.defaults[ key ]; } } return options; }, _themeClassFromOption: function( prefix, value ) { return ( value ? ( value === "none" ? "" : prefix + value ) : "" ); }, _enhance: function( elem, ui ) { var iconclass, opts = this._getOptions( this.options ), contentThemeClass = this._themeClassFromOption( "ui-body-", opts.contentTheme ); elem.addClass( "ui-collapsible " + ( opts.inset ? "ui-collapsible-inset " : "" ) + ( opts.inset && opts.corners ? "ui-corner-all " : "" ) + ( contentThemeClass ? "ui-collapsible-themed-content " : "" ) ); ui.originalHeading = elem.children( this.options.heading ).first(), ui.content = elem .wrapInner( "<div " + "class='ui-collapsible-content " + contentThemeClass + "'></div>" ) .children( ".ui-collapsible-content" ), ui.heading = ui.originalHeading; // Replace collapsibleHeading if it's a legend if ( ui.heading.is( "legend" ) ) { ui.heading = $( "<div role='heading'>"+ ui.heading.html() +"</div>" ); ui.placeholder = $( "<div><!-- placeholder for legend --></div>" ).insertBefore( ui.originalHeading ); ui.originalHeading.remove(); } iconclass = ( opts.collapsed ? ( opts.collapsedIcon ? "ui-icon-" + opts.collapsedIcon : "" ): ( opts.expandedIcon ? "ui-icon-" + opts.expandedIcon : "" ) ); ui.status = $( "<span class='ui-collapsible-heading-status'></span>" ); ui.anchor = ui.heading .detach() //modify markup & attributes .addClass( "ui-collapsible-heading" ) .append( ui.status ) .wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" ) .find( "a" ) .first() .addClass( "ui-btn " + ( iconclass ? iconclass + " " : "" ) + ( iconclass ? ( "ui-btn-icon-" + ( opts.iconpos === "right" ? "right" : "left" ) ) + " " : "" ) + this._themeClassFromOption( "ui-btn-", opts.theme ) + " " + ( opts.mini ? "ui-mini " : "" ) ); //drop heading in before content ui.heading.insertBefore( ui.content ); this._handleExpandCollapse( this.options.collapsed ); return ui; }, refresh: function() { var key, options = {}; for ( key in $.mobile.collapsible.defaults ) { options[ key ] = this.options[ key ]; } this._setOptions( options ); }, _setOptions: function( options ) { var isCollapsed, newTheme, oldTheme, hasCorners, elem = this.element, currentOpts = this._getOptions( this.options ), ui = this._ui, anchor = ui.anchor, status = ui.status, opts = this._getOptions( options ); // First and foremost we need to make sure the collapsible is in the proper // state, in case somebody decided to change the collapsed option at the // same time as another option if ( options.collapsed !== undefined ) { this._handleExpandCollapse( options.collapsed ); } isCollapsed = elem.hasClass( "ui-collapsible-collapsed" ); // Only options referring to the current state need to be applied right away // It is enough to store options covering the alternate in this.options. if ( isCollapsed ) { if ( opts.expandCueText !== undefined ) { status.text( opts.expandCueText ); } if ( opts.collapsedIcon !== undefined ) { if ( currentOpts.collapsedIcon ) { anchor.removeClass( "ui-icon-" + currentOpts.collapsedIcon ); } if ( opts.collapsedIcon ) { anchor.addClass( "ui-icon-" + opts.collapsedIcon ); } } } else { if ( opts.collapseCueText !== undefined ) { status.text( opts.collapseCueText ); } if ( opts.expandedIcon !== undefined ) { if ( currentOpts.expandedIcon ) { anchor.removeClass( "ui-icon-" + currentOpts.expandedIcon ); } if ( opts.expandedIcon ) { anchor.addClass( "ui-icon-" + opts.expandedIcon ); } } } if ( opts.iconpos !== undefined ) { anchor.removeClass( "ui-btn-icon-" + ( currentOpts.iconPos === "right" ? "right" : "left" ) ); anchor.addClass( "ui-btn-icon-" + ( opts.iconPos === "right" ? "right" : "left" ) ); } if ( opts.theme !== undefined ) { oldTheme = this._themeClassFromOption( "ui-btn-", currentOpts.theme ); newTheme = this._themeClassFromOption( "ui-btn-", opts.theme ); anchor.removeClass( oldTheme ).addClass( newTheme ); } if ( opts.contentTheme !== undefined ) { oldTheme = this._themeClassFromOption( "ui-body-", currentOpts.theme ); newTheme = this._themeClassFromOption( "ui-body-", opts.theme ); ui.content.removeClass( oldTheme ).addClass( newTheme ); } if ( opts.inset !== undefined ) { elem.toggleClass( "ui-collapsible-inset", opts.inset ); hasCorners = !!( opts.inset && ( opts.corners || currentOpts.corners ) ); } if ( opts.corners !== undefined ) { hasCorners = !!( opts.corners && ( opts.inset || currentOpts.inset ) ); } if ( hasCorners !== undefined ) { elem.toggleClass( "ui-corner-all", hasCorners ); } if ( opts.mini !== undefined ) { anchor.toggleClass( "ui-mini", opts.mini ); } this._super( options ); }, _handleExpandCollapse: function( isCollapse ) { var opts = this._getOptions( this.options ), ui = this._ui; ui.status.text( isCollapse ? opts.expandCueText : opts.collapseCueText ); ui.heading .toggleClass( "ui-collapsible-heading-collapsed", isCollapse ) .find( "a" ).first() .toggleClass( "ui-icon-" + opts.expandedIcon, !isCollapse ) // logic or cause same icon for expanded/collapsed state would remove the ui-icon-class .toggleClass( "ui-icon-" + opts.collapsedIcon, ( isCollapse || opts.expandedIcon === opts.collapsedIcon ) ) .removeClass( $.mobile.activeBtnClass ); this.element.toggleClass( "ui-collapsible-collapsed", isCollapse ); ui.content .toggleClass( "ui-collapsible-content-collapsed", isCollapse ) .attr( "aria-hidden", isCollapse ) .trigger( "updatelayout" ); this.options.collapsed = isCollapse; this._trigger( isCollapse ? "collapse" : "expand" ); }, expand: function() { this._handleExpandCollapse( false ); }, collapse: function() { this._handleExpandCollapse( true ); }, _destroy: function() { var ui = this._ui, opts = this.options; if ( opts.enhanced ) { return; } if ( ui.placeholder ) { ui.originalHeading.insertBefore( ui.placeholder ); ui.placeholder.remove(); ui.heading.remove(); } else { ui.status.remove(); ui.heading .removeClass( "ui-collapsible-heading ui-collapsible-heading-collapsed" ) .children() .contents() .unwrap(); } ui.anchor.contents().unwrap(); ui.content.contents().unwrap(); this.element .removeClass( "ui-collapsible ui-collapsible-collapsed " + "ui-collapsible-themed-content ui-collapsible-inset ui-corner-all" ); } }); // Defaults to be used by all instances of collapsible if per-instance values // are unset or if nothing is specified by way of inheritance from an accordion. // Note that this hash does not contain options "collapsed" or "heading", // because those are not inheritable. $.mobile.collapsible.defaults = { expandCueText: " click to expand contents", collapseCueText: " click to collapse contents", collapsedIcon: "plus", contentTheme: "inherit", expandedIcon: "minus", iconpos: "left", inset: true, corners: true, theme: "inherit", mini: false }; })( jQuery ); //>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); }); //>>excludeEnd("jqmBuildExclude");
describe('getLocation', function() { before(h.setup()); it('should return the location of a single element', function() { return this.client.getLocation('header h1').then(function (location) { /** * between devices and platform this can be different */ location.x.should.be.below(27); location.y.should.be.below(27); }); }); it('should return a specific property width of the location if set', function() { return this.client.getLocation('header h1', 'x').then(function (x) { x.should.be.below(27); }); }); it('should return a specific property width of the location if set', function() { return this.client.getLocation('header h1', 'y').then(function (y) { y.should.be.below(27); }); }); it('should return the location of multiple elements', function() { return this.client.getLocation('.box').then(function (locations) { locations.should.be.an.instanceOf(Array); locations.should.have.length(5); locations.forEach(function(location) { location.x.should.be.type('number'); location.y.should.be.type('number'); }); }); }); });
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Defines the {@link CKEDITOR.lang} object, for the * Arabic language. */ /**#@+ @type String @example */ /** * Constains the dictionary of language entries. * @namespace */ CKEDITOR.lang['ar'] = { /** * The language reading direction. Possible values are "rtl" for * Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right * languages (like English). * @default 'ltr' */ dir : 'rtl', /* * Screenreader titles. Please note that screenreaders are not always capable * of reading non-English words. So be careful while translating it. */ editorTitle : 'Rich text editor, %1, press ALT 0 for help.', // MISSING // ARIA descriptions. toolbars : 'Editor toolbars', // MISSING editor : 'Rich Text Editor', // MISSING // Toolbar buttons without dialogs. source : 'المصدر', newPage : 'صفحة جديدة', save : 'حفظ', preview : 'معاينة الصفحة', cut : 'قص', copy : 'نسخ', paste : 'لصق', print : 'طباعة', underline : 'تسطير', bold : 'غامق', italic : 'مائل', selectAll : 'تحديد الكل', removeFormat : 'إزالة التنسيقات', strike : 'يتوسطه خط', subscript : 'منخفض', superscript : 'مرتفع', horizontalrule : 'خط فاصل', pagebreak : 'إدخال صفحة جديدة', pagebreakAlt : 'Page Break', // MISSING unlink : 'إزالة رابط', undo : 'تراجع', redo : 'إعادة', // Common messages and labels. common : { browseServer : 'تصفح', url : 'الرابط', protocol : 'البروتوكول', upload : 'رفع', uploadSubmit : 'أرسل', image : 'صورة', flash : 'فلاش', form : 'نموذج', checkbox : 'خانة إختيار', radio : 'زر اختيار', textField : 'مربع نص', textarea : 'مساحة نصية', hiddenField : 'إدراج حقل خفي', button : 'زر ضغط', select : 'اختار', imageButton : 'زر صورة', notSet : '<بدون تحديد>', id : 'الرقم', name : 'الاسم', langDir : 'إتجاه النص', langDirLtr : 'اليسار لليمين (LTR)', langDirRtl : 'اليمين لليسار (RTL)', langCode : 'رمز اللغة', longDescr : 'الوصف التفصيلى', cssClass : 'فئات التنسيق', advisoryTitle : 'عنوان التقرير', cssStyle : 'نمط', ok : 'موافق', cancel : 'إلغاء الأمر', close : 'Close', // MISSING preview : 'Preview', // MISSING generalTab : 'عام', advancedTab : 'متقدم', validateNumberFailed : 'لايوجد نتيجة', confirmNewPage : 'ستفقد أي متغييرات اذا لم تقم بحفظها اولا. هل أنت متأكد أنك تريد صفحة جديدة؟', confirmCancel : 'بعض الخيارات قد تغيرت. هل أنت متأكد من إغلاق مربع النص؟', options : 'Options', // MISSING target : 'Target', // MISSING targetNew : 'New Window (_blank)', // MISSING targetTop : 'Topmost Window (_top)', // MISSING targetSelf : 'Same Window (_self)', // MISSING targetParent : 'Parent Window (_parent)', // MISSING langDirLTR : 'Left to Right (LTR)', // MISSING langDirRTL : 'Right to Left (RTL)', // MISSING styles : 'Style', // MISSING cssClasses : 'Stylesheet Classes', // MISSING width : 'العرض', height : 'الإرتفاع', align : 'محاذاة', alignLeft : 'يسار', alignRight : 'يمين', alignCenter : 'وسط', alignTop : 'أعلى', alignMiddle : 'وسط', alignBottom : 'أسفل', invalidHeight : 'الارتفاع يجب أن يكون عدداً.', invalidWidth : 'العرض يجب أن يكون عدداً.', invalidCssLength : 'Value specified for the "%1" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).', // MISSING invalidHtmlLength : 'Value specified for the "%1" field must be a positive number with or without a valid HTML measurement unit (px or %).', // MISSING // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, غير متاح</span>' }, contextmenu : { options : 'Context Menu Options' // MISSING }, // Special char dialog. specialChar : { toolbar : 'إدراج خاص.ِ', title : 'اختر الخواص', options : 'Special Character Options' // MISSING }, // Link dialog. link : { toolbar : 'رابط', other : '<أخرى>', menu : 'تحرير رابط', title : 'إرتباط تشعبي', info : 'معلومات الرابط', target : 'هدف الرابط', upload : 'رفع', advanced : 'متقدم', type : 'نوع الربط', toUrl : 'URL', // MISSING toAnchor : 'مكان في هذا المستند', toEmail : 'بريد إلكتروني', targetFrame : '<إطار>', targetPopup : '<نافذة منبثقة>', targetFrameName : 'اسم الإطار المستهدف', targetPopupName : 'اسم النافذة المنبثقة', popupFeatures : 'خصائص النافذة المنبثقة', popupResizable : 'قابلة التشكيل', popupStatusBar : 'شريط الحالة', popupLocationBar: 'شريط العنوان', popupToolbar : 'شريط الأدوات', popupMenuBar : 'القوائم الرئيسية', popupFullScreen : 'ملئ الشاشة (IE)', popupScrollBars : 'أشرطة التمرير', popupDependent : 'تابع (Netscape)', popupLeft : 'التمركز لليسار', popupTop : 'التمركز للأعلى', id : 'هوية', langDir : 'إتجاه النص', langDirLTR : 'اليسار لليمين (LTR)', langDirRTL : 'اليمين لليسار (RTL)', acccessKey : 'مفاتيح الإختصار', name : 'الاسم', langCode : 'كود النص', tabIndex : 'الترتيب', advisoryTitle : 'عنوان التقرير', advisoryContentType : 'نوع التقرير', cssClasses : 'فئات التنسيق', charset : 'ترميز المادة المطلوبة', styles : 'نمط', rel : 'Relationship', // MISSING selectAnchor : 'اختر علامة مرجعية', anchorName : 'حسب الاسم', anchorId : 'حسب رقم العنصر', emailAddress : 'عنوان البريد إلكتروني', emailSubject : 'موضوع الرسالة', emailBody : 'محتوى الرسالة', noAnchors : '(لا توجد علامات مرجعية في هذا المستند)', noUrl : 'من فضلك أدخل عنوان الموقع الذي يشير إليه الرابط', noEmail : 'من فضلك أدخل عنوان البريد الإلكتروني' }, // Anchor dialog anchor : { toolbar : 'إشارة مرجعية', menu : 'تحرير الإشارة المرجعية', title : 'خصائص الإشارة المرجعية', name : 'اسم الإشارة المرجعية', errorName : 'الرجاء كتابة اسم الإشارة المرجعية', remove : 'Remove Anchor' // MISSING }, // List style dialog list: { numberedTitle : 'Numbered List Properties', // MISSING bulletedTitle : 'Bulleted List Properties', // MISSING type : 'Type', // MISSING start : 'Start', // MISSING validateStartNumber :'List start number must be a whole number.', // MISSING circle : 'Circle', // MISSING disc : 'Disc', // MISSING square : 'Square', // MISSING none : 'None', // MISSING notset : '<not set>', // MISSING armenian : 'Armenian numbering', // MISSING georgian : 'Georgian numbering (an, ban, gan, etc.)', // MISSING lowerRoman : 'Lower Roman (i, ii, iii, iv, v, etc.)', // MISSING upperRoman : 'Upper Roman (I, II, III, IV, V, etc.)', // MISSING lowerAlpha : 'Lower Alpha (a, b, c, d, e, etc.)', // MISSING upperAlpha : 'Upper Alpha (A, B, C, D, E, etc.)', // MISSING lowerGreek : 'Lower Greek (alpha, beta, gamma, etc.)', // MISSING decimal : 'Decimal (1, 2, 3, etc.)', // MISSING decimalLeadingZero : 'Decimal leading zero (01, 02, 03, etc.)' // MISSING }, // Find And Replace Dialog findAndReplace : { title : 'بحث واستبدال', find : 'بحث', replace : 'إستبدال', findWhat : 'البحث بـ:', replaceWith : 'إستبدال بـ:', notFoundMsg : 'لم يتم العثور على النص المحدد.', matchCase : 'مطابقة حالة الأحرف', matchWord : 'مطابقة بالكامل', matchCyclic : 'مطابقة دورية', replaceAll : 'إستبدال الكل', replaceSuccessMsg : 'تم استبدال 1% من الحالات ' }, // Table Dialog table : { toolbar : 'جدول', title : 'خصائص الجدول', menu : 'خصائص الجدول', deleteTable : 'حذف الجدول', rows : 'صفوف', columns : 'أعمدة', border : 'الحدود', widthPx : 'بكسل', widthPc : 'بالمئة', widthUnit : 'width unit', // MISSING cellSpace : 'تباعد الخلايا', cellPad : 'المسافة البادئة', caption : 'الوصف', summary : 'الخلاصة', headers : 'العناوين', headersNone : 'بدون', headersColumn : 'العمود الأول', headersRow : 'الصف الأول', headersBoth : 'كلاهما', invalidRows : 'عدد الصفوف يجب أن يكون عدداً أكبر من صفر.', invalidCols : 'عدد الأعمدة يجب أن يكون عدداً أكبر من صفر.', invalidBorder : 'حجم الحد يجب أن يكون عدداً.', invalidWidth : 'عرض الجدول يجب أن يكون عدداً.', invalidHeight : 'ارتفاع الجدول يجب أن يكون عدداً.', invalidCellSpacing : 'المسافة بين الخلايا يجب أن تكون عدداً.', invalidCellPadding : 'المسافة البادئة يجب أن تكون عدداً', cell : { menu : 'خلية', insertBefore : 'إدراج خلية قبل', insertAfter : 'إدراج خلية بعد', deleteCell : 'حذف خلية', merge : 'دمج خلايا', mergeRight : 'دمج لليمين', mergeDown : 'دمج للأسفل', splitHorizontal : 'تقسيم الخلية أفقياً', splitVertical : 'تقسيم الخلية عمودياً', title : 'خصائص الخلية', cellType : 'نوع الخلية', rowSpan : 'امتداد الصفوف', colSpan : 'امتداد الأعمدة', wordWrap : 'التفاف النص', hAlign : 'محاذاة أفقية', vAlign : 'محاذاة رأسية', alignBaseline : 'خط القاعدة', bgColor : 'لون الخلفية', borderColor : 'لون الحدود', data : 'بيانات', header : 'عنوان', yes : 'نعم', no : 'لا', invalidWidth : 'عرض الخلية يجب أن يكون عدداً.', invalidHeight : 'ارتفاع الخلية يجب أن يكون عدداً.', invalidRowSpan : 'امتداد الصفوف يجب أن يكون عدداً صحيحاً.', invalidColSpan : 'امتداد الأعمدة يجب أن يكون عدداً صحيحاً.', chooseColor : 'اختر' }, row : { menu : 'صف', insertBefore : 'إدراج صف قبل', insertAfter : 'إدراج صف بعد', deleteRow : 'حذف صفوف' }, column : { menu : 'عمود', insertBefore : 'إدراج عمود قبل', insertAfter : 'إدراج عمود بعد', deleteColumn : 'حذف أعمدة' } }, // Button Dialog. button : { title : 'خصائص زر الضغط', text : 'القيمة/التسمية', type : 'نوع الزر', typeBtn : 'زر', typeSbm : 'إرسال', typeRst : 'إعادة تعيين' }, // Checkbox and Radio Button Dialogs. checkboxAndRadio : { checkboxTitle : 'خصائص خانة الإختيار', radioTitle : 'خصائص زر الخيار', value : 'القيمة', selected : 'محدد' }, // Form Dialog. form : { title : 'خصائص النموذج', menu : 'خصائص النموذج', action : 'اسم الملف', method : 'الأسلوب', encoding : 'تشفير' }, // Select Field Dialog. select : { title : 'خصائص اختيار الحقل', selectInfo : 'اختار معلومات', opAvail : 'الخيارات المتاحة', value : 'القيمة', size : 'الحجم', lines : 'الأسطر', chkMulti : 'السماح بتحديدات متعددة', opText : 'النص', opValue : 'القيمة', btnAdd : 'إضافة', btnModify : 'تعديل', btnUp : 'أعلى', btnDown : 'أسفل', btnSetValue : 'إجعلها محددة', btnDelete : 'إزالة' }, // Textarea Dialog. textarea : { title : 'خصائص مساحة النص', cols : 'الأعمدة', rows : 'الصفوف' }, // Text Field Dialog. textfield : { title : 'خصائص مربع النص', name : 'الاسم', value : 'القيمة', charWidth : 'عرض السمات', maxChars : 'اقصى عدد للسمات', type : 'نوع المحتوى', typeText : 'نص', typePass : 'كلمة مرور' }, // Hidden Field Dialog. hidden : { title : 'خصائص الحقل المخفي', name : 'الاسم', value : 'القيمة' }, // Image Dialog. image : { title : 'خصائص الصورة', titleButton : 'خصائص زر الصورة', menu : 'خصائص الصورة', infoTab : 'معلومات الصورة', btnUpload : 'أرسلها للخادم', upload : 'رفع', alt : 'عنوان الصورة', lockRatio : 'تناسق الحجم', resetSize : 'إستعادة الحجم الأصلي', border : 'سمك الحدود', hSpace : 'تباعد أفقي', vSpace : 'تباعد عمودي', alertUrl : 'فضلاً أكتب الموقع الذي توجد عليه هذه الصورة.', linkTab : 'الرابط', button2Img : 'هل تريد تحويل زر الصورة المختار إلى صورة بسيطة؟', img2Button : 'هل تريد تحويل الصورة المختارة إلى زر صورة؟', urlMissing : 'عنوان مصدر الصورة مفقود', validateBorder : 'Border must be a whole number.', // MISSING validateHSpace : 'HSpace must be a whole number.', // MISSING validateVSpace : 'VSpace must be a whole number.' // MISSING }, // Flash Dialog flash : { properties : 'خصائص الفلاش', propertiesTab : 'الخصائص', title : 'خصائص فيلم الفلاش', chkPlay : 'تشغيل تلقائي', chkLoop : 'تكرار', chkMenu : 'تمكين قائمة فيلم الفلاش', chkFull : 'ملء الشاشة', scale : 'الحجم', scaleAll : 'إظهار الكل', scaleNoBorder : 'بلا حدود', scaleFit : 'ضبط تام', access : 'دخول النص البرمجي', accessAlways : 'دائماً', accessSameDomain: 'نفس النطاق', accessNever : 'مطلقاً', alignAbsBottom : 'أسفل النص', alignAbsMiddle : 'وسط السطر', alignBaseline : 'على السطر', alignTextTop : 'أعلى النص', quality : 'جودة', qualityBest : 'أفضل', qualityHigh : 'عالية', qualityAutoHigh : 'عالية تلقائياً', qualityMedium : 'متوسطة', qualityAutoLow : 'منخفضة تلقائياً', qualityLow : 'منخفضة', windowModeWindow: 'نافذة', windowModeOpaque: 'غير شفاف', windowModeTransparent : 'شفاف', windowMode : 'وضع النافذة', flashvars : 'متغيرات الفلاش', bgcolor : 'لون الخلفية', hSpace : 'تباعد أفقي', vSpace : 'تباعد عمودي', validateSrc : 'فضلاً أدخل عنوان الموقع الذي يشير إليه الرابط', validateHSpace : 'HSpace يجب أن يكون عدداً.', validateVSpace : 'VSpace يجب أن يكون عدداً.' }, // Speller Pages Dialog spellCheck : { toolbar : 'تدقيق إملائي', title : 'التدقيق الإملائي', notAvailable : 'عفواً، ولكن هذه الخدمة غير متاحة الان', errorLoading : 'خطأ في تحميل تطبيق خدمة الاستضافة: %s.', notInDic : 'ليست في القاموس', changeTo : 'التغيير إلى', btnIgnore : 'تجاهل', btnIgnoreAll : 'تجاهل الكل', btnReplace : 'تغيير', btnReplaceAll : 'تغيير الكل', btnUndo : 'تراجع', noSuggestions : '- لا توجد إقتراحات -', progress : 'جاري التدقيق الاملائى', noMispell : 'تم التدقيق الإملائي: لم يتم العثور على أي أخطاء إملائية', noChanges : 'تم التدقيق الإملائي: لم يتم تغيير أي كلمة', oneChange : 'تم التدقيق الإملائي: تم تغيير كلمة واحدة فقط', manyChanges : 'تم إكمال التدقيق الإملائي: تم تغيير %1 من كلمات', ieSpellDownload : 'المدقق الإملائي (الإنجليزي) غير مثبّت. هل تود تحميله الآن؟' }, smiley : { toolbar : 'ابتسامات', title : 'إدراج ابتسامات', options : 'Smiley Options' // MISSING }, elementsPath : { eleLabel : 'Elements path', // MISSING eleTitle : 'عنصر 1%' }, numberedlist : 'ادخال/حذف تعداد رقمي', bulletedlist : 'ادخال/حذف تعداد نقطي', indent : 'زيادة المسافة البادئة', outdent : 'إنقاص المسافة البادئة', justify : { left : 'محاذاة إلى اليسار', center : 'توسيط', right : 'محاذاة إلى اليمين', block : 'ضبط' }, blockquote : 'اقتباس', clipboard : { title : 'لصق', cutError : 'الإعدادات الأمنية للمتصفح الذي تستخدمه تمنع القص التلقائي. فضلاً إستخدم لوحة المفاتيح لفعل ذلك (Ctrl/Cmd+X).', copyError : 'الإعدادات الأمنية للمتصفح الذي تستخدمه تمنع النسخ التلقائي. فضلاً إستخدم لوحة المفاتيح لفعل ذلك (Ctrl/Cmd+C).', pasteMsg : 'الصق داخل الصندوق بإستخدام زرائر (<STRONG>Ctrl/Cmd+V</STRONG>) في لوحة المفاتيح، ثم اضغط زر <STRONG>موافق</STRONG>.', securityMsg : 'نظراً لإعدادات الأمان الخاصة بمتصفحك، لن يتمكن هذا المحرر من الوصول لمحتوى حافظتك، لذلك يجب عليك لصق المحتوى مرة أخرى في هذه النافذة.', pasteArea : 'Paste Area' // MISSING }, pastefromword : { confirmCleanup : 'يبدو أن النص المراد لصقه منسوخ من برنامج وورد. هل تود تنظيفه قبل الشروع في عملية اللصق؟', toolbar : 'لصق من وورد', title : 'لصق من وورد', error : 'It was not possible to clean up the pasted data due to an internal error' // MISSING }, pasteText : { button : 'لصق كنص بسيط', title : 'لصق كنص بسيط' }, templates : { button : 'القوالب', title : 'قوالب المحتوى', options : 'Template Options', // MISSING insertOption : 'استبدال المحتوى', selectPromptMsg : 'اختر القالب الذي تود وضعه في المحرر', emptyListMsg : '(لم يتم تعريف أي قالب)' }, showBlocks : 'مخطط تفصيلي', stylesCombo : { label : 'أنماط', panelTitle : 'Formatting Styles', // MISSING panelTitle1 : 'أنماط الفقرة', panelTitle2 : 'أنماط مضمنة', panelTitle3 : 'أنماط الكائن' }, format : { label : 'تنسيق', panelTitle : 'تنسيق الفقرة', tag_p : 'عادي', tag_pre : 'منسّق', tag_address : 'عنوان', tag_h1 : 'العنوان 1', tag_h2 : 'العنوان 2', tag_h3 : 'العنوان 3', tag_h4 : 'العنوان 4', tag_h5 : 'العنوان 5', tag_h6 : 'العنوان 6', tag_div : 'عادي (DIV)' }, div : { title : 'Create Div Container', // MISSING toolbar : 'Create Div Container', // MISSING cssClassInputLabel : 'Stylesheet Classes', // MISSING styleSelectLabel : 'Style', // MISSING IdInputLabel : 'Id', // MISSING languageCodeInputLabel : ' Language Code', // MISSING inlineStyleInputLabel : 'Inline Style', // MISSING advisoryTitleInputLabel : 'Advisory Title', // MISSING langDirLabel : 'Language Direction', // MISSING langDirLTRLabel : 'Left to Right (LTR)', // MISSING langDirRTLLabel : 'Right to Left (RTL)', // MISSING edit : 'Edit Div', // MISSING remove : 'Remove Div' // MISSING }, iframe : { title : 'IFrame Properties', // MISSING toolbar : 'IFrame', // MISSING noUrl : 'Please type the iframe URL', // MISSING scrolling : 'Enable scrollbars', // MISSING border : 'Show frame border' // MISSING }, font : { label : 'خط', voiceLabel : 'حجم الخط', panelTitle : 'حجم الخط' }, fontSize : { label : 'حجم الخط', voiceLabel : 'حجم الخط', panelTitle : 'حجم الخط' }, colorButton : { textColorTitle : 'لون النص', bgColorTitle : 'لون الخلفية', panelTitle : 'Colors', // MISSING auto : 'تلقائي', more : 'ألوان إضافية...' }, colors : { '000' : 'أسود', '800000' : 'كستنائي', '8B4513' : 'بني فاتح', '2F4F4F' : 'رمادي أردوازي غامق', '008080' : 'أزرق مخضر', '000080' : 'أزرق داكن', '4B0082' : 'كحلي', '696969' : 'رمادي داكن', 'B22222' : 'طوبي', 'A52A2A' : 'بني', 'DAA520' : 'ذهبي داكن', '006400' : 'أخضر داكن', '40E0D0' : 'فيروزي', '0000CD' : 'أزرق متوسط', '800080' : 'بنفسجي غامق', '808080' : 'رمادي', 'F00' : 'أحمر', 'FF8C00' : 'برتقالي داكن', 'FFD700' : 'ذهبي', '008000' : 'أخضر', '0FF' : 'تركواز', '00F' : 'أزرق', 'EE82EE' : 'بنفسجي', 'A9A9A9' : 'رمادي شاحب', 'FFA07A' : 'برتقالي وردي', 'FFA500' : 'برتقالي', 'FFFF00' : 'أصفر', '00FF00' : 'ليموني', 'AFEEEE' : 'فيروزي شاحب', 'ADD8E6' : 'أزرق فاتح', 'DDA0DD' : 'بنفسجي فاتح', 'D3D3D3' : 'رمادي فاتح', 'FFF0F5' : 'وردي فاتح', 'FAEBD7' : 'أبيض عتيق', 'FFFFE0' : 'أصفر فاتح', 'F0FFF0' : 'أبيض مائل للأخضر', 'F0FFFF' : 'سماوي', 'F0F8FF' : 'لبني', 'E6E6FA' : 'أرجواني', 'FFF' : 'أبيض' }, scayt : { title : 'تدقيق إملائي أثناء الكتابة', opera_title : 'Not supported by Opera', // MISSING enable : 'تفعيل SCAYT', disable : 'تعطيل SCAYT', about : 'عن SCAYT', toggle : 'تثبيت SCAYT', options : 'خيارات', langs : 'لغات', moreSuggestions : 'المزيد من المقترحات', ignore : 'تجاهل', ignoreAll : 'تجاهل الكل', addWord : 'إضافة كلمة', emptyDic : 'اسم القاموس يجب ألا يكون فارغاً.', optionsTab : 'خيارات', allCaps : 'Ignore All-Caps Words', // MISSING ignoreDomainNames : 'Ignore Domain Names', // MISSING mixedCase : 'Ignore Words with Mixed Case', // MISSING mixedWithDigits : 'Ignore Words with Numbers', // MISSING languagesTab : 'لغات', dictionariesTab : 'قواميس', dic_field_name : 'Dictionary name', // MISSING dic_create : 'Create', // MISSING dic_restore : 'Restore', // MISSING dic_delete : 'Delete', // MISSING dic_rename : 'Rename', // MISSING dic_info : 'Initially the User Dictionary is stored in a Cookie. However, Cookies are limited in size. When the User Dictionary grows to a point where it cannot be stored in a Cookie, then the dictionary may be stored on our server. To store your personal dictionary on our server you should specify a name for your dictionary. If you already have a stored dictionary, please type its name and click the Restore button.', // MISSING aboutTab : 'عن' }, about : { title : 'عن CKEditor', dlgTitle : 'عن CKEditor', help : 'Check $1 for help.', // MISSING userGuide : 'CKEditor User\'s Guide', // MISSING moreInfo : 'للحصول على معلومات الترخيص ، يرجى زيارة موقعنا على شبكة الانترنت:', copy : 'حقوق النشر &copy; $1. جميع الحقوق محفوظة.' }, maximize : 'تكبير', minimize : 'تصغير', fakeobjects : { anchor : 'إرساء', flash : 'رسم متحرك بالفلاش', iframe : 'IFrame', // MISSING hiddenfield : 'Hidden Field', // MISSING unknown : 'كائن غير معروف' }, resize : 'اسحب لتغيير الحجم', colordialog : { title : 'اختر لون', options : 'Color Options', // MISSING highlight : 'إلقاء الضوء', selected : 'مُختار', clear : 'مسح' }, toolbarCollapse : 'Collapse Toolbar', // MISSING toolbarExpand : 'Expand Toolbar', // MISSING toolbarGroups : { document : 'Document', // MISSING clipboard : 'Clipboard/Undo', // MISSING editing : 'Editing', // MISSING forms : 'Forms', // MISSING basicstyles : 'Basic Styles', // MISSING paragraph : 'Paragraph', // MISSING links : 'Links', // MISSING insert : 'Insert', // MISSING styles : 'Styles', // MISSING colors : 'Colors', // MISSING tools : 'Tools' // MISSING }, bidi : { ltr : 'Text direction from left to right', // MISSING rtl : 'Text direction from right to left' // MISSING }, docprops : { label : 'خصائص الصفحة', title : 'خصائص الصفحة', design : 'Design', // MISSING meta : 'المعرّفات الرأسية', chooseColor : 'اختر', other : '<أخرى>', docTitle : 'عنوان الصفحة', charset : 'ترميز الحروف', charsetOther : 'ترميز آخر', charsetASCII : 'ASCII', // MISSING charsetCE : 'أوروبا الوسطى', charsetCT : 'الصينية التقليدية (Big5)', charsetCR : 'السيريلية', charsetGR : 'اليونانية', charsetJP : 'اليابانية', charsetKR : 'الكورية', charsetTR : 'التركية', charsetUN : 'Unicode (UTF-8)', // MISSING charsetWE : 'أوروبا الغربية', docType : 'ترويسة نوع الصفحة', docTypeOther : 'ترويسة نوع صفحة أخرى', xhtmlDec : 'تضمين إعلانات لغة XHTMLَ', bgColor : 'لون الخلفية', bgImage : 'رابط الصورة الخلفية', bgFixed : 'جعلها علامة مائية', txtColor : 'لون النص', margin : 'هوامش الصفحة', marginTop : 'علوي', marginLeft : 'أيسر', marginRight : 'أيمن', marginBottom : 'سفلي', metaKeywords : 'الكلمات الأساسية (مفصولة بفواصل)َ', metaDescription : 'وصف الصفحة', metaAuthor : 'الكاتب', metaCopyright : 'المالك', previewHtml : '<p>This is some <strong>sample text</strong>. You are using <a href="javascript:void(0)">CKEditor</a>.</p>' // MISSING } };
import { isPresent } from 'angular2/src/facade/lang'; import { DOM } from 'angular2/src/platform/dom/dom_adapter'; /** * Predicates for use with {@link DebugElement}'s query functions. */ export class By { /** * Match all elements. * * ## Example * * {@example platform/dom/debug/ts/by/by.ts region='by_all'} */ static all() { return (debugElement) => true; } /** * Match elements by the given CSS selector. * * ## Example * * {@example platform/dom/debug/ts/by/by.ts region='by_css'} */ static css(selector) { return (debugElement) => { return isPresent(debugElement.nativeElement) ? DOM.elementMatches(debugElement.nativeElement, selector) : false; }; } /** * Match elements that have the given directive present. * * ## Example * * {@example platform/dom/debug/ts/by/by.ts region='by_directive'} */ static directive(type) { return (debugElement) => { return debugElement.providerTokens.indexOf(type) !== -1; }; } }
import {color} from "d3-color"; import rgb from "./rgb"; import array from "./array"; import date from "./date"; import number from "./number"; import object from "./object"; import string from "./string"; import constant from "./constant"; export default function(a, b) { var t = typeof b, c; return b == null || t === "boolean" ? constant(b) : (t === "number" ? number : t === "string" ? ((c = color(b)) ? (b = c, rgb) : string) : b instanceof color ? rgb : b instanceof Date ? date : Array.isArray(b) ? array : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object : number)(a, b); }
(function(){var e=window.AmCharts;e.AmRectangularChart=e.Class({inherits:e.AmCoordinateChart,construct:function(a){e.AmRectangularChart.base.construct.call(this,a);this.theme=a;this.createEvents("zoomed","changed");this.marginRight=this.marginBottom=this.marginTop=this.marginLeft=20;this.depth3D=this.angle=0;this.plotAreaFillColors="#FFFFFF";this.plotAreaFillAlphas=0;this.plotAreaBorderColor="#000000";this.plotAreaBorderAlpha=0;this.maxZoomFactor=20;this.zoomOutButtonImageSize=19;this.zoomOutButtonImage= "lens";this.zoomOutText="Show all";this.zoomOutButtonColor="#e5e5e5";this.zoomOutButtonAlpha=0;this.zoomOutButtonRollOverAlpha=1;this.zoomOutButtonPadding=8;this.trendLines=[];this.autoMargins=!0;this.marginsUpdated=!1;this.autoMarginOffset=10;e.applyTheme(this,a,"AmRectangularChart")},initChart:function(){e.AmRectangularChart.base.initChart.call(this);this.updateDxy();!this.marginsUpdated&&this.autoMargins&&(this.resetMargins(),this.drawGraphs=!1);this.processScrollbars();this.updateMargins();this.updatePlotArea(); this.updateScrollbars();this.updateTrendLines();this.updateChartCursor();this.updateValueAxes();this.scrollbarOnly||this.updateGraphs()},drawChart:function(){e.AmRectangularChart.base.drawChart.call(this);this.drawPlotArea();if(e.ifArray(this.chartData)){var a=this.chartCursor;a&&a.draw()}},resetMargins:function(){var a={},b;if("xy"==this.type){var c=this.xAxes,d=this.yAxes;for(b=0;b<c.length;b++){var g=c[b];g.ignoreAxisWidth||(g.setOrientation(!0),g.fixAxisPosition(),a[g.position]=!0)}for(b=0;b< d.length;b++)c=d[b],c.ignoreAxisWidth||(c.setOrientation(!1),c.fixAxisPosition(),a[c.position]=!0)}else{d=this.valueAxes;for(b=0;b<d.length;b++)c=d[b],c.ignoreAxisWidth||(c.setOrientation(this.rotate),c.fixAxisPosition(),a[c.position]=!0);(b=this.categoryAxis)&&!b.ignoreAxisWidth&&(b.setOrientation(!this.rotate),b.fixAxisPosition(),b.fixAxisPosition(),a[b.position]=!0)}a.left&&(this.marginLeft=0);a.right&&(this.marginRight=0);a.top&&(this.marginTop=0);a.bottom&&(this.marginBottom=0);this.fixMargins= a},measureMargins:function(){var a=this.valueAxes,b,c=this.autoMarginOffset,d=this.fixMargins,g=this.realWidth,h=this.realHeight,f=c,e=c,k=g;b=h;var m;for(m=0;m<a.length;m++)a[m].handleSynchronization(),b=this.getAxisBounds(a[m],f,k,e,b),f=Math.round(b.l),k=Math.round(b.r),e=Math.round(b.t),b=Math.round(b.b);if(a=this.categoryAxis)b=this.getAxisBounds(a,f,k,e,b),f=Math.round(b.l),k=Math.round(b.r),e=Math.round(b.t),b=Math.round(b.b);d.left&&f<c&&(this.marginLeft=Math.round(-f+c),!isNaN(this.minMarginLeft)&& this.marginLeft<this.minMarginLeft&&(this.marginLeft=this.minMarginLeft));d.right&&k>=g-c&&(this.marginRight=Math.round(k-g+c),!isNaN(this.minMarginRight)&&this.marginRight<this.minMarginRight&&(this.marginRight=this.minMarginRight));d.top&&e<c+this.titleHeight&&(this.marginTop=Math.round(this.marginTop-e+c+this.titleHeight),!isNaN(this.minMarginTop)&&this.marginTop<this.minMarginTop&&(this.marginTop=this.minMarginTop));d.bottom&&b>h-c&&(this.marginBottom=Math.round(this.marginBottom+b-h+c),!isNaN(this.minMarginBottom)&& this.marginBottom<this.minMarginBottom&&(this.marginBottom=this.minMarginBottom));this.initChart()},getAxisBounds:function(a,b,c,d,g){if(!a.ignoreAxisWidth){var h=a.labelsSet,f=a.tickLength;a.inside&&(f=0);if(h)switch(h=a.getBBox(),a.position){case "top":a=h.y;d>a&&(d=a);break;case "bottom":a=h.y+h.height;g<a&&(g=a);break;case "right":a=h.x+h.width+f+3;c<a&&(c=a);break;case "left":a=h.x-f,b>a&&(b=a)}}return{l:b,t:d,r:c,b:g}},drawZoomOutButton:function(){var a=this;if(!a.zbSet){var b=a.container.set(); a.zoomButtonSet.push(b);var c=a.color,d=a.fontSize,g=a.zoomOutButtonImageSize,h=a.zoomOutButtonImage.replace(/\.[a-z]*$/i,""),f=e.lang.zoomOutText||a.zoomOutText,l=a.zoomOutButtonColor,k=a.zoomOutButtonAlpha,m=a.zoomOutButtonFontSize,p=a.zoomOutButtonPadding;isNaN(m)||(d=m);(m=a.zoomOutButtonFontColor)&&(c=m);var m=a.zoomOutButton,n;m&&(m.fontSize&&(d=m.fontSize),m.color&&(c=m.color),m.backgroundColor&&(l=m.backgroundColor),isNaN(m.backgroundAlpha)||(a.zoomOutButtonRollOverAlpha=m.backgroundAlpha)); var r=m=0;void 0!==a.pathToImages&&h&&(n=a.container.image(a.pathToImages+h+a.extension,0,0,g,g),e.setCN(a,n,"zoom-out-image"),b.push(n),n=n.getBBox(),m=n.width+5);void 0!==f&&(c=e.text(a.container,f,c,a.fontFamily,d,"start"),e.setCN(a,c,"zoom-out-label"),d=c.getBBox(),r=n?n.height/2-3:d.height/2,c.translate(m,r),b.push(c));n=b.getBBox();c=1;e.isModern||(c=0);l=e.rect(a.container,n.width+2*p+5,n.height+2*p-2,l,1,1,l,c);l.setAttr("opacity",k);l.translate(-p,-p);e.setCN(a,l,"zoom-out-bg");b.push(l); l.toBack();a.zbBG=l;n=l.getBBox();b.translate(a.marginLeftReal+a.plotAreaWidth-n.width+p,a.marginTopReal+p);b.hide();b.mouseover(function(){a.rollOverZB()}).mouseout(function(){a.rollOutZB()}).click(function(){a.clickZB()}).touchstart(function(){a.rollOverZB()}).touchend(function(){a.rollOutZB();a.clickZB()});for(k=0;k<b.length;k++)b[k].attr({cursor:"pointer"});void 0!==a.zoomOutButtonTabIndex&&(b.setAttr("tabindex",a.zoomOutButtonTabIndex),b.setAttr("role","menuitem"),b.keyup(function(b){13==b.keyCode&& a.clickZB()}));a.zbSet=b}},rollOverZB:function(){this.rolledOverZB=!0;this.zbBG.setAttr("opacity",this.zoomOutButtonRollOverAlpha)},rollOutZB:function(){this.rolledOverZB=!1;this.zbBG.setAttr("opacity",this.zoomOutButtonAlpha)},clickZB:function(){this.rolledOverZB=!1;this.zoomOut()},zoomOut:function(){this.zoomOutValueAxes()},drawPlotArea:function(){var a=this.dx,b=this.dy,c=this.marginLeftReal,d=this.marginTopReal,g=this.plotAreaWidth-1,h=this.plotAreaHeight-1,f=this.plotAreaFillColors,l=this.plotAreaFillAlphas, k=this.plotAreaBorderColor,m=this.plotAreaBorderAlpha;"object"==typeof l&&(l=l[0]);f=e.polygon(this.container,[0,g,g,0,0],[0,0,h,h,0],f,l,1,k,m,this.plotAreaGradientAngle);e.setCN(this,f,"plot-area");f.translate(c+a,d+b);this.set.push(f);0!==a&&0!==b&&(f=this.plotAreaFillColors,"object"==typeof f&&(f=f[0]),f=e.adjustLuminosity(f,-.15),g=e.polygon(this.container,[0,a,g+a,g,0],[0,b,b,0,0],f,l,1,k,m),e.setCN(this,g,"plot-area-bottom"),g.translate(c,d+h),this.set.push(g),a=e.polygon(this.container,[0, 0,a,a,0],[0,h,h+b,b,0],f,l,1,k,m),e.setCN(this,a,"plot-area-left"),a.translate(c,d),this.set.push(a));(c=this.bbset)&&this.scrollbarOnly&&c.remove()},updatePlotArea:function(){var a=this.updateWidth(),b=this.updateHeight(),c=this.container;this.realWidth=a;this.realWidth=b;c&&this.container.setSize(a,b);var c=this.marginLeftReal,d=this.marginTopReal,a=a-c-this.marginRightReal-this.dx,b=b-d-this.marginBottomReal;1>a&&(a=1);1>b&&(b=1);this.plotAreaWidth=Math.round(a);this.plotAreaHeight=Math.round(b); this.plotBalloonsSet.translate(c,d)},updateDxy:function(){this.dx=Math.round(this.depth3D*Math.cos(this.angle*Math.PI/180));this.dy=Math.round(-this.depth3D*Math.sin(this.angle*Math.PI/180));this.d3x=Math.round(this.columnSpacing3D*Math.cos(this.angle*Math.PI/180));this.d3y=Math.round(-this.columnSpacing3D*Math.sin(this.angle*Math.PI/180))},updateMargins:function(){var a=this.getTitleHeight();this.titleHeight=a;this.marginTopReal=this.marginTop-this.dy;this.fixMargins&&!this.fixMargins.top&&(this.marginTopReal+= a);this.marginBottomReal=this.marginBottom;this.marginLeftReal=this.marginLeft;this.marginRightReal=this.marginRight},updateValueAxes:function(){var a=this.valueAxes,b;for(b=0;b<a.length;b++){var c=a[b];this.setAxisRenderers(c);this.updateObjectSize(c)}},setAxisRenderers:function(a){a.axisRenderer=e.RecAxis;a.guideFillRenderer=e.RecFill;a.axisItemRenderer=e.RecItem;a.marginsChanged=!0},updateGraphs:function(){var a=this.graphs,b;for(b=0;b<a.length;b++){var c=a[b];c.index=b;c.rotate=this.rotate;this.updateObjectSize(c)}}, updateObjectSize:function(a){a.width=this.plotAreaWidth-1;a.height=this.plotAreaHeight-1;a.x=this.marginLeftReal;a.y=this.marginTopReal;a.dx=this.dx;a.dy=this.dy},updateChartCursor:function(){var a=this.chartCursor;a&&(a=e.processObject(a,e.ChartCursor,this.theme),this.updateObjectSize(a),this.addChartCursor(a),a.chart=this)},processScrollbars:function(){var a=this.chartScrollbar;a&&(a=e.processObject(a,e.ChartScrollbar,this.theme),this.addChartScrollbar(a))},updateScrollbars:function(){},removeChartCursor:function(){e.callMethod("destroy", [this.chartCursor]);this.chartCursor=null},zoomTrendLines:function(){var a=this.trendLines,b;for(b=0;b<a.length;b++){var c=a[b];c.valueAxis.recalculateToPercents?c.set&&c.set.hide():(c.x=this.marginLeftReal,c.y=this.marginTopReal,c.draw())}},handleCursorValueZoom:function(){},addTrendLine:function(a){this.trendLines.push(a)},zoomOutValueAxes:function(){for(var a=this.valueAxes,b=0;b<a.length;b++)a[b].zoomOut()},removeTrendLine:function(a){var b=this.trendLines,c;for(c=b.length-1;0<=c;c--)b[c]==a&& b.splice(c,1)},adjustMargins:function(a,b){var c=a.position,d=a.scrollbarHeight+a.offset;a.enabled&&("top"==c?b?this.marginLeftReal+=d:this.marginTopReal+=d:b?this.marginRightReal+=d:this.marginBottomReal+=d)},getScrollbarPosition:function(a,b,c){var d="bottom",g="top";a.oppositeAxis||(g=d,d="top");a.position=b?"bottom"==c||"left"==c?d:g:"top"==c||"right"==c?d:g},updateChartScrollbar:function(a,b){if(a){a.rotate=b;var c=this.marginTopReal,d=this.marginLeftReal,g=a.scrollbarHeight,h=this.dx,f=this.dy, e=a.offset;"top"==a.position?b?(a.y=c,a.x=d-g-e):(a.y=c-g+f-e,a.x=d+h):b?(a.y=c+f,a.x=d+this.plotAreaWidth+h+e):(a.y=c+this.plotAreaHeight+e,a.x=this.marginLeftReal)}},showZB:function(a){var b=this.zbSet;a&&(b=this.zoomOutText,""!==b&&b&&this.drawZoomOutButton());if(b=this.zbSet)this.zoomButtonSet.push(b),a?b.show():b.hide(),this.rollOutZB()},handleReleaseOutside:function(a){e.AmRectangularChart.base.handleReleaseOutside.call(this,a);(a=this.chartCursor)&&a.handleReleaseOutside&&a.handleReleaseOutside()}, handleMouseDown:function(a){e.AmRectangularChart.base.handleMouseDown.call(this,a);var b=this.chartCursor;b&&b.handleMouseDown&&!this.rolledOverZB&&b.handleMouseDown(a)},update:function(){e.AmRectangularChart.base.update.call(this);this.chartCursor&&this.chartCursor.update&&this.chartCursor.update()},handleScrollbarValueZoom:function(a){this.relativeZoomValueAxes(a.target.valueAxes,a.relativeStart,a.relativeEnd);this.zoomAxesAndGraphs()},zoomValueScrollbar:function(a){if(a&&a.enabled){var b=a.valueAxes[0], c=b.relativeStart,d=b.relativeEnd;b.reversed&&(d=1-c,c=1-b.relativeEnd);a.percentZoom(c,d)}},zoomAxesAndGraphs:function(){if(!this.scrollbarOnly){var a=this.valueAxes,b;for(b=0;b<a.length;b++)a[b].zoom(this.start,this.end);a=this.graphs;for(b=0;b<a.length;b++)a[b].zoom(this.start,this.end);(b=this.chartCursor)&&b.clearSelection();this.zoomTrendLines()}},handleValueAxisZoomReal:function(a,b){var c=a.relativeStart,d=a.relativeEnd;if(c>d)var g=c,c=d,d=g;this.relativeZoomValueAxes(b,c,d);this.updateAfterValueZoom()}, updateAfterValueZoom:function(){this.zoomAxesAndGraphs();this.zoomScrollbar()},relativeZoomValueAxes:function(a,b,c){b=e.fitToBounds(b,0,1);c=e.fitToBounds(c,0,1);if(b>c){var d=b;b=c;c=d}var d=1/this.maxZoomFactor,g=e.getDecimals(d)+4;c-b<d&&(c=b+(c-b)/2,b=c-d/2,c+=d/2);b=e.roundTo(b,g);c=e.roundTo(c,g);d=!1;if(a){for(g=0;g<a.length;g++){var h=a[g].zoomToRelativeValues(b,c,!0);h&&(d=h)}this.showZB()}return d},addChartCursor:function(a){e.callMethod("destroy",[this.chartCursor]);a&&(this.listenTo(a, "moved",this.handleCursorMove),this.listenTo(a,"zoomed",this.handleCursorZoom),this.listenTo(a,"zoomStarted",this.handleCursorZoomStarted),this.listenTo(a,"panning",this.handleCursorPanning),this.listenTo(a,"onHideCursor",this.handleCursorHide));this.chartCursor=a},handleCursorChange:function(){},handleCursorMove:function(a){var b,c=this.valueAxes;for(b=0;b<c.length;b++)a.panning||c[b].showBalloon(a.x,a.y)},handleCursorZoom:function(a){if(this.skipZoomed)this.skipZoomed=!1;else{var b=this.startX0, c=this.endX0,d=this.endY0,g=this.startY0,h=a.startX,f=a.endX,e=a.startY,k=a.endY;this.startX0=this.endX0=this.startY0=this.endY0=NaN;this.handleCursorZoomReal(b+h*(c-b),b+f*(c-b),g+e*(d-g),g+k*(d-g),a)}},handleCursorHide:function(){var a,b=this.valueAxes;for(a=0;a<b.length;a++)b[a].hideBalloon();b=this.graphs;for(a=0;a<b.length;a++)b[a].hideBalloonReal()}})})();(function(){var e=window.AmCharts;e.AmSerialChart=e.Class({inherits:e.AmRectangularChart,construct:function(a){this.type="serial";e.AmSerialChart.base.construct.call(this,a);this.cname="AmSerialChart";this.theme=a;this.columnSpacing=5;this.columnSpacing3D=0;this.columnWidth=.8;var b=new e.CategoryAxis(a);b.chart=this;this.categoryAxis=b;this.zoomOutOnDataUpdate=!0;this.mouseWheelZoomEnabled=this.mouseWheelScrollEnabled=this.rotate=this.skipZoom=!1;this.minSelectedTime=0;e.applyTheme(this,a,this.cname)}, initChart:function(){e.AmSerialChart.base.initChart.call(this);this.updateCategoryAxis(this.categoryAxis,this.rotate,"categoryAxis");if(this.dataChanged)this.parseData();else this.onDataUpdated();this.drawGraphs=!0},onDataUpdated:function(){var a=this.countColumns(),b=this.chartData,c=this.graphs,d;for(d=0;d<c.length;d++){var g=c[d];g.data=b;g.columnCount=a}0<b.length&&(this.firstTime=this.getStartTime(b[0].time),this.lastTime=this.getEndTime(b[b.length-1].time));this.drawChart();this.autoMargins&& !this.marginsUpdated?(this.marginsUpdated=!0,this.measureMargins()):this.dispDUpd()},syncGrid:function(){if(this.synchronizeGrid){var a=this.valueAxes,b,c;if(0<a.length){var d=0;for(c=0;c<a.length;c++)b=a[c],d<b.gridCountReal&&(d=b.gridCountReal);var g=!1;for(c=0;c<a.length;c++)if(b=a[c],b.gridCountReal<d){var h=g=(d-b.gridCountReal)/2,f=g;0!==g-Math.round(g)&&(h-=.5,f+=.5);b.minimum=b.min-h*b.step;b.maximum=b.max+f*b.step;b.setStep=b.step;g=!0}g&&this.updateAfterValueZoom();for(c=0;c<a.length;c++)b= a[c],b.minimum=NaN,b.maximum=NaN,b.setStep=NaN}}},handleWheelReal:function(a,b){if(!this.wheelBusy){var c=this.categoryAxis,d=c.parseDates,g=c.minDuration(),h=1,f=1;this.mouseWheelZoomEnabled?b||(h=-1):b&&(h=-1);var e=this.chartCursor;if(e){var k=e.mouseX,e=e.mouseY;h!=f&&(k=this.rotate?e/this.plotAreaHeight:k/this.plotAreaWidth,h*=k,f*=1-k);k=.05*(this.end-this.start);1>k&&(k=1);h*=k;f*=k;if(!d||c.equalSpacing)h=Math.round(h),f=Math.round(f)}e=this.chartData.length;c=this.lastTime;k=this.firstTime; 0>a?d?(e=this.endTime-this.startTime,d=this.startTime+h*g,g=this.endTime+f*g,0<f&&0<h&&g>=c&&(g=c,d=c-e),this.zoomToDates(new Date(d),new Date(g))):(0<f&&0<h&&this.end>=e-1&&(h=f=0),d=this.start+h,g=this.end+f,this.zoomToIndexes(d,g)):d?(e=this.endTime-this.startTime,d=this.startTime-h*g,g=this.endTime-f*g,0<f&&0<h&&d<=k&&(d=k,g=k+e),this.zoomToDates(new Date(d),new Date(g))):(0<f&&0<h&&1>this.start&&(h=f=0),d=this.start-h,g=this.end-f,this.zoomToIndexes(d,g))}},validateData:function(a){this.marginsUpdated= !1;this.zoomOutOnDataUpdate&&!a&&(this.endTime=this.end=this.startTime=this.start=NaN);e.AmSerialChart.base.validateData.call(this)},drawChart:function(){if(0<this.realWidth&&0<this.realHeight){e.AmSerialChart.base.drawChart.call(this);var a=this.chartData;if(e.ifArray(a)){var b=this.chartScrollbar;!b||!this.marginsUpdated&&this.autoMargins||b.draw();(b=this.valueScrollbar)&&b.draw();var a=a.length-1,c,b=this.categoryAxis;if(b.parseDates&&!b.equalSpacing){if(b=this.startTime,c=this.endTime,isNaN(b)|| isNaN(c))b=this.firstTime,c=this.lastTime}else if(b=this.start,c=this.end,isNaN(b)||isNaN(c))b=0,c=a;this.endTime=this.startTime=this.end=this.start=void 0;this.zoom(b,c)}}else this.cleanChart()},cleanChart:function(){e.callMethod("destroy",[this.valueAxes,this.graphs,this.categoryAxis,this.chartScrollbar,this.chartCursor,this.valueScrollbar])},updateCategoryAxis:function(a,b,c){a.chart=this;a.id=c;a.rotate=b;a.setOrientation(!this.rotate);a.init();this.setAxisRenderers(a);this.updateObjectSize(a)}, updateValueAxes:function(){e.AmSerialChart.base.updateValueAxes.call(this);var a=this.valueAxes,b;for(b=0;b<a.length;b++){var c=a[b],d=this.rotate;c.rotate=d;c.setOrientation(d);d=this.categoryAxis;if(!d.startOnAxis||d.parseDates)c.expandMinMax=!0}},getStartTime:function(a){var b=this.categoryAxis;return e.resetDateToMin(new Date(a),b.minPeriod,1,b.firstDayOfWeek).getTime()},getEndTime:function(a){var b=e.extractPeriod(this.categoryAxis.minPeriod);return e.changeDate(new Date(a),b.period,b.count, !0).getTime()-1},updateMargins:function(){e.AmSerialChart.base.updateMargins.call(this);var a=this.chartScrollbar;a&&(this.getScrollbarPosition(a,this.rotate,this.categoryAxis.position),this.adjustMargins(a,this.rotate));if(a=this.valueScrollbar)this.getScrollbarPosition(a,!this.rotate,this.valueAxes[0].position),this.adjustMargins(a,!this.rotate)},updateScrollbars:function(){e.AmSerialChart.base.updateScrollbars.call(this);this.updateChartScrollbar(this.chartScrollbar,this.rotate);this.updateChartScrollbar(this.valueScrollbar, !this.rotate)},zoom:function(a,b){var c=this.categoryAxis;c.parseDates&&!c.equalSpacing?this.timeZoom(a,b):this.indexZoom(a,b);isNaN(a)&&this.zoomOutValueAxes();(c=this.chartCursor)&&(c.pan||c.hideCursorReal());this.updateLegendValues()},timeZoom:function(a,b){var c=this.maxSelectedTime;isNaN(c)||(b!=this.endTime&&b-a>c&&(a=b-c),a!=this.startTime&&b-a>c&&(b=a+c));var d=this.minSelectedTime;if(0<d&&b-a<d){var g=Math.round(a+(b-a)/2),d=Math.round(d/2);a=g-d;b=g+d}d=this.chartData;g=this.categoryAxis; if(e.ifArray(d)&&(a!=this.startTime||b!=this.endTime)){var h=g.minDuration(),f=this.firstTime,l=this.lastTime;a||(a=f,isNaN(c)||(a=l-c));b||(b=l);a>l&&(a=l);b<f&&(b=f);a<f&&(a=f);b>l&&(b=l);b<a&&(b=a+h);b-a<h/5&&(b<l?b=a+h/5:a=b-h/5);this.startTime=a;this.endTime=b;c=d.length-1;h=this.getClosestIndex(d,"time",a,!0,0,c);d=this.getClosestIndex(d,"time",b,!1,h,c);g.timeZoom(a,b);g.zoom(h,d);this.start=e.fitToBounds(h,0,c);this.end=e.fitToBounds(d,0,c);this.zoomAxesAndGraphs();this.zoomScrollbar();this.fixCursor(); this.showZB();this.syncGrid();this.updateColumnsDepth();this.dispatchTimeZoomEvent()}},showZB:function(){var a,b=this.categoryAxis;b&&b.parseDates&&!b.equalSpacing&&(this.startTime>this.firstTime&&(a=!0),this.endTime<this.lastTime&&(a=!0));0<this.start&&(a=!0);this.end<this.chartData.length-1&&(a=!0);if(b=this.valueAxes)b=b[0],0!==b.relativeStart&&(a=!0),1!=b.relativeEnd&&(a=!0);e.AmSerialChart.base.showZB.call(this,a)},updateAfterValueZoom:function(){e.AmSerialChart.base.updateAfterValueZoom.call(this); this.updateColumnsDepth()},indexZoom:function(a,b){var c=this.maxSelectedSeries;isNaN(c)||(b!=this.end&&b-a>c&&(a=b-c),a!=this.start&&b-a>c&&(b=a+c));if(a!=this.start||b!=this.end){var d=this.chartData.length-1;isNaN(a)&&(a=0,isNaN(c)||(a=d-c));isNaN(b)&&(b=d);b<a&&(b=a);b>d&&(b=d);a>d&&(a=d-1);0>a&&(a=0);this.start=a;this.end=b;this.categoryAxis.zoom(a,b);this.zoomAxesAndGraphs();this.zoomScrollbar();this.fixCursor();0!==a||b!=this.chartData.length-1?this.showZB(!0):this.showZB(!1);this.syncGrid(); this.updateColumnsDepth();this.dispatchIndexZoomEvent()}},updateGraphs:function(){e.AmSerialChart.base.updateGraphs.call(this);var a=this.graphs,b;for(b=0;b<a.length;b++){var c=a[b];c.columnWidthReal=this.columnWidth;c.categoryAxis=this.categoryAxis;e.isString(c.fillToGraph)&&(c.fillToGraph=this.graphsById[c.fillToGraph])}},zoomAxesAndGraphs:function(){e.AmSerialChart.base.zoomAxesAndGraphs.call(this);this.updateColumnsDepth()},updateColumnsDepth:function(){if(0!==this.depth3D||0!==this.angle){var a, b=this.graphs,c;this.columnsArray=[];for(a=0;a<b.length;a++){c=b[a];var d=c.columnsArray;if(d){var g;for(g=0;g<d.length;g++)this.columnsArray.push(d[g])}}this.columnsArray.sort(this.compareDepth);if(0<this.columnsArray.length){b=this.columnsSet;d=this.container.set();this.columnSet.push(d);for(a=0;a<this.columnsArray.length;a++)d.push(this.columnsArray[a].column.set);c&&d.translate(c.x,c.y);this.columnsSet=d;e.remove(b)}}},compareDepth:function(a,b){return a.depth>b.depth?1:-1},zoomScrollbar:function(){var a= this.chartScrollbar,b=this.categoryAxis;if(a){if(!this.zoomedByScrollbar){var c=a.dragger;c&&c.stop()}this.zoomedByScrollbar=!1;b.parseDates&&!b.equalSpacing?a.timeZoom(this.startTime,this.endTime):a.zoom(this.start,this.end)}this.zoomValueScrollbar(this.valueScrollbar)},updateTrendLines:function(){var a=this.trendLines,b;for(b=0;b<a.length;b++){var c=a[b],c=e.processObject(c,e.TrendLine,this.theme);a[b]=c;c.chart=this;c.id||(c.id="trendLineAuto"+b+"_"+(new Date).getTime());e.isString(c.valueAxis)&& (c.valueAxis=this.getValueAxisById(c.valueAxis));c.valueAxis||(c.valueAxis=this.valueAxes[0]);c.categoryAxis=this.categoryAxis}},countColumns:function(){var a=0,b=this.valueAxes.length,c=this.graphs.length,d,g,e=!1,f,l;for(l=0;l<b;l++){g=this.valueAxes[l];var k=g.stackType;if("100%"==k||"regular"==k)for(e=!1,f=0;f<c;f++)d=this.graphs[f],d.tcc=1,d.valueAxis==g&&"column"==d.type&&(!e&&d.stackable&&(a++,e=!0),(!d.stackable&&d.clustered||d.newStack)&&a++,d.columnIndex=a-1,d.clustered||(d.columnIndex= 0));if("none"==k||"3d"==k){e=!1;for(f=0;f<c;f++)d=this.graphs[f],d.valueAxis==g&&"column"==d.type&&(d.clustered?(d.tcc=1,d.newStack&&(a=0),d.hidden||(d.columnIndex=a,a++)):d.hidden||(e=!0,d.tcc=1,d.columnIndex=0));e&&0===a&&(a=1)}if("3d"==k){g=1;for(l=0;l<c;l++)d=this.graphs[l],d.newStack&&g++,d.depthCount=g,d.tcc=a;a=g}}return a},parseData:function(){e.AmSerialChart.base.parseData.call(this);this.parseSerialData(this.dataProvider)},getCategoryIndexByValue:function(a){var b=this.chartData,c;for(c= 0;c<b.length;c++)if(b[c].category==a)return c},handleScrollbarZoom:function(a){this.zoomedByScrollbar=!0;this.zoom(a.start,a.end)},dispatchTimeZoomEvent:function(){if(this.drawGraphs&&(this.prevStartTime!=this.startTime||this.prevEndTime!=this.endTime)){var a={type:"zoomed"};a.startDate=new Date(this.startTime);a.endDate=new Date(this.endTime);a.startIndex=this.start;a.endIndex=this.end;this.startIndex=this.start;this.endIndex=this.end;this.startDate=a.startDate;this.endDate=a.endDate;this.prevStartTime= this.startTime;this.prevEndTime=this.endTime;var b=this.categoryAxis,c=e.extractPeriod(b.minPeriod).period,b=b.dateFormatsObject[c];a.startValue=e.formatDate(a.startDate,b,this);a.endValue=e.formatDate(a.endDate,b,this);a.chart=this;a.target=this;this.fire(a)}},dispatchIndexZoomEvent:function(){if(this.drawGraphs&&(this.prevStartIndex!=this.start||this.prevEndIndex!=this.end)){this.startIndex=this.start;this.endIndex=this.end;var a=this.chartData;if(e.ifArray(a)&&!isNaN(this.start)&&!isNaN(this.end)){var b= {chart:this,target:this,type:"zoomed"};b.startIndex=this.start;b.endIndex=this.end;b.startValue=a[this.start].category;b.endValue=a[this.end].category;this.categoryAxis.parseDates&&(this.startTime=a[this.start].time,this.endTime=a[this.end].time,b.startDate=new Date(this.startTime),b.endDate=new Date(this.endTime));this.prevStartIndex=this.start;this.prevEndIndex=this.end;this.fire(b)}}},updateLegendValues:function(){this.legend&&this.legend.updateValues()},getClosestIndex:function(a,b,c,d,g,e){0> g&&(g=0);e>a.length-1&&(e=a.length-1);var f=g+Math.round((e-g)/2),l=a[f][b];return c==l?f:1>=e-g?d?g:Math.abs(a[g][b]-c)<Math.abs(a[e][b]-c)?g:e:c==l?f:c<l?this.getClosestIndex(a,b,c,d,g,f):this.getClosestIndex(a,b,c,d,f,e)},zoomToIndexes:function(a,b){var c=this.chartData;if(c){var d=c.length;0<d&&(0>a&&(a=0),b>d-1&&(b=d-1),d=this.categoryAxis,d.parseDates&&!d.equalSpacing?this.zoom(c[a].time,this.getEndTime(c[b].time)):this.zoom(a,b))}},zoomToDates:function(a,b){var c=this.chartData;if(c)if(this.categoryAxis.equalSpacing){var d= this.getClosestIndex(c,"time",a.getTime(),!0,0,c.length);b=e.resetDateToMin(b,this.categoryAxis.minPeriod,1);c=this.getClosestIndex(c,"time",b.getTime(),!1,0,c.length);this.zoom(d,c)}else this.zoom(a.getTime(),b.getTime())},zoomToCategoryValues:function(a,b){this.chartData&&this.zoom(this.getCategoryIndexByValue(a),this.getCategoryIndexByValue(b))},formatPeriodString:function(a,b){if(b){var c=["value","open","low","high","close"],d="value open low high close average sum count".split(" "),g=b.valueAxis, h=this.chartData,f=b.numberFormatter;f||(f=this.nf);for(var l=0;l<c.length;l++){for(var k=c[l],m=0,p=0,n,r,w,z,u,q=0,D=0,v,t,x,B,A,G=this.start;G<=this.end;G++){var y=h[G];if(y&&(y=y.axes[g.id].graphs[b.id])){if(y.values){var C=y.values[k];if(this.rotate){if(0>y.x||y.x>y.graph.height)C=NaN}else if(0>y.x||y.x>y.graph.width)C=NaN;if(!isNaN(C)){isNaN(n)&&(n=C);r=C;if(isNaN(w)||w>C)w=C;if(isNaN(z)||z<C)z=C;u=e.getDecimals(m);var F=e.getDecimals(C),m=m+C,m=e.roundTo(m,Math.max(u,F));p++;u=m/p}}if(y.percents&& (y=y.percents[k],!isNaN(y))){isNaN(v)&&(v=y);t=y;if(isNaN(x)||x>y)x=y;if(isNaN(B)||B<y)B=y;A=e.getDecimals(q);C=e.getDecimals(y);q+=y;q=e.roundTo(q,Math.max(A,C));D++;A=q/D}}}q={open:v,close:t,high:B,low:x,average:A,sum:q,count:D};a=e.formatValue(a,{open:n,close:r,high:z,low:w,average:u,sum:m,count:p},d,f,k+"\\.",this.usePrefixes,this.prefixesOfSmallNumbers,this.prefixesOfBigNumbers);a=e.formatValue(a,q,d,this.pf,"percents\\."+k+"\\.")}}return a=e.cleanFromEmpty(a)},formatString:function(a,b,c){if(b){var d= b.graph;if(void 0!==a){if(-1!=a.indexOf("[[category]]")){var g=b.serialDataItem.category;if(this.categoryAxis.parseDates){var h=this.balloonDateFormat,f=this.chartCursor;f&&f.categoryBalloonDateFormat&&(h=f.categoryBalloonDateFormat);h=e.formatDate(g,h,this);-1!=h.indexOf("fff")&&(h=e.formatMilliseconds(h,g));g=h}a=a.replace(/\[\[category\]\]/g,String(g))}g=d.numberFormatter;g||(g=this.nf);h=b.graph.valueAxis;(f=h.duration)&&!isNaN(b.values.value)&&(f=e.formatDuration(b.values.value,f,"",h.durationUnits, h.maxInterval,g),a=a.replace(RegExp("\\[\\[value\\]\\]","g"),f));"date"==h.type&&(h=e.formatDate(new Date(b.values.value),d.dateFormat,this),f=RegExp("\\[\\[value\\]\\]","g"),a=a.replace(f,h),h=e.formatDate(new Date(b.values.open),d.dateFormat,this),f=RegExp("\\[\\[open\\]\\]","g"),a=a.replace(f,h));d="value open low high close total".split(" ");h=this.pf;a=e.formatValue(a,b.percents,d,h,"percents\\.");a=e.formatValue(a,b.values,d,g,"",this.usePrefixes,this.prefixesOfSmallNumbers,this.prefixesOfBigNumbers); a=e.formatValue(a,b.values,["percents"],h);-1!=a.indexOf("[[")&&(a=e.formatDataContextValue(a,b.dataContext));-1!=a.indexOf("[[")&&b.graph.customData&&(a=e.formatDataContextValue(a,b.graph.customData));a=e.AmSerialChart.base.formatString.call(this,a,b,c)}return a}},updateChartCursor:function(){e.AmSerialChart.base.updateChartCursor.call(this);var a=this.chartCursor,b=this.categoryAxis;if(a){var c=a.categoryBalloonAlpha,d=a.categoryBalloonColor,g=a.color;void 0===d&&(d=a.cursorColor);var h=a.valueZoomable, f=a.zoomable,l=a.valueLineEnabled;this.rotate?(a.vLineEnabled=l,a.hZoomEnabled=h,a.vZoomEnabled=f):(a.hLineEnabled=l,a.vZoomEnabled=h,a.hZoomEnabled=f);if(a.valueLineBalloonEnabled)for(l=0;l<this.valueAxes.length;l++)h=this.valueAxes[l],(f=h.balloon)||(f={}),f=e.extend(f,this.balloon,!0),f.fillColor=d,f.balloonColor=d,f.fillAlpha=c,f.borderColor=d,f.color=g,h.balloon=f;else for(f=0;f<this.valueAxes.length;f++)h=this.valueAxes[f],h.balloon&&(h.balloon=null);b&&(b.balloonTextFunction=a.categoryBalloonFunction, a.categoryLineAxis=b,b.balloonText=a.categoryBalloonText,a.categoryBalloonEnabled&&((f=b.balloon)||(f={}),f=e.extend(f,this.balloon,!0),f.fillColor=d,f.balloonColor=d,f.fillAlpha=c,f.borderColor=d,f.color=g,b.balloon=f),b.balloon&&(b.balloon.enabled=a.categoryBalloonEnabled))}},addChartScrollbar:function(a){e.callMethod("destroy",[this.chartScrollbar]);a&&(a.chart=this,this.listenTo(a,"zoomed",this.handleScrollbarZoom));this.rotate?void 0===a.width&&(a.width=a.scrollbarHeight):void 0===a.height&& (a.height=a.scrollbarHeight);a.gridAxis=this.categoryAxis;this.chartScrollbar=a},addValueScrollbar:function(a){e.callMethod("destroy",[this.valueScrollbar]);a&&(a.chart=this,this.listenTo(a,"zoomed",this.handleScrollbarValueZoom),this.listenTo(a,"zoomStarted",this.handleCursorZoomStarted));var b=a.scrollbarHeight;this.rotate?void 0===a.height&&(a.height=b):void 0===a.width&&(a.width=b);a.gridAxis||(a.gridAxis=this.valueAxes[0]);a.valueAxes=this.valueAxes;this.valueScrollbar=a},removeChartScrollbar:function(){e.callMethod("destroy", [this.chartScrollbar]);this.chartScrollbar=null},removeValueScrollbar:function(){e.callMethod("destroy",[this.valueScrollbar]);this.valueScrollbar=null},handleReleaseOutside:function(a){e.AmSerialChart.base.handleReleaseOutside.call(this,a);e.callMethod("handleReleaseOutside",[this.chartScrollbar,this.valueScrollbar])},update:function(){e.AmSerialChart.base.update.call(this);this.chartScrollbar&&this.chartScrollbar.update&&this.chartScrollbar.update();this.valueScrollbar&&this.valueScrollbar.update&& this.valueScrollbar.update()},processScrollbars:function(){e.AmSerialChart.base.processScrollbars.call(this);var a=this.valueScrollbar;a&&(a=e.processObject(a,e.ChartScrollbar,this.theme),a.id="valueScrollbar",this.addValueScrollbar(a))},handleValueAxisZoom:function(a){this.handleValueAxisZoomReal(a,this.valueAxes)},zoomOut:function(){e.AmSerialChart.base.zoomOut.call(this);this.zoom()},getNextItem:function(a){var b=a.index,c=this.chartData,d=a.graph;if(b+1<c.length)for(b+=1;b<c.length;b++)if(a=c[b])if(a= a.axes[d.valueAxis.id].graphs[d.id],!isNaN(a.y))return a},handleCursorZoomReal:function(a,b,c,d,e){var h=e.target,f,l;this.rotate?(isNaN(a)||isNaN(b)||this.relativeZoomValueAxes(this.valueAxes,a,b)&&this.updateAfterValueZoom(),h.vZoomEnabled&&(f=e.start,l=e.end)):(isNaN(c)||isNaN(d)||this.relativeZoomValueAxes(this.valueAxes,c,d)&&this.updateAfterValueZoom(),h.hZoomEnabled&&(f=e.start,l=e.end));isNaN(f)||isNaN(l)||(a=this.categoryAxis,a.parseDates&&!a.equalSpacing?this.zoomToDates(new Date(f),new Date(l)): this.zoomToIndexes(f,l))},handleCursorZoomStarted:function(){var a=this.valueAxes;if(a){var a=a[0],b=a.relativeStart,c=a.relativeEnd;a.reversed&&(b=1-a.relativeEnd,c=1-a.relativeStart);this.rotate?(this.startX0=b,this.endX0=c):(this.startY0=b,this.endY0=c)}this.categoryAxis&&(this.start0=this.start,this.end0=this.end,this.startTime0=this.startTime,this.endTime0=this.endTime)},fixCursor:function(){this.chartCursor&&this.chartCursor.fixPosition();this.prevCursorItem=null},handleCursorMove:function(a){e.AmSerialChart.base.handleCursorMove.call(this, a);var b=a.target,c=this.categoryAxis;if(a.panning)this.handleCursorHide(a);else if(this.chartData&&!b.isHidden){var d=this.graphs;if(d){var g;g=c.xToIndex(this.rotate?a.y:a.x);if(g=this.chartData[g]){var h,f,l,k;if(b.oneBalloonOnly&&b.valueBalloonsEnabled){var m=Infinity;for(h=0;h<d.length;h++)if(f=d[h],f.balloon.enabled&&f.showBalloon&&!f.hidden){l=f.valueAxis.id;l=g.axes[l].graphs[f.id];l=l.y;"top"==f.showBalloonAt&&(l=0);"bottom"==f.showBalloonAt&&(l=this.height);var p=b.mouseX,n=b.mouseY;l=this.rotate? Math.abs(p-l):Math.abs(n-l);l<m&&(m=l,k=f)}b.mostCloseGraph=k}if(this.prevCursorItem!=g||k!=this.prevMostCloseGraph){m=[];for(h=0;h<d.length;h++)f=d[h],l=f.valueAxis.id,l=g.axes[l].graphs[f.id],b.showNextAvailable&&isNaN(l.y)&&(l=this.getNextItem(l)),k&&f!=k?(f.showGraphBalloon(l,b.pointer,!1,b.graphBulletSize,b.graphBulletAlpha),f.balloon.hide(0)):b.valueBalloonsEnabled?(f.balloon.showBullet=b.bulletsEnabled,f.balloon.bulletSize=b.bulletSize/2,a.hideBalloons||(f.showGraphBalloon(l,b.pointer,!1,b.graphBulletSize, b.graphBulletAlpha),f.balloon.set&&m.push({balloon:f.balloon,y:f.balloon.pointToY}))):(f.currentDataItem=l,f.resizeBullet(l,b.graphBulletSize,b.graphBulletAlpha));b.avoidBalloonOverlapping&&this.arrangeBalloons(m);this.prevCursorItem=g}this.prevMostCloseGraph=k}}c.showBalloon(a.x,a.y,b.categoryBalloonDateFormat,a.skip);this.updateLegendValues()}},handleCursorHide:function(a){e.AmSerialChart.base.handleCursorHide.call(this,a);a=this.categoryAxis;this.prevCursorItem=null;this.updateLegendValues();a&& a.hideBalloon();a=this.graphs;var b;for(b=0;b<a.length;b++)a[b].currentDataItem=null},handleCursorPanning:function(a){var b=a.target,c,d=a.deltaX,g=a.deltaY,h=a.delta2X,f=a.delta2Y;a=!1;if(this.rotate){isNaN(h)&&(h=d,a=!0);var l=this.endX0;c=this.startX0;var k=l-c,l=l-k*h,m=k;a||(m=0);a=e.fitToBounds(c-k*d,0,1-m)}else isNaN(f)&&(f=g,a=!0),l=this.endY0,c=this.startY0,k=l-c,l+=k*g,m=k,a||(m=0),a=e.fitToBounds(c+k*f,0,1-m);c=e.fitToBounds(l,m,1);var p;b.valueZoomable&&(p=this.relativeZoomValueAxes(this.valueAxes, a,c));var n;c=this.categoryAxis;this.rotate&&(d=g,h=f);a=!1;isNaN(h)&&(h=d,a=!0);if(b.zoomable&&(0<Math.abs(d)||0<Math.abs(h)))if(c.parseDates&&!c.equalSpacing){if(f=this.startTime0,g=this.endTime0,c=g-f,h*=c,k=this.firstTime,l=this.lastTime,m=c,a||(m=0),a=Math.round(e.fitToBounds(f-c*d,k,l-m)),h=Math.round(e.fitToBounds(g-h,k+m,l)),this.startTime!=a||this.endTime!=h)n={chart:this,target:b,type:"zoomed",start:a,end:h},this.skipZoomed=!0,b.fire(n),this.zoom(a,h),n=!0}else if(f=this.start0,g=this.end0, c=g-f,d=Math.round(c*d),h=Math.round(c*h),k=this.chartData.length-1,a||(c=0),a=e.fitToBounds(f-d,0,k-c),c=e.fitToBounds(g-h,c,k),this.start!=a||this.end!=c)this.skipZoomed=!0,b.fire({chart:this,target:b,type:"zoomed",start:a,end:c}),this.zoom(a,c),n=!0;!n&&p&&this.updateAfterValueZoom()},arrangeBalloons:function(a){var b=this.plotAreaHeight;a.sort(this.compareY);var c,d,e,h=this.plotAreaWidth,f=a.length;for(c=0;c<f;c++)d=a[c].balloon,d.setBounds(0,0,h,b),d.restorePrevious(),d.draw(),b=d.yPos-3;a.reverse(); for(c=0;c<f;c++){d=a[c].balloon;var b=d.bottom,l=d.bottom-d.yPos;0<c&&b-l<e+3&&(d.setBounds(0,e+3,h,e+l+3),d.restorePrevious(),d.draw());d.set&&d.set.show();e=d.bottom}},compareY:function(a,b){return a.y<b.y?1:-1}})})();(function(){var e=window.AmCharts;e.Cuboid=e.Class({construct:function(a,b,c,d,e,h,f,l,k,m,p,n,r,w,z,u,q){this.set=a.set();this.container=a;this.h=Math.round(c);this.w=Math.round(b);this.dx=d;this.dy=e;this.colors=h;this.alpha=f;this.bwidth=l;this.bcolor=k;this.balpha=m;this.dashLength=w;this.topRadius=u;this.pattern=z;this.rotate=r;this.bcn=q;r?0>b&&0===p&&(p=180):0>c&&270==p&&(p=90);this.gradientRotation=p;0===d&&0===e&&(this.cornerRadius=n);this.draw()},draw:function(){var a=this.set;a.clear(); var b=this.container,c=b.chart,d=this.w,g=this.h,h=this.dx,f=this.dy,l=this.colors,k=this.alpha,m=this.bwidth,p=this.bcolor,n=this.balpha,r=this.gradientRotation,w=this.cornerRadius,z=this.dashLength,u=this.pattern,q=this.topRadius,D=this.bcn,v=l,t=l;"object"==typeof l&&(v=l[0],t=l[l.length-1]);var x,B,A,G,y,C,F,L,M,Q=k;u&&(k=0);var E,H,I,J,K=this.rotate;if(0<Math.abs(h)||0<Math.abs(f))if(isNaN(q))F=t,t=e.adjustLuminosity(v,-.2),t=e.adjustLuminosity(v,-.2),x=e.polygon(b,[0,h,d+h,d,0],[0,f,f,0,0], t,k,1,p,0,r),0<n&&(M=e.line(b,[0,h,d+h],[0,f,f],p,n,m,z)),B=e.polygon(b,[0,0,d,d,0],[0,g,g,0,0],t,k,1,p,0,r),B.translate(h,f),0<n&&(A=e.line(b,[h,h],[f,f+g],p,n,m,z)),G=e.polygon(b,[0,0,h,h,0],[0,g,g+f,f,0],t,k,1,p,0,r),y=e.polygon(b,[d,d,d+h,d+h,d],[0,g,g+f,f,0],t,k,1,p,0,r),0<n&&(C=e.line(b,[d,d+h,d+h,d],[0,f,g+f,g],p,n,m,z)),t=e.adjustLuminosity(F,.2),F=e.polygon(b,[0,h,d+h,d,0],[g,g+f,g+f,g,g],t,k,1,p,0,r),0<n&&(L=e.line(b,[0,h,d+h],[g,g+f,g+f],p,n,m,z));else{var N,O,P;K?(N=g/2,t=h/2,P=g/2,O= d+h/2,H=Math.abs(g/2),E=Math.abs(h/2)):(t=d/2,N=f/2,O=d/2,P=g+f/2+1,E=Math.abs(d/2),H=Math.abs(f/2));I=E*q;J=H*q;.1<E&&.1<E&&(x=e.circle(b,E,v,k,m,p,n,!1,H),x.translate(t,N));.1<I&&.1<I&&(F=e.circle(b,I,e.adjustLuminosity(v,.5),k,m,p,n,!1,J),F.translate(O,P))}k=Q;1>Math.abs(g)&&(g=0);1>Math.abs(d)&&(d=0);!isNaN(q)&&(0<Math.abs(h)||0<Math.abs(f))?(l=[v],l={fill:l,stroke:p,"stroke-width":m,"stroke-opacity":n,"fill-opacity":k},K?(k="M0,0 L"+d+","+(g/2-g/2*q),m=" B",0<d&&(m=" A"),e.VML?(k+=m+Math.round(d- I)+","+Math.round(g/2-J)+","+Math.round(d+I)+","+Math.round(g/2+J)+","+d+",0,"+d+","+g,k=k+(" L0,"+g)+(m+Math.round(-E)+","+Math.round(g/2-H)+","+Math.round(E)+","+Math.round(g/2+H)+",0,"+g+",0,0")):(k+="A"+I+","+J+",0,0,0,"+d+","+(g-g/2*(1-q))+"L0,"+g,k+="A"+E+","+H+",0,0,1,0,0"),E=90):(m=d/2-d/2*q,k="M0,0 L"+m+","+g,e.VML?(k="M0,0 L"+m+","+g,m=" B",0>g&&(m=" A"),k+=m+Math.round(d/2-I)+","+Math.round(g-J)+","+Math.round(d/2+I)+","+Math.round(g+J)+",0,"+g+","+d+","+g,k+=" L"+d+",0",k+=m+Math.round(d/ 2+E)+","+Math.round(H)+","+Math.round(d/2-E)+","+Math.round(-H)+","+d+",0,0,0"):(k+="A"+I+","+J+",0,0,0,"+(d-d/2*(1-q))+","+g+"L"+d+",0",k+="A"+E+","+H+",0,0,1,0,0"),E=180),b=b.path(k).attr(l),b.gradient("linearGradient",[v,e.adjustLuminosity(v,-.3),e.adjustLuminosity(v,-.3),v],E),K?b.translate(h/2,0):b.translate(0,f/2)):b=0===g?e.line(b,[0,d],[0,0],p,n,m,z):0===d?e.line(b,[0,0],[0,g],p,n,m,z):0<w?e.rect(b,d,g,l,k,m,p,n,w,r,z):e.polygon(b,[0,0,d,d,0],[0,g,g,0,0],l,k,m,p,n,r,!1,z);d=isNaN(q)?0>g?[x, M,B,A,G,y,C,F,L,b]:[F,L,B,A,G,y,x,M,C,b]:K?0<d?[x,b,F]:[F,b,x]:0>g?[x,b,F]:[F,b,x];e.setCN(c,b,D+"front");e.setCN(c,B,D+"back");e.setCN(c,F,D+"top");e.setCN(c,x,D+"bottom");e.setCN(c,G,D+"left");e.setCN(c,y,D+"right");for(x=0;x<d.length;x++)if(B=d[x])a.push(B),e.setCN(c,B,D+"element");u&&b.pattern(u,NaN,c.path)},width:function(a){isNaN(a)&&(a=0);this.w=Math.round(a);this.draw()},height:function(a){isNaN(a)&&(a=0);this.h=Math.round(a);this.draw()},animateHeight:function(a,b){var c=this;c.animationFinished= !1;c.easing=b;c.totalFrames=a*e.updateRate;c.rh=c.h;c.frame=0;c.height(1);setTimeout(function(){c.updateHeight.call(c)},1E3/e.updateRate)},updateHeight:function(){var a=this;a.frame++;var b=a.totalFrames;a.frame<=b?(b=a.easing(0,a.frame,1,a.rh-1,b),a.height(b),window.requestAnimationFrame?window.requestAnimationFrame(function(){a.updateHeight.call(a)}):setTimeout(function(){a.updateHeight.call(a)},1E3/e.updateRate)):(a.height(a.rh),a.animationFinished=!0)},animateWidth:function(a,b){var c=this;c.animationFinished= !1;c.easing=b;c.totalFrames=a*e.updateRate;c.rw=c.w;c.frame=0;c.width(1);setTimeout(function(){c.updateWidth.call(c)},1E3/e.updateRate)},updateWidth:function(){var a=this;a.frame++;var b=a.totalFrames;a.frame<=b?(b=a.easing(0,a.frame,1,a.rw-1,b),a.width(b),window.requestAnimationFrame?window.requestAnimationFrame(function(){a.updateWidth.call(a)}):setTimeout(function(){a.updateWidth.call(a)},1E3/e.updateRate)):(a.width(a.rw),a.animationFinished=!0)}})})();(function(){var e=window.AmCharts;e.CategoryAxis=e.Class({inherits:e.AxisBase,construct:function(a){this.cname="CategoryAxis";e.CategoryAxis.base.construct.call(this,a);this.minPeriod="DD";this.equalSpacing=this.parseDates=!1;this.position="bottom";this.startOnAxis=!1;this.gridPosition="middle";this.safeDistance=30;this.stickBalloonToCategory=!1;e.applyTheme(this,a,this.cname)},draw:function(){e.CategoryAxis.base.draw.call(this);this.generateDFObject();var a=this.chart.chartData;this.data=a;this.labelRotationR= this.labelRotation;this.type=null;if(e.ifArray(a)){var b,c=this.chart;"scrollbar"!=this.id?(e.setCN(c,this.set,"category-axis"),e.setCN(c,this.labelsSet,"category-axis"),e.setCN(c,this.axisLine.axisSet,"category-axis")):this.bcn=this.id+"-";var d=this.start,g=this.labelFrequency,h=0,f=this.end-d+1,l=this.gridCountR,k=this.showFirstLabel,m=this.showLastLabel,p,n="",n=e.extractPeriod(this.minPeriod),r=e.getPeriodDuration(n.period,n.count),w,z,u,q,D=this.rotate;p=this.firstDayOfWeek;var v=this.boldPeriodBeginning; b=e.resetDateToMin(new Date(a[a.length-1].time+1.05*r),this.minPeriod,1,p).getTime();this.firstTime=c.firstTime;var t;this.endTime>b&&(this.endTime=b);q=this.minorGridEnabled;z=this.gridAlpha;var x=0,B=0;if(this.widthField)for(b=this.start;b<=this.end;b++)if(t=this.data[b]){var A=Number(this.data[b].dataContext[this.widthField]);isNaN(A)||(x+=A,t.widthValue=A)}if(this.parseDates&&!this.equalSpacing)this.lastTime=a[a.length-1].time,this.maxTime=e.resetDateToMin(new Date(this.lastTime+1.05*r),this.minPeriod, 1,p).getTime(),this.timeDifference=this.endTime-this.startTime,this.parseDatesDraw();else if(!this.parseDates){if(this.cellWidth=this.getStepWidth(f),f<l&&(l=f),h+=this.start,this.stepWidth=this.getStepWidth(f),0<l)for(v=Math.floor(f/l),r=this.chooseMinorFrequency(v),f=h,f/2==Math.round(f/2)&&f--,0>f&&(f=0),l=0,this.widthField&&(f=this.start),this.end-f+1>=this.autoRotateCount&&(this.labelRotationR=this.autoRotateAngle),b=f;b<=this.end+2;b++){p=!1;0<=b&&b<this.data.length?(w=this.data[b],n=w.category, p=w.forceShow):n="";if(q&&!isNaN(r))if(b/r==Math.round(b/r)||p)b/v==Math.round(b/v)||p||(this.gridAlpha=this.minorGridAlpha,n=void 0);else continue;else if(b/v!=Math.round(b/v)&&!p)continue;f=this.getCoordinate(b-h);u=0;"start"==this.gridPosition&&(f-=this.cellWidth/2,u=this.cellWidth/2);p=!0;a=u;"start"==this.tickPosition&&(a=0,p=!1,u=0);if(b==d&&!k||b==this.end&&!m)n=void 0;Math.round(l/g)!=l/g&&(n=void 0);l++;A=this.cellWidth;D&&(A=NaN,this.ignoreAxisWidth||!c.autoMargins)&&(A="right"==this.position? c.marginRight:c.marginLeft,A-=this.tickLength+10);this.labelFunction&&w&&(n=this.labelFunction(n,w,this));n=e.fixBrakes(n);t=!1;this.boldLabels&&(t=!0);b>this.end&&"start"==this.tickPosition&&(n=" ");this.rotate&&this.inside&&(u-=2);isNaN(w.widthValue)||(w.percentWidthValue=w.widthValue/x*100,A=this.rotate?this.height*w.widthValue/x:this.width*w.widthValue/x,f=B,B+=A,u=A/2);u=new this.axisItemRenderer(this,f,n,p,A,u,void 0,t,a,!1,w.labelColor,w.className);u.serialDataItem=w;this.pushAxisItem(u);this.gridAlpha= z}}else if(this.parseDates&&this.equalSpacing){h=this.start;this.startTime=this.data[this.start].time;this.endTime=this.data[this.end].time;this.timeDifference=this.endTime-this.startTime;b=this.choosePeriod(0);g=b.period;w=b.count;b=e.getPeriodDuration(g,w);b<r&&(g=n.period,w=n.count,b=r);z=g;"WW"==z&&(z="DD");this.currentDateFormat=this.dateFormatsObject[z];this.stepWidth=this.getStepWidth(f);l=Math.ceil(this.timeDifference/b)+1;n=e.resetDateToMin(new Date(this.startTime-b),g,w,p).getTime();this.cellWidth= this.getStepWidth(f);f=Math.round(n/b);d=-1;f/2==Math.round(f/2)&&(d=-2,n-=b);f=this.start;f/2==Math.round(f/2)&&f--;0>f&&(f=0);B=this.end+2;B>=this.data.length&&(B=this.data.length);a=!1;a=!k;this.previousPos=-1E3;20<this.labelRotationR&&(this.safeDistance=5);A=f;if(this.data[f].time!=e.resetDateToMin(new Date(this.data[f].time),g,w,p).getTime()){t=0;var G=n;for(b=f;b<B;b++)r=this.data[b].time,this.checkPeriodChange(g,w,r,G)&&(t++,2<=t&&(A=b,b=B),G=r)}q&&1<w&&(r=this.chooseMinorFrequency(w),e.getPeriodDuration(g, r));if(0<this.gridCountR)for(b=f;b<B;b++)if(r=this.data[b].time,this.checkPeriodChange(g,w,r,n)&&b>=A){f=this.getCoordinate(b-this.start);q=!1;this.nextPeriod[z]&&(q=this.checkPeriodChange(this.nextPeriod[z],1,r,n,z))&&e.resetDateToMin(new Date(r),this.nextPeriod[z],1,p).getTime()!=r&&(q=!1);t=!1;q&&this.markPeriodChange?(q=this.dateFormatsObject[this.nextPeriod[z]],t=!0):q=this.dateFormatsObject[z];n=e.formatDate(new Date(r),q,c);if(b==d&&!k||b==l&&!m)n=" ";a?a=!1:(v||(t=!1),f-this.previousPos>this.safeDistance* Math.cos(this.labelRotationR*Math.PI/180)&&(this.labelFunction&&(n=this.labelFunction(n,new Date(r),this,g,w,u)),this.boldLabels&&(t=!0),u=new this.axisItemRenderer(this,f,n,void 0,void 0,void 0,void 0,t),q=u.graphics(),this.pushAxisItem(u),q=q.getBBox().width,e.isModern||(q-=f),this.previousPos=f+q));u=n=r}}for(b=k=0;b<this.data.length;b++)if(t=this.data[b])this.parseDates&&!this.equalSpacing?(m=t.time,d=this.cellWidth,"MM"==this.minPeriod&&(d=864E5*e.daysInMonth(new Date(m))*this.stepWidth,t.cellWidth= d),m=Math.round((m-this.startTime)*this.stepWidth+d/2)):m=this.getCoordinate(b-h),t.x[this.id]=m;if(this.widthField)for(b=this.start;b<=this.end;b++)t=this.data[b],d=t.widthValue,t.percentWidthValue=d/x*100,this.rotate?(m=this.height*d/x/2+k,k=this.height*d/x+k):(m=this.width*d/x/2+k,k=this.width*d/x+k),t.x[this.id]=m;x=this.guides.length;for(b=0;b<x;b++)if(k=this.guides[b],p=v=v=q=d=NaN,m=k.above,k.toCategory&&(v=c.getCategoryIndexByValue(k.toCategory),isNaN(v)||(d=this.getCoordinate(v-h),k.expand&& (d+=this.cellWidth/2),u=new this.axisItemRenderer(this,d,"",!0,NaN,NaN,k),this.pushAxisItem(u,m))),k.category&&(p=c.getCategoryIndexByValue(k.category),isNaN(p)||(q=this.getCoordinate(p-h),k.expand&&(q-=this.cellWidth/2),v=(d-q)/2,u=new this.axisItemRenderer(this,q,k.label,!0,NaN,v,k),this.pushAxisItem(u,m))),p=c.dataDateFormat,k.toDate&&(!p||k.toDate instanceof Date||(k.toDate=k.toDate.toString()+" |"),k.toDate=e.getDate(k.toDate,p),this.equalSpacing?(v=c.getClosestIndex(this.data,"time",k.toDate.getTime(), !1,0,this.data.length-1),isNaN(v)||(d=this.getCoordinate(v-h))):d=(k.toDate.getTime()-this.startTime)*this.stepWidth,u=new this.axisItemRenderer(this,d,"",!0,NaN,NaN,k),this.pushAxisItem(u,m)),k.date&&(!p||k.date instanceof Date||(k.date=k.date.toString()+" |"),k.date=e.getDate(k.date,p),this.equalSpacing?(p=c.getClosestIndex(this.data,"time",k.date.getTime(),!1,0,this.data.length-1),isNaN(p)||(q=this.getCoordinate(p-h))):q=(k.date.getTime()-this.startTime)*this.stepWidth,v=(d-q)/2,p=!0,k.toDate&& (p=!1),u="H"==this.orientation?new this.axisItemRenderer(this,q,k.label,p,2*v,NaN,k):new this.axisItemRenderer(this,q,k.label,!1,NaN,v,k),this.pushAxisItem(u,m)),0<d||0<q){p=!1;if(this.rotate){if(d<this.height||q<this.height)p=!0}else if(d<this.width||q<this.width)p=!0;p&&(d=new this.guideFillRenderer(this,q,d,k),q=d.graphics(),this.pushAxisItem(d,m),k.graphics=q,q.index=b,k.balloonText&&this.addEventListeners(q,k))}if(c=c.chartCursor)D?c.fixHeight(this.cellWidth):(c.fixWidth(this.cellWidth),c.fullWidth&& this.balloon&&(this.balloon.minWidth=this.cellWidth));this.previousHeight=y}this.axisCreated=!0;this.set.translate(this.x,this.y);this.labelsSet.translate(this.x,this.y);this.labelsSet.show();this.positionTitle();(D=this.axisLine.set)&&D.toFront();var y=this.getBBox().height;2<y-this.previousHeight&&this.autoWrap&&!this.parseDates&&(this.axisCreated=this.chart.marginsUpdated=!1)},xToIndex:function(a){var b=this.data,c=this.chart,d=c.rotate,g=this.stepWidth,h;if(this.parseDates&&!this.equalSpacing)a= this.startTime+Math.round(a/g)-this.minDuration()/2,h=c.getClosestIndex(b,"time",a,!1,this.start,this.end+1);else if(this.widthField)for(c=Infinity,g=this.start;g<=this.end;g++){var f=this.data[g];f&&(f=Math.abs(f.x[this.id]-a),f<c&&(c=f,h=g))}else this.startOnAxis||(a-=g/2),h=this.start+Math.round(a/g);h=e.fitToBounds(h,0,b.length-1);var l;b[h]&&(l=b[h].x[this.id]);d?l>this.height+1&&h--:l>this.width+1&&h--;0>l&&h++;return h=e.fitToBounds(h,0,b.length-1)},dateToCoordinate:function(a){return this.parseDates&& !this.equalSpacing?(a.getTime()-this.startTime)*this.stepWidth:this.parseDates&&this.equalSpacing?(a=this.chart.getClosestIndex(this.data,"time",a.getTime(),!1,0,this.data.length-1),this.getCoordinate(a-this.start)):NaN},categoryToCoordinate:function(a){if(this.chart){if(this.parseDates)return this.dateToCoordinate(new Date(a));a=this.chart.getCategoryIndexByValue(a);if(!isNaN(a))return this.getCoordinate(a-this.start)}else return NaN},coordinateToDate:function(a){return this.equalSpacing?(a=this.xToIndex(a), new Date(this.data[a].time)):new Date(this.startTime+a/this.stepWidth)},coordinateToValue:function(a){a=this.xToIndex(a);if(a=this.data[a])return this.parseDates?a.time:a.category},getCoordinate:function(a){a*=this.stepWidth;this.startOnAxis||(a+=this.stepWidth/2);return Math.round(a)},formatValue:function(a,b){b||(b=this.currentDateFormat);this.parseDates&&(a=e.formatDate(new Date(a),b,this.chart));return a},showBalloonAt:function(a){a=this.parseDates?this.dateToCoordinate(new Date(a)):this.categoryToCoordinate(a); return this.adjustBalloonCoordinate(a)},formatBalloonText:function(a,b,c){var d="",g="",h=this.chart,f=this.data[b];if(f)if(this.parseDates)d=e.formatDate(f.category,c,h),b=e.changeDate(new Date(f.category),this.minPeriod,1),g=e.formatDate(b,c,h),-1!=d.indexOf("fff")&&(d=e.formatMilliseconds(d,f.category),g=e.formatMilliseconds(g,b));else{var l;this.data[b+1]&&(l=this.data[b+1]);d=e.fixNewLines(f.category);l&&(g=e.fixNewLines(l.category))}a=a.replace(/\[\[category\]\]/g,String(d));return a=a.replace(/\[\[toCategory\]\]/g, String(g))},adjustBalloonCoordinate:function(a,b){var c=this.xToIndex(a),d=this.chart.chartCursor;if(this.stickBalloonToCategory){var e=this.data[c];e&&(a=e.x[this.id]);this.stickBalloonToStart&&(a-=this.cellWidth/2);var h=0;if(d){var f=d.limitToGraph;if(f){var l=f.valueAxis.id;f.hidden||(h=e.axes[l].graphs[f.id].y)}this.rotate?("left"==this.position?(f&&(h-=d.width),0<h&&(h=0)):0>h&&(h=0),d.fixHLine(a,h)):("top"==this.position?(f&&(h-=d.height),0<h&&(h=0)):0>h&&(h=0),d.fixVLine(a,h))}}d&&!b&&(d.setIndex(c), this.parseDates&&d.setTimestamp(this.coordinateToDate(a).getTime()));return a}})})();
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImagePhoto = (props) => ( <SvgIcon {...props}> <path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/> </SvgIcon> ); ImagePhoto = pure(ImagePhoto); ImagePhoto.displayName = 'ImagePhoto'; ImagePhoto.muiName = 'SvgIcon'; export default ImagePhoto;
(function(e,t){"use strict";function n(){return t.qoopido.initialize("transport",e,arguments)}"function"==typeof define&&define.amd?define(["./base","./function/merge"],n):n()})(function(e){"use strict";var t;return t=e.base.extend({setup:function(t){var n=this;return n._settings=e["function/merge"]({},n._settings,t),n},serialize:function(e,t){var n,o,r,i=[];for(n in e)o=t?"".concat(t,"[",n,"]"):n,r=e[n],i.push("object"==typeof r?this.serialize(r,o):"".concat(encodeURIComponent(o),"=",encodeURIComponent(r)));return i.join("&")}})},window,document);
(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.deepstream = 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(_dereq_,module,exports){ },{}],2:[function(_dereq_,module,exports){ /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; },{}],3:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],4:[function(_dereq_,module,exports){ (function (global){ /*! https://mths.be/punycode v1.4.1 by @mathias */ ;(function(root) { /** Detect free variables */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; var freeModule = typeof module == 'object' && module && !module.nodeType && module; var freeGlobal = typeof global == 'object' && global; if ( freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal ) { root = freeGlobal; } /** * The `punycode` object. * @name punycode * @type Object */ var punycode, /** Highest positive signed 32-bit float value */ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */ base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128, // 0x80 delimiter = '-', // '\x2D' /** Regular expressions */ regexPunycode = /^xn--/, regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators /** Error messages */ errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }, /** Convenience shortcuts */ baseMinusTMin = base - tMin, floor = Math.floor, stringFromCharCode = String.fromCharCode, /** Temporary variable */ key; /*--------------------------------------------------------------------------*/ /** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */ function error(type) { throw new RangeError(errors[type]); } /** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */ function map(array, fn) { var length = array.length; var result = []; while (length--) { result[length] = fn(array[length]); } return result; } /** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */ function mapDomain(string, fn) { var parts = string.split('@'); var result = ''; if (parts.length > 1) { // In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result = parts[0] + '@'; string = parts[1]; } // Avoid `split(regex)` for IE8 compatibility. See #17. string = string.replace(regexSeparators, '\x2E'); var labels = string.split('.'); var encoded = map(labels, fn).join('.'); return result + encoded; } /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see <https://mathiasbynens.be/notes/javascript-encoding> * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */ function ucs2decode(string) { var output = [], counter = 0, length = string.length, value, extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } /** * Creates a string based on an array of numeric code points. * @see `punycode.ucs2.decode` * @memberOf punycode.ucs2 * @name encode * @param {Array} codePoints The array of numeric code points. * @returns {String} The new Unicode string (UCS-2). */ function ucs2encode(array) { return map(array, function(value) { var output = ''; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); return output; }).join(''); } /** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic numeric code point value. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */ function basicToDigit(codePoint) { if (codePoint - 48 < 10) { return codePoint - 22; } if (codePoint - 65 < 26) { return codePoint - 65; } if (codePoint - 97 < 26) { return codePoint - 97; } return base; } /** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */ function digitToBasic(digit, flag) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); } /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */ function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); } /** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. */ function decode(input) { // Don't use UCS-2 var output = [], inputLength = input.length, out, i = 0, n = initialN, bias = initialBias, basic, j, index, oldi, w, k, digit, t, /** Cached calculation results */ baseMinusT; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (j = 0; j < basic; ++j) { // if it's not a basic code point if (input.charCodeAt(j) >= 0x80) { error('not-basic'); } output.push(input.charCodeAt(j)); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { // `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. for (oldi = i, w = 1, k = base; /* no condition */; k += base) { if (index >= inputLength) { error('invalid-input'); } digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (digit < t) { break; } baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor(i / out) > maxInt - n) { error('overflow'); } n += floor(i / out); i %= out; // Insert `n` at position `i` of the output output.splice(i++, 0, n); } return ucs2encode(output); } /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */ function encode(input) { var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], /** `inputLength` will hold the number of code points in `input`. */ inputLength, /** Cached calculation results */ handledCPCountPlusOne, baseMinusT, qMinusT; // Convert the input in UCS-2 to Unicode input = ucs2decode(input); // Cache the length inputLength = input.length; // Initialize the state n = initialN; delta = 0; bias = initialBias; // Handle the basic code points for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string - if it is not empty - with a delimiter if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, // but guard against overflow handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { // Represent delta as a generalized variable-length integer for (q = delta, k = base; /* no condition */; k += base) { t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) { break; } qMinusT = q - t; baseMinusT = base - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); } /** * Converts a Punycode string representing a domain name or an email address * to Unicode. Only the Punycoded parts of the input will be converted, i.e. * it doesn't matter if you call it on a string that has already been * converted to Unicode. * @memberOf punycode * @param {String} input The Punycoded domain name or email address to * convert to Unicode. * @returns {String} The Unicode representation of the given Punycode * string. */ function toUnicode(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); } /** * Converts a Unicode string representing a domain name or an email address to * Punycode. Only the non-ASCII parts of the domain name will be converted, * i.e. it doesn't matter if you call it with a domain that's already in * ASCII. * @memberOf punycode * @param {String} input The domain name or email address to convert, as a * Unicode string. * @returns {String} The Punycode representation of the given domain name or * email address. */ function toASCII(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); } /*--------------------------------------------------------------------------*/ /** Define the public API */ punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ 'version': '1.4.1', /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see <https://mathiasbynens.be/notes/javascript-encoding> * @memberOf punycode * @type Object */ 'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode }; /** Expose `punycode` */ // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( typeof define == 'function' && typeof define.amd == 'object' && define.amd ) { define('punycode', function() { return punycode; }); } else if (freeExports && freeModule) { if (module.exports == freeExports) { // in Node.js, io.js, or RingoJS v0.8.0+ freeModule.exports = punycode; } else { // in Narwhal or RingoJS v0.7.0- for (key in punycode) { punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); } } } else { // in Rhino or a web browser root.punycode = punycode; } }(this)); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],5:[function(_dereq_,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // 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'; // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; },{}],6:[function(_dereq_,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // 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'; var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map(objectKeys(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray(obj[k])) { return map(obj[k], function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; },{}],7:[function(_dereq_,module,exports){ 'use strict'; exports.decode = exports.parse = _dereq_('./decode'); exports.encode = exports.stringify = _dereq_('./encode'); },{"./decode":5,"./encode":6}],8:[function(_dereq_,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // 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'; var punycode = _dereq_('punycode'); var util = _dereq_('./util'); exports.parse = urlParse; exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat; exports.Url = Url; function Url() { this.protocol = null; this.slashes = null; this.auth = null; this.host = null; this.port = null; this.hostname = null; this.hash = null; this.search = null; this.query = null; this.pathname = null; this.path = null; this.href = null; } // Reference: RFC 3986, RFC 1808, RFC 2396 // define these here so at least they only have to be // compiled once on the first module load. var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, // Special case for a simple path URL simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, // RFC 2396: characters reserved for delimiting URLs. // We actually just auto-escape these. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], // RFC 2396: characters not allowed for various reasons. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), // Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape = ['\''].concat(unwise), // Characters that are never ever allowed in a hostname. // Note that any invalid chars are also handled, but these // are the ones that are *expected* to be seen, so we fast-path // them. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), hostEndingChars = ['/', '?', '#'], hostnameMaxLen = 255, hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, // protocols that can allow "unsafe" and "unwise" chars. unsafeProtocol = { 'javascript': true, 'javascript:': true }, // protocols that never have a hostname. hostlessProtocol = { 'javascript': true, 'javascript:': true }, // protocols that always contain a // bit. slashedProtocol = { 'http': true, 'https': true, 'ftp': true, 'gopher': true, 'file': true, 'http:': true, 'https:': true, 'ftp:': true, 'gopher:': true, 'file:': true }, querystring = _dereq_('querystring'); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && util.isObject(url) && url instanceof Url) return url; var u = new Url; u.parse(url, parseQueryString, slashesDenoteHost); return u; } Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { if (!util.isString(url)) { throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } // Copy chrome, IE, opera backslash-handling behavior. // Back slashes before the query string get converted to forward slashes // See: https://code.google.com/p/chromium/issues/detail?id=25916 var queryIndex = url.indexOf('?'), splitter = (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', uSplit = url.split(splitter), slashRegex = /\\/g; uSplit[0] = uSplit[0].replace(slashRegex, '/'); url = uSplit.join(splitter); var rest = url; // trim before proceeding. // This is to support parse stuff like " http://foo.com \n" rest = rest.trim(); if (!slashesDenoteHost && url.split('#').length === 1) { // Try fast path regexp var simplePath = simplePathPattern.exec(rest); if (simplePath) { this.path = rest; this.href = rest; this.pathname = simplePath[1]; if (simplePath[2]) { this.search = simplePath[2]; if (parseQueryString) { this.query = querystring.parse(this.search.substr(1)); } else { this.query = this.search.substr(1); } } else if (parseQueryString) { this.search = ''; this.query = {}; } return this; } } var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; var lowerProto = proto.toLowerCase(); this.protocol = lowerProto; rest = rest.substr(proto.length); } // figure out if it's got a host // user@server is *always* interpreted as a hostname, and url // resolution will treat //foo/bar as host=foo,path=bar because that's // how the browser resolves relative URLs. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { var slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); this.slashes = true; } } if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // // If there is an @ in the hostname, then non-host chars *are* allowed // to the left of the last @ sign, unless some host-ending character // comes *before* the @-sign. // URLs are obnoxious. // // ex: // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. // find the first instance of any hostEndingChars var hostEnd = -1; for (var i = 0; i < hostEndingChars.length; i++) { var hec = rest.indexOf(hostEndingChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // at this point, either we have an explicit point where the // auth portion cannot go past, or the last @ char is the decider. var auth, atSign; if (hostEnd === -1) { // atSign can be anywhere. atSign = rest.lastIndexOf('@'); } else { // atSign must be in auth portion. // http://a@b/c@d => host:b auth:a path:/c@d atSign = rest.lastIndexOf('@', hostEnd); } // Now we have a portion which is definitely the auth. // Pull that off. if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); this.auth = decodeURIComponent(auth); } // the host is the remaining to the left of the first non-host char hostEnd = -1; for (var i = 0; i < nonHostChars.length; i++) { var hec = rest.indexOf(nonHostChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // if we still have not hit it, then the entire thing is a host. if (hostEnd === -1) hostEnd = rest.length; this.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); // pull out port. this.parseHost(); // we've indicated that there is a hostname, // so even if it's empty, it has to be present. this.hostname = this.hostname || ''; // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; // validate a little. if (!ipv6Hostname) { var hostparts = this.hostname.split(/\./); for (var i = 0, l = hostparts.length; i < l; i++) { var part = hostparts[i]; if (!part) continue; if (!part.match(hostnamePartPattern)) { var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { if (part.charCodeAt(j) > 127) { // we replace non-ASCII char with a temporary placeholder // we need this to make sure size of hostname is not // broken by replacing non-ASCII by nothing newpart += 'x'; } else { newpart += part[j]; } } // we test again with ASCII char only if (!newpart.match(hostnamePartPattern)) { var validParts = hostparts.slice(0, i); var notHost = hostparts.slice(i + 1); var bit = part.match(hostnamePartStart); if (bit) { validParts.push(bit[1]); notHost.unshift(bit[2]); } if (notHost.length) { rest = '/' + notHost.join('.') + rest; } this.hostname = validParts.join('.'); break; } } } } if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } else { // hostnames are always lower case. this.hostname = this.hostname.toLowerCase(); } if (!ipv6Hostname) { // IDNA Support: Returns a punycoded representation of "domain". // It only converts parts of the domain name that // have non-ASCII characters, i.e. it doesn't matter if // you call it with a domain that already is ASCII-only. this.hostname = punycode.toASCII(this.hostname); } var p = this.port ? ':' + this.port : ''; var h = this.hostname || ''; this.host = h + p; this.href += this.host; // strip [ and ] from the hostname // the host field still retains them, though if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); if (rest[0] !== '/') { rest = '/' + rest; } } } // now rest is set to the post-host stuff. // chop off any delim chars. if (!unsafeProtocol[lowerProto]) { // First, make 100% sure that any "autoEscape" chars get // escaped, even if encodeURIComponent doesn't think they // need to be. for (var i = 0, l = autoEscape.length; i < l; i++) { var ae = autoEscape[i]; if (rest.indexOf(ae) === -1) continue; var esc = encodeURIComponent(ae); if (esc === ae) { esc = escape(ae); } rest = rest.split(ae).join(esc); } } // chop off from the tail first. var hash = rest.indexOf('#'); if (hash !== -1) { // got a fragment string. this.hash = rest.substr(hash); rest = rest.slice(0, hash); } var qm = rest.indexOf('?'); if (qm !== -1) { this.search = rest.substr(qm); this.query = rest.substr(qm + 1); if (parseQueryString) { this.query = querystring.parse(this.query); } rest = rest.slice(0, qm); } else if (parseQueryString) { // no query string, but parseQueryString still requested this.search = ''; this.query = {}; } if (rest) this.pathname = rest; if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { this.pathname = '/'; } //to support http.request if (this.pathname || this.search) { var p = this.pathname || ''; var s = this.search || ''; this.path = p + s; } // finally, reconstruct the href based on what has been validated. this.href = this.format(); return this; }; // format a parsed object into a url string function urlFormat(obj) { // ensure it's an object, and not a string url. // If it's an obj, this is a no-op. // this way, you can call url_format() on strings // to clean up potentially wonky urls. if (util.isString(obj)) obj = urlParse(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj); return obj.format(); } Url.prototype.format = function() { var auth = this.auth || ''; if (auth) { auth = encodeURIComponent(auth); auth = auth.replace(/%3A/i, ':'); auth += '@'; } var protocol = this.protocol || '', pathname = this.pathname || '', hash = this.hash || '', host = false, query = ''; if (this.host) { host = auth + this.host; } else if (this.hostname) { host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); if (this.port) { host += ':' + this.port; } } if (this.query && util.isObject(this.query) && Object.keys(this.query).length) { query = querystring.stringify(this.query); } var search = this.search || (query && ('?' + query)) || ''; if (protocol && protocol.substr(-1) !== ':') protocol += ':'; // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // unless they had them to begin with. if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { host = '//' + (host || ''); if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; } else if (!host) { host = ''; } if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; pathname = pathname.replace(/[?#]/g, function(match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); return protocol + host + pathname + search + hash; }; function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } Url.prototype.resolve = function(relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } Url.prototype.resolveObject = function(relative) { if (util.isString(relative)) { var rel = new Url(); rel.parse(relative, false, true); relative = rel; } var result = new Url(); var tkeys = Object.keys(this); for (var tk = 0; tk < tkeys.length; tk++) { var tkey = tkeys[tk]; result[tkey] = this[tkey]; } // hash is always overridden, no matter what. // even href="" will remove it. result.hash = relative.hash; // if the relative url is empty, then there's nothing left to do here. if (relative.href === '') { result.href = result.format(); return result; } // hrefs like //foo/bar always cut to the protocol. if (relative.slashes && !relative.protocol) { // take everything except the protocol from relative var rkeys = Object.keys(relative); for (var rk = 0; rk < rkeys.length; rk++) { var rkey = rkeys[rk]; if (rkey !== 'protocol') result[rkey] = relative[rkey]; } //urlParse appends trailing / to urls like http://www.example.com if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } result.href = result.format(); return result; } if (relative.protocol && relative.protocol !== result.protocol) { // if it's a known url protocol, then changing // the protocol does weird things // first, if it's not file:, then we MUST have a host, // and if there was a path // to begin with, then we MUST have a path. // if it is file:, then the host is dropped, // because that's known to be hostless. // anything else is assumed to be absolute. if (!slashedProtocol[relative.protocol]) { var keys = Object.keys(relative); for (var v = 0; v < keys.length; v++) { var k = keys[v]; result[k] = relative[k]; } result.href = result.format(); return result; } result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { var relPath = (relative.pathname || '').split('/'); while (relPath.length && !(relative.host = relPath.shift())); if (!relative.host) relative.host = ''; if (!relative.hostname) relative.hostname = ''; if (relPath[0] !== '') relPath.unshift(''); if (relPath.length < 2) relPath.unshift(''); result.pathname = relPath.join('/'); } else { result.pathname = relative.pathname; } result.search = relative.search; result.query = relative.query; result.host = relative.host || ''; result.auth = relative.auth; result.hostname = relative.hostname || relative.host; result.port = relative.port; // to support http.request if (result.pathname || result.search) { var p = result.pathname || ''; var s = result.search || ''; result.path = p + s; } result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; } var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), isRelAbs = ( relative.host || relative.pathname && relative.pathname.charAt(0) === '/' ), mustEndAbs = (isRelAbs || isSourceAbs || (result.host && relative.pathname)), removeAllDots = mustEndAbs, srcPath = result.pathname && result.pathname.split('/') || [], relPath = relative.pathname && relative.pathname.split('/') || [], psychotic = result.protocol && !slashedProtocol[result.protocol]; // if the url is a non-slashed url, then relative // links like ../.. should be able // to crawl up to the hostname, as well. This is strange. // result.protocol has already been set by now. // Later on, put the first path part into the host field. if (psychotic) { result.hostname = ''; result.port = null; if (result.host) { if (srcPath[0] === '') srcPath[0] = result.host; else srcPath.unshift(result.host); } result.host = ''; if (relative.protocol) { relative.hostname = null; relative.port = null; if (relative.host) { if (relPath[0] === '') relPath[0] = relative.host; else relPath.unshift(relative.host); } relative.host = null; } mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } if (isRelAbs) { // it's absolute. result.host = (relative.host || relative.host === '') ? relative.host : result.host; result.hostname = (relative.hostname || relative.hostname === '') ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; // fall through to the dot-handling below. } else if (relPath.length) { // it's relative // throw away the existing file, and take the new path instead. if (!srcPath) srcPath = []; srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; } else if (!util.isNullOrUndefined(relative.search)) { // just pull out the search. // like href='?foo'. // Put this after the other two cases because it simplifies the booleans if (psychotic) { result.hostname = result.host = srcPath.shift(); //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } result.search = relative.search; result.query = relative.query; //to support http.request if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; } if (!srcPath.length) { // no path at all. easy. // we've already handled the other stuff above. result.pathname = null; //to support http.request if (result.search) { result.path = '/' + result.search; } else { result.path = null; } result.href = result.format(); return result; } // if a url ENDs in . or .., then it must get a trailing slash. // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. var last = srcPath.slice(-1)[0]; var hasTrailingSlash = ( (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === ''); // strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = srcPath.length; i >= 0; i--) { last = srcPath[i]; if (last === '.') { srcPath.splice(i, 1); } else if (last === '..') { srcPath.splice(i, 1); up++; } else if (up) { srcPath.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { srcPath.push(''); } var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // put the host back if (psychotic) { result.hostname = result.host = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } mustEndAbs = mustEndAbs || (result.host && srcPath.length); if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); } //to support request.http if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; }; Url.prototype.parseHost = function() { var host = this.host; var port = portPattern.exec(host); if (port) { port = port[0]; if (port !== ':') { this.port = port.substr(1); } host = host.substr(0, host.length - port.length); } if (host) this.hostname = host; }; },{"./util":9,"punycode":4,"querystring":7}],9:[function(_dereq_,module,exports){ 'use strict'; module.exports = { isString: function(arg) { return typeof(arg) === 'string'; }, isObject: function(arg) { return typeof(arg) === 'object' && arg !== null; }, isNull: function(arg) { return arg === null; }, isNullOrUndefined: function(arg) { return arg == null; } }; },{}],10:[function(_dereq_,module,exports){ var C = _dereq_( './constants/constants' ), MS = _dereq_( './constants/merge-strategies' ), Emitter = _dereq_( 'component-emitter' ), Connection = _dereq_( './message/connection' ), EventHandler = _dereq_( './event/event-handler' ), RpcHandler = _dereq_( './rpc/rpc-handler' ), RecordHandler = _dereq_( './record/record-handler' ), PresenceHandler = _dereq_( './presence/presence-handler' ), defaultOptions = _dereq_( './default-options' ), messageBuilder = _dereq_( './message/message-builder' ); /** * deepstream.io javascript client * * @copyright 2016 deepstreamHub GmbH * @author deepstreamHub GmbH * * * @{@link http://deepstream.io} * * * @param {String} url URL to connect to. The protocol can be ommited, e.g. <host>:<port>. * @param {Object} options A map of options that extend the ones specified in default-options.js * * @public * @constructor */ var Client = function( url, options ) { this._url = url; this._options = this._getOptions( options || {} ); this._connection = new Connection( this, this._url, this._options ); this.event = new EventHandler( this._options, this._connection, this ); this.rpc = new RpcHandler( this._options, this._connection, this ); this.record = new RecordHandler( this._options, this._connection, this ); this.presence = new PresenceHandler( this._options, this._connection, this ); this._messageCallbacks = {}; this._messageCallbacks[ C.TOPIC.EVENT ] = this.event._$handle.bind( this.event ); this._messageCallbacks[ C.TOPIC.RPC ] = this.rpc._$handle.bind( this.rpc ); this._messageCallbacks[ C.TOPIC.RECORD ] = this.record._$handle.bind( this.record ); this._messageCallbacks[ C.TOPIC.PRESENCE ] = this.presence._$handle.bind( this.presence ); this._messageCallbacks[ C.TOPIC.ERROR ] = this._onErrorMessage.bind( this ); }; Emitter( Client.prototype ); /** * Send authentication parameters to the client to fully open * the connection. * * Please note: Authentication parameters are send over an already established * connection, rather than appended to the server URL. This means the parameters * will be encrypted when used with a WSS / HTTPS connection. If the deepstream server * on the other side has message logging enabled it will however be written to the logs in * plain text. If additional security is a requirement it might therefor make sense to hash * the password on the client. * * If the connection is not yet established the authentication parameter will be * stored and send once it becomes available * * authParams can be any JSON serializable data structure and its up for the * permission handler on the server to make sense of them, although something * like { username: 'someName', password: 'somePass' } will probably make the most sense. * * login can be called multiple times until either the connection is authenticated or * forcefully closed by the server since its maxAuthAttempts threshold has been exceeded * * @param {Object} authParams JSON.serializable authentication data * @param {Function} callback Will be called with either (true) or (false, data) * * @public * @returns {Client} */ Client.prototype.login = function( authParams, callback ) { this._connection.authenticate( authParams || {}, callback ); return this; }; /** * Closes the connection to the server. * * @public * @returns {void} */ Client.prototype.close = function() { this._connection.close(); }; /** * Returns the current state of the connection. * * connectionState is one of CONSTANTS.CONNECTION_STATE * * @returns {[type]} [description] */ Client.prototype.getConnectionState = function() { return this._connection.getState(); }; /** * Returns a random string. The first block of characters * is a timestamp, in order to allow databases to optimize for semi- * sequentuel numberings * * @public * @returns {String} unique id */ Client.prototype.getUid = function() { var timestamp = (new Date()).getTime().toString(36), randomString = (Math.random() * 10000000000000000).toString(36).replace( '.', '' ); return timestamp + '-' + randomString; }; /** * Package private callback for parsed incoming messages. Will be invoked * by the connection class * * @param {Object} message parsed deepstream message * * @package private * @returns {void} */ Client.prototype._$onMessage = function( message ) { if( this._messageCallbacks[ message.topic ] ) { this._messageCallbacks[ message.topic ]( message ); } else { message.processedError = true; this._$onError( message.topic, C.EVENT.MESSAGE_PARSE_ERROR, 'Received message for unknown topic ' + message.topic ); } if( message.action === C.ACTIONS.ERROR && !message.processedError ) { this._$onError( message.topic, message.data[ 0 ], message.data.slice( 0 ) ); } }; /** * Package private error callback. This is the single point at which * errors are thrown in the client. (Well... that's the intention anyways) * * The expectations would be for implementations to subscribe * to the client's error event to prevent errors from being thrown * and then decide based on the event and topic parameters how * to handle the errors * * IMPORTANT: Errors that are specific to a request, e.g. a RPC * timing out or a record not being permissioned are passed directly * to the method that requested them * * @param {String} topic One of CONSTANTS.TOPIC * @param {String} event One of CONSTANTS.EVENT * @param {String} msg Error dependent message * * @package private * @returns {void} */ Client.prototype._$onError = function( topic, event, msg ) { var errorMsg; /* * Help to diagnose the problem quicker by checking for * some common problems */ if( event === C.EVENT.ACK_TIMEOUT || event === C.EVENT.RESPONSE_TIMEOUT ) { if( this.getConnectionState() === C.CONNECTION_STATE.AWAITING_AUTHENTICATION ) { errorMsg = 'Your message timed out because you\'re not authenticated. Have you called login()?'; setTimeout( this._$onError.bind( this, C.EVENT.NOT_AUTHENTICATED, C.TOPIC.ERROR, errorMsg ), 1 ); } } if( this.hasListeners( 'error' ) ) { this.emit( 'error', msg, event, topic ); this.emit( event, topic, msg ); } else { console.log( '--- You can catch all deepstream errors by subscribing to the error event ---' ); errorMsg = event + ': ' + msg; if( topic ) { errorMsg += ' (' + topic + ')'; } throw new Error( errorMsg ); } }; /** * Passes generic messages from the error topic * to the _$onError handler * * @param {Object} errorMessage parsed deepstream error message * * @private * @returns {void} */ Client.prototype._onErrorMessage = function( errorMessage ) { this._$onError( errorMessage.topic, errorMessage.data[ 0 ], errorMessage.data[ 1 ] ); }; /** * Creates a new options map by extending default * options with the passed in options * * @param {Object} options The user specified client configuration options * * @private * @returns {Object} merged options */ Client.prototype._getOptions = function( options ) { var mergedOptions = {}, key; for( key in defaultOptions ) { if( typeof options[ key ] === 'undefined' ) { mergedOptions[ key ] = defaultOptions[ key ]; } else { mergedOptions[ key ] = options[ key ]; } } return mergedOptions; }; /** * Exports factory function to adjust to the current JS style of * disliking 'new' :-) * * @param {String} url URL to connect to. The protocol can be ommited, e.g. <host>:<port>. * @param {Object} options A map of options that extend the ones specified in default-options.js * * @public * @returns {void} */ function createDeepstream( url, options ) { return new Client( url, options ); } /** * Expose constants to allow consumers to access them */ Client.prototype.CONSTANTS = C; createDeepstream.CONSTANTS = C; /** * Expose merge strategies to allow consumers to access them */ Client.prototype.MERGE_STRATEGIES = MS; createDeepstream.MERGE_STRATEGIES = MS; module.exports = createDeepstream; },{"./constants/constants":11,"./constants/merge-strategies":12,"./default-options":13,"./event/event-handler":14,"./message/connection":15,"./message/message-builder":16,"./presence/presence-handler":18,"./record/record-handler":22,"./rpc/rpc-handler":24,"component-emitter":2}],11:[function(_dereq_,module,exports){ exports.CONNECTION_STATE = {}; exports.CONNECTION_STATE.CLOSED = 'CLOSED'; exports.CONNECTION_STATE.AWAITING_CONNECTION = 'AWAITING_CONNECTION'; exports.CONNECTION_STATE.CHALLENGING = 'CHALLENGING'; exports.CONNECTION_STATE.AWAITING_AUTHENTICATION = 'AWAITING_AUTHENTICATION'; exports.CONNECTION_STATE.AUTHENTICATING = 'AUTHENTICATING'; exports.CONNECTION_STATE.OPEN = 'OPEN'; exports.CONNECTION_STATE.ERROR = 'ERROR'; exports.CONNECTION_STATE.RECONNECTING = 'RECONNECTING'; exports.MESSAGE_SEPERATOR = String.fromCharCode( 30 ); // ASCII Record Seperator 1E exports.MESSAGE_PART_SEPERATOR = String.fromCharCode( 31 ); // ASCII Unit Separator 1F exports.TYPES = {}; exports.TYPES.STRING = 'S'; exports.TYPES.OBJECT = 'O'; exports.TYPES.NUMBER = 'N'; exports.TYPES.NULL = 'L'; exports.TYPES.TRUE = 'T'; exports.TYPES.FALSE = 'F'; exports.TYPES.UNDEFINED = 'U'; exports.TOPIC = {}; exports.TOPIC.CONNECTION = 'C'; exports.TOPIC.AUTH = 'A'; exports.TOPIC.ERROR = 'X'; exports.TOPIC.EVENT = 'E'; exports.TOPIC.RECORD = 'R'; exports.TOPIC.RPC = 'P'; exports.TOPIC.PRESENCE = 'U'; exports.TOPIC.PRIVATE = 'PRIVATE/'; exports.EVENT = {}; exports.EVENT.CONNECTION_ERROR = 'connectionError'; exports.EVENT.CONNECTION_STATE_CHANGED = 'connectionStateChanged'; exports.EVENT.MAX_RECONNECTION_ATTEMPTS_REACHED = 'MAX_RECONNECTION_ATTEMPTS_REACHED'; exports.EVENT.CONNECTION_AUTHENTICATION_TIMEOUT = 'CONNECTION_AUTHENTICATION_TIMEOUT'; exports.EVENT.ACK_TIMEOUT = 'ACK_TIMEOUT'; exports.EVENT.NO_RPC_PROVIDER = 'NO_RPC_PROVIDER'; exports.EVENT.RESPONSE_TIMEOUT = 'RESPONSE_TIMEOUT'; exports.EVENT.DELETE_TIMEOUT = 'DELETE_TIMEOUT'; exports.EVENT.UNSOLICITED_MESSAGE = 'UNSOLICITED_MESSAGE'; exports.EVENT.MESSAGE_DENIED = 'MESSAGE_DENIED'; exports.EVENT.MESSAGE_PARSE_ERROR = 'MESSAGE_PARSE_ERROR'; exports.EVENT.VERSION_EXISTS = 'VERSION_EXISTS'; exports.EVENT.NOT_AUTHENTICATED = 'NOT_AUTHENTICATED'; exports.EVENT.MESSAGE_PERMISSION_ERROR = 'MESSAGE_PERMISSION_ERROR'; exports.EVENT.LISTENER_EXISTS = 'LISTENER_EXISTS'; exports.EVENT.NOT_LISTENING = 'NOT_LISTENING'; exports.EVENT.TOO_MANY_AUTH_ATTEMPTS = 'TOO_MANY_AUTH_ATTEMPTS'; exports.EVENT.IS_CLOSED = 'IS_CLOSED'; exports.EVENT.RECORD_NOT_FOUND = 'RECORD_NOT_FOUND'; exports.EVENT.NOT_SUBSCRIBED = 'NOT_SUBSCRIBED'; exports.ACTIONS = {}; exports.ACTIONS.PING = 'PI'; exports.ACTIONS.PONG = 'PO'; exports.ACTIONS.ACK = 'A'; exports.ACTIONS.REDIRECT = 'RED'; exports.ACTIONS.CHALLENGE = 'CH'; exports.ACTIONS.CHALLENGE_RESPONSE = 'CHR'; exports.ACTIONS.READ = 'R'; exports.ACTIONS.CREATE = 'C'; exports.ACTIONS.UPDATE = 'U'; exports.ACTIONS.PATCH = 'P'; exports.ACTIONS.DELETE = 'D'; exports.ACTIONS.SUBSCRIBE = 'S'; exports.ACTIONS.UNSUBSCRIBE = 'US'; exports.ACTIONS.HAS = 'H'; exports.ACTIONS.SNAPSHOT = 'SN'; exports.ACTIONS.INVOKE = 'I'; exports.ACTIONS.SUBSCRIPTION_FOR_PATTERN_FOUND = 'SP'; exports.ACTIONS.SUBSCRIPTION_FOR_PATTERN_REMOVED = 'SR'; exports.ACTIONS.SUBSCRIPTION_HAS_PROVIDER = 'SH'; exports.ACTIONS.LISTEN = 'L'; exports.ACTIONS.UNLISTEN = 'UL'; exports.ACTIONS.LISTEN_ACCEPT = 'LA'; exports.ACTIONS.LISTEN_REJECT = 'LR'; exports.ACTIONS.PROVIDER_UPDATE = 'PU'; exports.ACTIONS.QUERY = 'Q'; exports.ACTIONS.CREATEORREAD = 'CR'; exports.ACTIONS.EVENT = 'EVT'; exports.ACTIONS.ERROR = 'E'; exports.ACTIONS.REQUEST = 'REQ'; exports.ACTIONS.RESPONSE = 'RES'; exports.ACTIONS.REJECTION = 'REJ'; exports.ACTIONS.PRESENCE_JOIN = 'PNJ'; exports.ACTIONS.PRESENCE_LEAVE = 'PNL'; exports.ACTIONS.QUERY = 'Q'; exports.ACTIONS.WRITE_ACKNOWLEDGEMENT = 'WA'; exports.CALL_STATE = {}; exports.CALL_STATE.INITIAL = 'INITIAL'; exports.CALL_STATE.CONNECTING = 'CONNECTING'; exports.CALL_STATE.ESTABLISHED = 'ESTABLISHED'; exports.CALL_STATE.ACCEPTED = 'ACCEPTED'; exports.CALL_STATE.DECLINED = 'DECLINED'; exports.CALL_STATE.ENDED = 'ENDED'; exports.CALL_STATE.ERROR = 'ERROR'; },{}],12:[function(_dereq_,module,exports){ module.exports = { /** * Choose the server's state over the client's **/ REMOTE_WINS: function( record, remoteValue, remoteVersion, callback ) { callback( null, remoteValue ); }, /** * Choose the local state over the server's **/ LOCAL_WINS: function( record, remoteValue, remoteVersion, callback ) { callback( null, record.get() ); } }; },{}],13:[function(_dereq_,module,exports){ var MERGE_STRATEGIES = _dereq_('./constants/merge-strategies'); module.exports = { /** * @param {Number} heartBeatInterval How often you expect the heartbeat to be sent. If two heatbeats are missed * in a row the client will consider the server to have disconnected and will close the connection in order to * establish a new one. */ heartbeatInterval: 30000, /** * @param {Boolean} recordPersistDefault Whether records should be * persisted by default. Can be overwritten * for individual records when calling getRecord( name, persist ); */ recordPersistDefault: true, /** * @param {Number} reconnectIntervalIncrement Specifies the number of milliseconds by which the time until * the next reconnection attempt will be incremented after every * unsuccesful attempt. * E.g. for 1500: if the connection is lost, the client will attempt to reconnect * immediatly, if that fails it will try again after 1.5 seconds, if that fails * it will try again after 3 seconds and so on */ reconnectIntervalIncrement: 4000, /** * @param {Number} maxReconnectInterval Specifies the maximum number of milliseconds for the reconnectIntervalIncrement * The amount of reconnections will reach this value * then reconnectIntervalIncrement will be ignored. */ maxReconnectInterval: 180000, /** * @param {Number} maxReconnectAttempts The number of reconnection attempts until the client gives * up and declares the connection closed */ maxReconnectAttempts: 5, /** * @param {Number} rpcAckTimeout The number of milliseconds after which a rpc will create an error if * no Ack-message has been received */ rpcAckTimeout: 6000, /** * @param {Number} rpcResponseTimeout The number of milliseconds after which a rpc will create an error if * no response-message has been received */ rpcResponseTimeout: 10000, /** * @param {Number} subscriptionTimeout The number of milliseconds that can pass after providing/unproviding a RPC or subscribing/unsubscribing/ * listening to a record before an error is thrown */ subscriptionTimeout: 2000, /** * @param {Number} maxMessagesPerPacket If the implementation tries to send a large number of messages at the same * time, the deepstream client will try to split them into smaller packets and send * these every <timeBetweenSendingQueuedPackages> ms. * * This parameter specifies the number of messages after which deepstream sends the * packet and queues the remaining messages. Set to Infinity to turn the feature off. * */ maxMessagesPerPacket: 100, /** * @param {Number} timeBetweenSendingQueuedPackages Please see description for maxMessagesPerPacket. Sets the time in ms. */ timeBetweenSendingQueuedPackages: 16, /** * @param {Number} recordReadAckTimeout The number of milliseconds from the moment client.record.getRecord() is called * until an error is thrown since no ack message has been received. */ recordReadAckTimeout: 1000, /** * @param {Number} recordReadTimeout The number of milliseconds from the moment client.record.getRecord() is called * until an error is thrown since no data has been received. */ recordReadTimeout: 3000, /** * @param {Number} recordDeleteTimeout The number of milliseconds from the moment record.delete() is called * until an error is thrown since no delete ack message had been received. Please * take into account that the deletion is only complete after the record has been * deleted from both cache and storage */ recordDeleteTimeout: 3000, /** * @param {String} path path to connect to */ path: '/deepstream', /** * @param {Function} mergeStrategy This provides the default strategy used to deal with merge conflicts. * If the merge strategy is not succesfull it will set an error, else set the * returned data as the latest revision. This can be overriden on a per record * basis by setting the `setMergeStrategy`. */ mergeStrategy: MERGE_STRATEGIES.REMOTE_WINS, /** * @param {Boolean} recordDeepCopy Setting to false disabled deepcopying of record data * when provided via `get()` in a `subscribe` callback. This * improves speed at the expense of the user having to ensure * object immutability. */ recordDeepCopy: true, /** * @param {Object} nodeSocketOptions Options to pass to the websocket constructor in node. * @default null * @see https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketaddress-protocols-options */ nodeSocketOptions: null }; },{"./constants/merge-strategies":12}],14:[function(_dereq_,module,exports){ var messageBuilder = _dereq_( '../message/message-builder' ), messageParser = _dereq_( '../message/message-parser' ), AckTimeoutRegistry = _dereq_( '../utils/ack-timeout-registry' ), ResubscribeNotifier = _dereq_( '../utils/resubscribe-notifier' ), C = _dereq_( '../constants/constants' ), Listener = _dereq_( '../utils/listener' ), EventEmitter = _dereq_( 'component-emitter' ); /** * This class handles incoming and outgoing messages in relation * to deepstream events. It basically acts like an event-hub that's * replicated across all connected clients. * * @param {Object} options deepstream options * @param {Connection} connection * @param {Client} client * @public * @constructor */ var EventHandler = function( options, connection, client ) { this._options = options; this._connection = connection; this._client = client; this._emitter = new EventEmitter(); this._listener = {}; this._ackTimeoutRegistry = new AckTimeoutRegistry( client, C.TOPIC.EVENT, this._options.subscriptionTimeout ); this._resubscribeNotifier = new ResubscribeNotifier( this._client, this._resubscribe.bind( this ) ); }; /** * Subscribe to an event. This will receive both locally emitted events * as well as events emitted by other connected clients. * * @param {String} name * @param {Function} callback * * @public * @returns {void} */ EventHandler.prototype.subscribe = function( name, callback ) { if ( typeof name !== 'string' || name.length === 0 ) { throw new Error( 'invalid argument name' ); } if ( typeof callback !== 'function' ) { throw new Error( 'invalid argument callback' ); } if( !this._emitter.hasListeners( name ) ) { this._ackTimeoutRegistry.add( name, C.ACTIONS.SUBSCRIBE ); this._connection.sendMsg( C.TOPIC.EVENT, C.ACTIONS.SUBSCRIBE, [ name ] ); } this._emitter.on( name, callback ); }; /** * Removes a callback for a specified event. If all callbacks * for an event have been removed, the server will be notified * that the client is unsubscribed as a listener * * @param {String} name * @param {Function} callback * * @public * @returns {void} */ EventHandler.prototype.unsubscribe = function( name, callback ) { if ( typeof name !== 'string' || name.length === 0 ) { throw new Error( 'invalid argument name' ); } if ( callback !== undefined && typeof callback !== 'function' ) { throw new Error( 'invalid argument callback' ); } this._emitter.off( name, callback ); if( !this._emitter.hasListeners( name ) ) { this._ackTimeoutRegistry.add( name, C.ACTIONS.UNSUBSCRIBE ); this._connection.sendMsg( C.TOPIC.EVENT, C.ACTIONS.UNSUBSCRIBE, [ name ] ); } }; /** * Emits an event locally and sends a message to the server to * broadcast the event to the other connected clients * * @param {String} name * @param {Mixed} data will be serialized and deserialized to its original type. * * @public * @returns {void} */ EventHandler.prototype.emit = function( name, data ) { if ( typeof name !== 'string' || name.length === 0 ) { throw new Error( 'invalid argument name' ); } this._connection.sendMsg( C.TOPIC.EVENT, C.ACTIONS.EVENT, [ name, messageBuilder.typed( data ) ] ); this._emitter.emit( name, data ); }; /** * Allows to listen for event subscriptions made by this or other clients. This * is useful to create "active" data providers, e.g. providers that only provide * data for a particular event if a user is actually interested in it * * @param {String} pattern A combination of alpha numeric characters and wildcards( * ) * @param {Function} callback * * @public * @returns {void} */ EventHandler.prototype.listen = function( pattern, callback ) { if ( typeof pattern !== 'string' || pattern.length === 0 ) { throw new Error( 'invalid argument pattern' ); } if ( typeof callback !== 'function' ) { throw new Error( 'invalid argument callback' ); } if( this._listener[ pattern ] && !this._listener[ pattern ].destroyPending ) { return this._client._$onError( C.TOPIC.EVENT, C.EVENT.LISTENER_EXISTS, pattern ); } else if( this._listener[ pattern ] ) { this._listener[ pattern ].destroy(); } this._listener[ pattern ] = new Listener( C.TOPIC.EVENT, pattern, callback, this._options, this._client, this._connection ); }; /** * Removes a listener that was previously registered with listenForSubscriptions * * @param {String} pattern A combination of alpha numeric characters and wildcards( * ) * @param {Function} callback * * @public * @returns {void} */ EventHandler.prototype.unlisten = function( pattern ) { if ( typeof pattern !== 'string' || pattern.length === 0 ) { throw new Error( 'invalid argument pattern' ); } var listener = this._listener[ pattern ]; if( listener && !listener.destroyPending ) { listener.sendDestroy(); } else if( this._listener[ pattern ] ) { this._ackTimeoutRegistry.add( pattern, C.EVENT.UNLISTEN ); this._listener[ pattern ].destroy(); delete this._listener[ pattern ]; } else { this._client._$onError( C.TOPIC.RECORD, C.EVENT.NOT_LISTENING, pattern ); } }; /** * Handles incoming messages from the server * * @param {Object} message parsed deepstream message * * @package private * @returns {void} */ EventHandler.prototype._$handle = function( message ) { var name = message.data[ message.action === C.ACTIONS.ACK ? 1 : 0 ]; if( message.action === C.ACTIONS.EVENT ) { processed = true; if( message.data && message.data.length === 2 ) { this._emitter.emit( name, messageParser.convertTyped( message.data[ 1 ], this._client ) ); } else { this._emitter.emit( name ); } return; } if( message.action === C.ACTIONS.ACK && message.data[ 0 ] === C.ACTIONS.UNLISTEN && this._listener[ name ] && this._listener[ name ].destroyPending ) { this._listener[ name ].destroy(); delete this._listener[ name ]; return; } else if( this._listener[ name ] ) { processed = true; this._listener[ name ]._$onMessage( message ); return; } else if( message.action === C.ACTIONS.SUBSCRIPTION_FOR_PATTERN_REMOVED ) { // An unlisten ACK was received before an PATTERN_REMOVED which is a valid case return; } else if( message.action === C.ACTIONS.SUBSCRIPTION_HAS_PROVIDER ) { // record can receive a HAS_PROVIDER after discarding the record return; } if( message.action === C.ACTIONS.ACK ) { this._ackTimeoutRegistry.clear( message ); return; } if( message.action === C.ACTIONS.ERROR ) { if (message.data[0] === C.EVENT.MESSAGE_DENIED){ this._ackTimeoutRegistry.remove( message.data[1], message.data[2] ); } else if ( message.data[0] === C.EVENT.NOT_SUBSCRIBED ){ this._ackTimeoutRegistry.remove( message.data[1], C.ACTIONS.UNSUBSCRIBE ); } message.processedError = true; this._client._$onError( C.TOPIC.EVENT, message.data[ 0 ], message.data[ 1 ] ); return; } this._client._$onError( C.TOPIC.EVENT, C.EVENT.UNSOLICITED_MESSAGE, name ); }; /** * Resubscribes to events when connection is lost * * @package private * @returns {void} */ EventHandler.prototype._resubscribe = function() { var callbacks = this._emitter._callbacks; for( var eventName in callbacks ) { this._connection.sendMsg( C.TOPIC.EVENT, C.ACTIONS.SUBSCRIBE, [ eventName ] ); } }; module.exports = EventHandler; },{"../constants/constants":11,"../message/message-builder":16,"../message/message-parser":17,"../utils/ack-timeout-registry":27,"../utils/listener":28,"../utils/resubscribe-notifier":29,"component-emitter":2}],15:[function(_dereq_,module,exports){ (function (global){ var BrowserWebSocket = global.WebSocket || global.MozWebSocket, NodeWebSocket = _dereq_( 'ws' ), messageParser = _dereq_( './message-parser' ), messageBuilder = _dereq_( './message-builder' ), utils = _dereq_( '../utils/utils' ), C = _dereq_( '../constants/constants' ); /** * Establishes a connection to a deepstream server using websockets * * @param {Client} client * @param {String} url Short url, e.g. <host>:<port>. Deepstream works out the protocol * @param {Object} options connection options * * @constructor */ var Connection = function( client, url, options ) { this._client = client; this._options = options; this._authParams = null; this._authCallback = null; this._deliberateClose = false; this._redirecting = false; this._tooManyAuthAttempts = false; this._connectionAuthenticationTimeout = false; this._challengeDenied = false; this._queuedMessages = []; this._reconnectTimeout = null; this._reconnectionAttempt = 0; this._currentPacketMessageCount = 0; this._sendNextPacketTimeout = null; this._currentMessageResetTimeout = null; this._endpoint = null; this._lastHeartBeat = null; this._heartbeatInterval = null; this._originalUrl = utils.parseUrl( url, this._options.path ); this._url = this._originalUrl; this._state = C.CONNECTION_STATE.CLOSED; this._createEndpoint(); }; /** * Returns the current connection state. * (One of constants.CONNECTION_STATE) * * @public * @returns {String} connectionState */ Connection.prototype.getState = function() { return this._state; }; /** * Sends the specified authentication parameters * to the server. Can be called up to <maxAuthAttempts> * times for the same connection. * * @param {Object} authParams A map of user defined auth parameters. E.g. { username:<String>, password:<String> } * @param {Function} callback A callback that will be invoked with the authenticationr result * * @public * @returns {void} */ Connection.prototype.authenticate = function( authParams, callback ) { this._authParams = authParams; this._authCallback = callback; if( this._tooManyAuthAttempts || this._challengeDenied || this._connectionAuthenticationTimeout ) { this._client._$onError( C.TOPIC.ERROR, C.EVENT.IS_CLOSED, 'this client\'s connection was closed' ); return; } else if( this._deliberateClose === true && this._state === C.CONNECTION_STATE.CLOSED ) { this._createEndpoint(); this._deliberateClose = false; return; } if( this._state === C.CONNECTION_STATE.AWAITING_AUTHENTICATION ) { this._sendAuthParams(); } }; /** * High level send message method. Creates a deepstream message * string and invokes the actual send method. * * @param {String} topic One of C.TOPIC * @param {String} action One of C.ACTIONS * @param {[Mixed]} data Date that will be added to the message. Primitive values will * be appended directly, objects and arrays will be serialized as JSON * * @private * @returns {void} */ Connection.prototype.sendMsg = function( topic, action, data ) { this.send( messageBuilder.getMsg( topic, action, data ) ); }; /** * Main method for sending messages. Doesn't send messages instantly, * but instead achieves conflation by adding them to the message * buffer that will be drained on the next tick * * @param {String} message deepstream message * * @public * @returns {void} */ Connection.prototype.send = function( message ) { this._queuedMessages.push( message ); this._currentPacketMessageCount++; if( this._currentMessageResetTimeout === null ) { this._currentMessageResetTimeout = utils.nextTick( this._resetCurrentMessageCount.bind( this ) ); } if( this._state === C.CONNECTION_STATE.OPEN && this._queuedMessages.length < this._options.maxMessagesPerPacket && this._currentPacketMessageCount < this._options.maxMessagesPerPacket ) { this._sendQueuedMessages(); } else if( this._sendNextPacketTimeout === null ) { this._queueNextPacket(); } }; /** * Closes the connection. Using this method * sets a _deliberateClose flag that will prevent the client from * reconnecting. * * @public * @returns {void} */ Connection.prototype.close = function() { clearInterval( this._heartbeatInterval ); this._deliberateClose = true; this._endpoint.close(); }; /** * Creates the endpoint to connect to using the url deepstream * was initialised with. * * @private * @returns {void} */ Connection.prototype._createEndpoint = function() { this._endpoint = BrowserWebSocket ? new BrowserWebSocket( this._url ) : new NodeWebSocket( this._url , this._options.nodeSocketOptions ) ; this._endpoint.onopen = this._onOpen.bind( this ); this._endpoint.onerror = this._onError.bind( this ); this._endpoint.onclose = this._onClose.bind( this ); this._endpoint.onmessage = this._onMessage.bind( this ); }; /** * When the implementation tries to send a large * number of messages in one execution thread, the first * <maxMessagesPerPacket> are send straight away. * * _currentPacketMessageCount keeps track of how many messages * went into that first packet. Once this number has been exceeded * the remaining messages are written to a queue and this message * is invoked on a timeout to reset the count. * * @private * @returns {void} */ Connection.prototype._resetCurrentMessageCount = function() { this._currentPacketMessageCount = 0; this._currentMessageResetTimeout = null; }; /** * Concatenates the messages in the current message queue * and sends them as a single package. This will also * empty the message queue and conclude the send process. * * @private * @returns {void} */ Connection.prototype._sendQueuedMessages = function() { if( this._state !== C.CONNECTION_STATE.OPEN || this._endpoint.readyState !== this._endpoint.OPEN ) { return; } if( this._queuedMessages.length === 0 ) { this._sendNextPacketTimeout = null; return; } var message = this._queuedMessages.splice( 0, this._options.maxMessagesPerPacket ).join( '' ); if( this._queuedMessages.length !== 0 ) { this._queueNextPacket(); } else { this._sendNextPacketTimeout = null; } this._submit( message ); }; /** * Sends a message to over the endpoint connection directly * * Will generate a connection error if the websocket was closed * prior to an onclose event. * * @private * @returns {void} */ Connection.prototype._submit = function( message ) { if( this._endpoint.readyState === this._endpoint.OPEN ) { this._endpoint.send( message ); } else { this._onError( 'Tried to send message on a closed websocket connection' ); } } /** * Schedules the next packet whilst the connection is under * heavy load. * * @private * @returns {void} */ Connection.prototype._queueNextPacket = function() { var fn = this._sendQueuedMessages.bind( this ), delay = this._options.timeBetweenSendingQueuedPackages; this._sendNextPacketTimeout = setTimeout( fn, delay ); }; /** * Sends authentication params to the server. Please note, this * doesn't use the queued message mechanism, but rather sends the message directly * * @private * @returns {void} */ Connection.prototype._sendAuthParams = function() { this._setState( C.CONNECTION_STATE.AUTHENTICATING ); var authMessage = messageBuilder.getMsg( C.TOPIC.AUTH, C.ACTIONS.REQUEST, [ this._authParams ] ); this._submit( authMessage ); }; /** * Ensures that a heartbeat was not missed more than once, otherwise it considers the connection * to have been lost and closes it for reconnection. * @return {void} */ Connection.prototype._checkHeartBeat = function() { var heartBeatTolerance = this._options.heartbeatInterval * 2; if( Date.now() - this._lastHeartBeat > heartBeatTolerance ) { clearInterval( this._heartbeatInterval ); this._endpoint.close(); this._onError( 'Two connections heartbeats missed successively' ); } }; /** * Will be invoked once the connection is established. The client * can't send messages yet, and needs to get a connection ACK or REDIRECT * from the server before authenticating * * @private * @returns {void} */ Connection.prototype._onOpen = function() { this._clearReconnect(); this._lastHeartBeat = Date.now(); this._heartbeatInterval = utils.setInterval( this._checkHeartBeat.bind( this ), this._options.heartbeatInterval ); this._setState( C.CONNECTION_STATE.AWAITING_CONNECTION ); }; /** * Callback for generic connection errors. Forwards * the error to the client. * * The connection is considered broken once this method has been * invoked. * * @param {String|Error} error connection error * * @private * @returns {void} */ Connection.prototype._onError = function( error ) { clearInterval( this._heartbeatInterval ); this._setState( C.CONNECTION_STATE.ERROR ); /* * If the implementation isn't listening on the error event this will throw * an error. So let's defer it to allow the reconnection to kick in. */ setTimeout(function(){ var msg; if( error.code === 'ECONNRESET' || error.code === 'ECONNREFUSED' ) { msg = 'Can\'t connect! Deepstream server unreachable on ' + this._originalUrl; } else { msg = error.toString(); } this._client._$onError( C.TOPIC.CONNECTION, C.EVENT.CONNECTION_ERROR, msg ); }.bind( this ), 1); }; /** * Callback when the connection closes. This might have been a deliberate * close triggered by the client or the result of the connection getting * lost. * * In the latter case the client will try to reconnect using the configured * strategy. * * @private * @returns {void} */ Connection.prototype._onClose = function() { clearInterval( this._heartbeatInterval ); if( this._redirecting === true ) { this._redirecting = false; this._createEndpoint(); } else if( this._deliberateClose === true ) { this._setState( C.CONNECTION_STATE.CLOSED ); } else { this._tryReconnect(); } }; /** * Callback for messages received on the connection. * * @param {String} message deepstream message * * @private * @returns {void} */ Connection.prototype._onMessage = function( message ) { var parsedMessages = messageParser.parse( message.data, this._client ), i; for( i = 0; i < parsedMessages.length; i++ ) { if( parsedMessages[ i ] === null ) { continue; } else if( parsedMessages[ i ].topic === C.TOPIC.CONNECTION ) { this._handleConnectionResponse( parsedMessages[ i ] ); } else if( parsedMessages[ i ].topic === C.TOPIC.AUTH ) { this._handleAuthResponse( parsedMessages[ i ] ); } else { this._client._$onMessage( parsedMessages[ i ] ); } } }; /** * The connection response will indicate whether the deepstream connection * can be used or if it should be forwarded to another instance. This * allows us to introduce load-balancing if needed. * * If authentication parameters are already provided this will kick of * authentication immediately. The actual 'open' event won't be emitted * by the client until the authentication is successful. * * If a challenge is recieved, the user will send the url to the server * in response to get the appropriate redirect. If the URL is invalid the * server will respond with a REJECTION resulting in the client connection * being permanently closed. * * If a redirect is recieved, this connection is closed and updated with * a connection to the url supplied in the message. * * @param {Object} message parsed connection message * * @private * @returns {void} */ Connection.prototype._handleConnectionResponse = function( message ) { var data; if( message.action === C.ACTIONS.PING ) { this._lastHeartBeat = Date.now(); this._submit( messageBuilder.getMsg( C.TOPIC.CONNECTION, C.ACTIONS.PONG ) ); } else if( message.action === C.ACTIONS.ACK ) { this._setState( C.CONNECTION_STATE.AWAITING_AUTHENTICATION ); if( this._authParams ) { this._sendAuthParams(); } } else if( message.action === C.ACTIONS.CHALLENGE ) { this._setState( C.CONNECTION_STATE.CHALLENGING ); this._submit( messageBuilder.getMsg( C.TOPIC.CONNECTION, C.ACTIONS.CHALLENGE_RESPONSE, [ this._originalUrl ] ) ); } else if( message.action === C.ACTIONS.REJECTION ) { this._challengeDenied = true; this.close(); } else if( message.action === C.ACTIONS.REDIRECT ) { this._url = message.data[ 0 ]; this._redirecting = true; this._endpoint.close(); } else if( message.action === C.ACTIONS.ERROR ) { if( message.data[ 0 ] === C.EVENT.CONNECTION_AUTHENTICATION_TIMEOUT ) { this._deliberateClose = true; this._connectionAuthenticationTimeout = true; this._client._$onError( C.TOPIC.CONNECTION, message.data[ 0 ], message.data[ 1 ] ); } } }; /** * Callback for messages received for the AUTH topic. If * the authentication was successful this method will * open the connection and send all messages that the client * tried to send so far. * * @param {Object} message parsed auth message * * @private * @returns {void} */ Connection.prototype._handleAuthResponse = function( message ) { var data; if( message.action === C.ACTIONS.ERROR ) { if( message.data[ 0 ] === C.EVENT.TOO_MANY_AUTH_ATTEMPTS ) { this._deliberateClose = true; this._tooManyAuthAttempts = true; } else { this._setState( C.CONNECTION_STATE.AWAITING_AUTHENTICATION ); } if( this._authCallback ) { this._authCallback( false, this._getAuthData( message.data[ 1 ] ) ); } } else if( message.action === C.ACTIONS.ACK ) { this._setState( C.CONNECTION_STATE.OPEN ); if( this._authCallback ) { this._authCallback( true, this._getAuthData( message.data[ 0 ] ) ); } this._sendQueuedMessages(); } }; /** * Checks if data is present with login ack and converts it * to the correct type * * @param {Object} message parsed and validated deepstream message * * @private * @returns {object} */ Connection.prototype._getAuthData = function( data ) { if( data === undefined ) { return null; } else { return messageParser.convertTyped( data, this._client ); } }; /** * Updates the connection state and emits the * connectionStateChanged event on the client * * @private * @returns {void} */ Connection.prototype._setState = function( state ) { this._state = state; this._client.emit( C.EVENT.CONNECTION_STATE_CHANGED, state ); }; /** * If the connection drops or is closed in error this * method schedules increasing reconnection intervals * * If the number of failed reconnection attempts exceeds * options.maxReconnectAttempts the connection is closed * * @private * @returns {void} */ Connection.prototype._tryReconnect = function() { if( this._reconnectTimeout !== null ) { return; } if( this._reconnectionAttempt < this._options.maxReconnectAttempts ) { this._setState( C.CONNECTION_STATE.RECONNECTING ); this._reconnectTimeout = setTimeout( this._tryOpen.bind( this ), Math.min( this._options.maxReconnectInterval, this._options.reconnectIntervalIncrement * this._reconnectionAttempt ) ); this._reconnectionAttempt++; } else { this._clearReconnect(); this.close(); this._client.emit( C.MAX_RECONNECTION_ATTEMPTS_REACHED, this._reconnectionAttempt ); } }; /** * Attempts to open a errourosly closed connection * * @private * @returns {void} */ Connection.prototype._tryOpen = function() { if( this._originalUrl !== this._url ) { this._url = this._originalUrl; } this._createEndpoint(); this._reconnectTimeout = null; }; /** * Stops all further reconnection attempts, * either because the connection is open again * or because the maximal number of reconnection * attempts has been exceeded * * @private * @returns {void} */ Connection.prototype._clearReconnect = function() { clearTimeout( this._reconnectTimeout ); this._reconnectTimeout = null; this._reconnectionAttempt = 0; }; module.exports = Connection; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../constants/constants":11,"../utils/utils":31,"./message-builder":16,"./message-parser":17,"ws":1}],16:[function(_dereq_,module,exports){ var C = _dereq_( '../constants/constants' ), SEP = C.MESSAGE_PART_SEPERATOR; /** * Creates a deepstream message string, based on the * provided parameters * * @param {String} topic One of CONSTANTS.TOPIC * @param {String} action One of CONSTANTS.ACTIONS * @param {Array} data An array of strings or JSON-serializable objects * * @returns {String} deepstream message string */ exports.getMsg = function( topic, action, data ) { if( data && !( data instanceof Array ) ) { throw new Error( 'data must be an array' ); } var sendData = [ topic, action ], i; if( data ) { for( i = 0; i < data.length; i++ ) { if( typeof data[ i ] === 'object' ) { sendData.push( JSON.stringify( data[ i ] ) ); } else { sendData.push( data[ i ] ); } } } return sendData.join( SEP ) + C.MESSAGE_SEPERATOR; }; /** * Converts a serializable value into its string-representation and adds * a flag that provides instructions on how to deserialize it. * * Please see messageParser.convertTyped for the counterpart of this method * * @param {Mixed} value * * @public * @returns {String} string representation of the value */ exports.typed = function( value ) { var type = typeof value; if( type === 'string' ) { return C.TYPES.STRING + value; } if( value === null ) { return C.TYPES.NULL; } if( type === 'object' ) { return C.TYPES.OBJECT + JSON.stringify( value ); } if( type === 'number' ) { return C.TYPES.NUMBER + value.toString(); } if( value === true ) { return C.TYPES.TRUE; } if( value === false ) { return C.TYPES.FALSE; } if( value === undefined ) { return C.TYPES.UNDEFINED; } throw new Error( 'Can\'t serialize type ' + value ); }; },{"../constants/constants":11}],17:[function(_dereq_,module,exports){ var C = _dereq_( '../constants/constants' ); /** * Parses ASCII control character seperated * message strings into digestable maps * * @constructor */ var MessageParser = function() { this._actions = this._getActions(); }; /** * Main interface method. Receives a raw message * string, containing one or more messages * and returns an array of parsed message objects * or null for invalid messages * * @param {String} message raw message * * @public * * @returns {Array} array of parsed message objects * following the format * { * raw: <original message string> * topic: <string> * action: <string - shortcode> * data: <array of strings> * } */ MessageParser.prototype.parse = function( message, client ) { var parsedMessages = [], rawMessages = message.split( C.MESSAGE_SEPERATOR ), i; for( i = 0; i < rawMessages.length; i++ ) { if( rawMessages[ i ].length > 2 ) { parsedMessages.push( this._parseMessage( rawMessages[ i ], client ) ); } } return parsedMessages; }; /** * Deserializes values created by MessageBuilder.typed to * their original format * * @param {String} value * * @public * @returns {Mixed} original value */ MessageParser.prototype.convertTyped = function( value, client ) { var type = value.charAt( 0 ); if( type === C.TYPES.STRING ) { return value.substr( 1 ); } if( type === C.TYPES.OBJECT ) { try { return JSON.parse( value.substr( 1 ) ); } catch( e ) { client._$onError( C.TOPIC.ERROR, C.EVENT.MESSAGE_PARSE_ERROR, e.toString() + '(' + value + ')' ); return; } } if( type === C.TYPES.NUMBER ) { return parseFloat( value.substr( 1 ) ); } if( type === C.TYPES.NULL ) { return null; } if( type === C.TYPES.TRUE ) { return true; } if( type === C.TYPES.FALSE ) { return false; } if( type === C.TYPES.UNDEFINED ) { return undefined; } client._$onError( C.TOPIC.ERROR, C.EVENT.MESSAGE_PARSE_ERROR, 'UNKNOWN_TYPE (' + value + ')' ); }; /** * Turns the ACTION:SHORTCODE constants map * around to facilitate shortcode lookup * * @private * * @returns {Object} actions */ MessageParser.prototype._getActions = function() { var actions = {}, key; for( key in C.ACTIONS ) { actions[ C.ACTIONS[ key ] ] = key; } return actions; }; /** * Parses an individual message (as oposed to a * block of multiple messages as is processed by .parse()) * * @param {String} message * * @private * * @returns {Object} parsedMessage */ MessageParser.prototype._parseMessage = function( message, client ) { var parts = message.split( C.MESSAGE_PART_SEPERATOR ), messageObject = {}; if( parts.length < 2 ) { message.processedError = true; client._$onError( C.TOPIC.ERROR, C.EVENT.MESSAGE_PARSE_ERROR, 'Insufficiant message parts' ); return null; } if( this._actions[ parts[ 1 ] ] === undefined ) { message.processedError = true; client._$onError( C.TOPIC.ERROR, C.EVENT.MESSAGE_PARSE_ERROR, 'Unknown action ' + parts[ 1 ] ); return null; } messageObject.raw = message; messageObject.topic = parts[ 0 ]; messageObject.action = parts[ 1 ]; messageObject.data = parts.splice( 2 ); return messageObject; }; module.exports = new MessageParser(); },{"../constants/constants":11}],18:[function(_dereq_,module,exports){ var EventEmitter = _dereq_( 'component-emitter' ), C = _dereq_( '../constants/constants' ), AckTimeoutRegistry = _dereq_( '../utils/ack-timeout-registry' ), messageParser = _dereq_( '../message/message-parser' ), messageBuilder = _dereq_( '../message/message-builder' ), ResubscribeNotifier = _dereq_( '../utils/resubscribe-notifier' ); /** * The main class for presence in deepstream * * Provides the presence interface and handles incoming messages * on the presence topic * * @param {Object} options deepstream configuration options * @param {Connection} connection * @param {Client} client * * @constructor * @public */ var PresenceHandler = function( options, connection, client ) { this._options = options; this._connection = connection; this._client = client; this._emitter = new EventEmitter(); this._ackTimeoutRegistry = new AckTimeoutRegistry( client, C.TOPIC.PRESENCE, this._options.subscriptionTimeout ); this._resubscribeNotifier = new ResubscribeNotifier( this._client, this._resubscribe.bind( this ) ); }; /** * Queries for clients logged into deepstream. * * @param {Function} callback Will be invoked with an array of clients * * @public * @returns {void} */ PresenceHandler.prototype.getAll = function( callback ) { if( !this._emitter.hasListeners( C.ACTIONS.QUERY ) ) { // At least one argument is required for a message to be permissionable this._connection.sendMsg( C.TOPIC.PRESENCE, C.ACTIONS.QUERY, [ C.ACTIONS.QUERY ] ); } this._emitter.once( C.ACTIONS.QUERY, callback ); }; /** * Subscribes to client logins or logouts in deepstream * * @param {Function} callback Will be invoked with the username of a client, * and a boolean to indicate if it was a login or * logout event * @public * @returns {void} */ PresenceHandler.prototype.subscribe = function( callback ) { if ( callback !== undefined && typeof callback !== 'function' ) { throw new Error( 'invalid argument callback' ); } if( !this._emitter.hasListeners( C.TOPIC.PRESENCE ) ) { this._ackTimeoutRegistry.add( C.TOPIC.PRESENCE, C.ACTIONS.SUBSCRIBE ); this._connection.sendMsg( C.TOPIC.PRESENCE, C.ACTIONS.SUBSCRIBE, [ C.ACTIONS.SUBSCRIBE ] ); } this._emitter.on( C.TOPIC.PRESENCE, callback ); }; /** * Removes a callback for a specified presence event * * @param {Function} callback The callback to unregister via {PresenceHandler#unsubscribe} * * @public * @returns {void} */ PresenceHandler.prototype.unsubscribe = function( callback ) { if ( callback !== undefined && typeof callback !== 'function' ) { throw new Error( 'invalid argument callback' ); } this._emitter.off( C.TOPIC.PRESENCE, callback ); if( !this._emitter.hasListeners( C.TOPIC.PRESENCE ) ) { this._ackTimeoutRegistry.add( C.TOPIC.PRESENCE, C.ACTIONS.UNSUBSCRIBE ); this._connection.sendMsg( C.TOPIC.PRESENCE, C.ACTIONS.UNSUBSCRIBE, [ C.ACTIONS.UNSUBSCRIBE ] ); } }; /** * Handles incoming messages from the server * * @param {Object} message parsed deepstream message * * @package private * @returns {void} */ PresenceHandler.prototype._$handle = function( message ) { if( message.action === C.ACTIONS.ERROR && message.data[ 0 ] === C.EVENT.MESSAGE_DENIED ) { this._ackTimeoutRegistry.remove( C.TOPIC.PRESENCE, message.data[ 1 ] ); message.processedError = true; this._client._$onError( C.TOPIC.PRESENCE, C.EVENT.MESSAGE_DENIED, message.data[ 1 ] ); } else if( message.action === C.ACTIONS.ACK ) { this._ackTimeoutRegistry.clear( message ); } else if( message.action === C.ACTIONS.PRESENCE_JOIN ) { this._emitter.emit( C.TOPIC.PRESENCE, message.data[ 0 ], true ); } else if( message.action === C.ACTIONS.PRESENCE_LEAVE ) { this._emitter.emit( C.TOPIC.PRESENCE, message.data[ 0 ], false ); } else if( message.action === C.ACTIONS.QUERY ) { this._emitter.emit( C.ACTIONS.QUERY, message.data ); } else { this._client._$onError( C.TOPIC.PRESENCE, C.EVENT.UNSOLICITED_MESSAGE, message.action ); } }; /** * Resubscribes to presence subscription when connection is lost * * @package private * @returns {void} */ PresenceHandler.prototype._resubscribe = function() { var callbacks = this._emitter._callbacks; if( callbacks && callbacks[ C.TOPIC.PRESENCE ] ) { this._connection.sendMsg( C.TOPIC.PRESENCE, C.ACTIONS.SUBSCRIBE, [ C.ACTIONS.SUBSCRIBE ] ); } }; module.exports = PresenceHandler; },{"../constants/constants":11,"../message/message-builder":16,"../message/message-parser":17,"../utils/ack-timeout-registry":27,"../utils/resubscribe-notifier":29,"component-emitter":2}],19:[function(_dereq_,module,exports){ var Record = _dereq_( './record' ), EventEmitter = _dereq_( 'component-emitter' ); /** * An AnonymousRecord is a record without a predefined name. It * acts like a wrapper around an actual record that can * be swapped out for another one whilst keeping all bindings intact. * * Imagine a customer relationship management system with a list of users * on the left and a user detail panel on the right. The user detail * panel could use the anonymous record to set up its bindings, yet whenever * a user is chosen from the list of existing users the anonymous record's * setName method is called and the detail panel will update to * show the selected user's details * * @param {RecordHandler} recordHandler * * @constructor */ var AnonymousRecord = function( recordHandler ) { this.name = null; this._recordHandler = recordHandler; this._record = null; this._subscriptions = []; this._proxyMethod( 'delete' ); this._proxyMethod( 'set' ); this._proxyMethod( 'discard' ); }; EventEmitter( AnonymousRecord.prototype ); /** * Proxies the actual record's get method. It is valid * to call get prior to setName - if no record exists, * the method returns undefined * * @param {[String]} path A json path. If non is provided, * the entire record is returned. * * @public * @returns {mixed} the value of path or the entire object */ AnonymousRecord.prototype.get = function( path ) { if( this._record === null ) { return undefined; } return this._record.get( path ); }; /** * Proxies the actual record's subscribe method. The same parameters * can be used. Can be called prior to setName(). Please note, triggerIfReady * will always be set to true to reflect changes in the underlying record. * * @param {[String]} path A json path. If non is provided, * it subscribes to changes for the entire record. * * @param {Function} callback A callback function that will be invoked whenever * the subscribed path or record updates * * @public * @returns {void} */ AnonymousRecord.prototype.subscribe = function() { var parameters = Record.prototype._normalizeArguments( arguments ); parameters.triggerNow = true; this._subscriptions.push( parameters ); if( this._record !== null ) { this._record.subscribe( parameters ); } }; /** * Proxies the actual record's unsubscribe method. The same parameters * can be used. Can be called prior to setName() * * @param {[String]} path A json path. If non is provided, * it subscribes to changes for the entire record. * * @param {Function} callback A callback function that will be invoked whenever * the subscribed path or record updates * * @public * @returns {void} */ AnonymousRecord.prototype.unsubscribe = function() { var parameters = Record.prototype._normalizeArguments( arguments ), subscriptions = [], i; for( i = 0; i < this._subscriptions.length; i++ ) { if( this._subscriptions[ i ].path !== parameters.path || this._subscriptions[ i ].callback !== parameters.callback ) { subscriptions.push( this._subscriptions[ i ] ); } } this._subscriptions = subscriptions; if( this._record !== null ) { this._record.unsubscribe( parameters ); } }; /** * Sets the underlying record the anonymous record is bound * to. Can be called multiple times. * * @param {String} recordName * * @public * @returns {void} */ AnonymousRecord.prototype.setName = function( recordName ) { this.name = recordName; var i; if( this._record !== null && !this._record.isDestroyed) { for( i = 0; i < this._subscriptions.length; i++ ) { this._record.unsubscribe( this._subscriptions[ i ] ); } this._record.discard(); } this._record = this._recordHandler.getRecord( recordName ); for( i = 0; i < this._subscriptions.length; i++ ) { this._record.subscribe( this._subscriptions[ i ] ); } this._record.whenReady( this.emit.bind( this, 'ready' ) ); this.emit( 'nameChanged', recordName ); }; /** * Adds the specified method to this method and forwards it * to _callMethodOnRecord * * @param {String} methodName * * @private * @returns {void} */ AnonymousRecord.prototype._proxyMethod = function( methodName ) { this[ methodName ] = this._callMethodOnRecord.bind( this, methodName ); }; /** * Invokes the specified method with the provided parameters on * the underlying record. Throws erros if the method is not * specified yet or doesn't expose the method in question * * @param {String} methodName * * @private * @returns {Mixed} the return value of the actual method */ AnonymousRecord.prototype._callMethodOnRecord = function( methodName ) { if( this._record === null ) { throw new Error( 'Can`t invoke ' + methodName + '. AnonymousRecord not initialised. Call setName first' ); } if( typeof this._record[ methodName ] !== 'function' ) { throw new Error( methodName + ' is not a method on the record' ); } var args = Array.prototype.slice.call( arguments, 1 ); return this._record[ methodName ].apply( this._record, args ); }; module.exports = AnonymousRecord; },{"./record":23,"component-emitter":2}],20:[function(_dereq_,module,exports){ var utils = _dereq_( '../utils/utils' ); var PARTS_REG_EXP = /([^\.\[\]\s]+)/g; var cache = Object.create( null ); /** * Returns the value of the path or * undefined if the path can't be resolved * * @public * @returns {Mixed} */ module.exports.get = function ( data, path, deepCopy ) { var tokens = tokenize( path ); for( var i = 0; i < tokens.length; i++ ) { if ( data === undefined ) { return undefined; } if ( typeof data !== 'object' ) { throw new Error( 'invalid data or path' ); } data = data[ tokens[ i ] ]; } return deepCopy !== false ? utils.deepCopy( data ) : data; }; /** * Sets the value of the path. If the path (or parts * of it) doesn't exist yet, it will be created * * @param {Mixed} value * * @public * @returns {Mixed} updated value */ module.exports.set = function( data, path, value, deepCopy ) { var tokens = tokenize( path ); if ( tokens.length === 0 ) { return patch( data, value, deepCopy ); } var oldValue = module.exports.get( data, path, false ); var newValue = patch( oldValue, value, deepCopy ); if ( newValue === oldValue ) { return data; } var result = utils.shallowCopy( data ); var node = result; for( var i = 0; i < tokens.length; i++ ) { if ( i === tokens.length - 1) { node[ tokens[ i ] ] = newValue; } else if( node[ tokens[ i ] ] !== undefined ) { node = node[ tokens[ i ] ] = utils.shallowCopy( node[ tokens[ i ] ] ); } else if( tokens[ i + 1 ] && !isNaN( tokens[ i + 1 ] ) ){ node = node[ tokens[ i ] ] = []; } else { node = node[ tokens[ i ] ] = Object.create( null ); } } return result; }; /** * Merge the new value into the old value * @param {Mixed} oldValue * @param {Mixed} newValue * @param {boolean} deepCopy * @return {Mixed} */ function patch( oldValue, newValue, deepCopy ) { var i; if ( utils.deepEquals( oldValue, newValue ) ) { return oldValue; } else if ( oldValue === null || newValue === null ) { return newValue; } else if ( Array.isArray( oldValue ) && Array.isArray( newValue ) ) { var arr = []; for ( i = 0; i < newValue.length; i++ ) { arr[ i ] = patch( oldValue[ i ], newValue[ i ], deepCopy ); } return arr; } else if ( !Array.isArray( newValue ) && typeof oldValue === 'object' && typeof newValue === 'object' ) { var props = Object.keys( newValue ); var obj = Object.create( null ); for ( i = 0; i < props.length; i++ ) { obj[ props[ i ] ] = patch( oldValue[ props[ i ] ], newValue[ props[ i ] ], deepCopy ); } return obj; } else { return deepCopy !== false ? utils.deepCopy( newValue ) : newValue; } } /** * Parses the path. Splits it into * keys for objects and indices for arrays. * * @returns Array of tokens */ function tokenize( path ) { if ( cache[ path ] ) { return cache[ path ]; } var parts = String(path) !== 'undefined' ? String( path ).match(PARTS_REG_EXP) : []; if ( !parts ) { throw new Error('invalid path ' + path) } return cache[ path ] = parts.map( function( part ) { return !isNaN( part ) ? parseInt( part, 10 ) : part; } ); }; },{"../utils/utils":31}],21:[function(_dereq_,module,exports){ var EventEmitter = _dereq_( 'component-emitter' ), Record = _dereq_( './record' ), C = _dereq_( '../constants/constants' ), ENTRY_ADDED_EVENT = 'entry-added', ENTRY_REMOVED_EVENT = 'entry-removed', ENTRY_MOVED_EVENT = 'entry-moved'; /** * A List is a specialised Record that contains * an Array of recordNames and provides a number * of convinience methods for interacting with them. * * @param {RecordHanlder} recordHandler * @param {String} name The name of the list * * @constructor */ var List = function( recordHandler, name, options ) { if ( typeof name !== 'string' || name.length === 0 ) { throw new Error( 'invalid argument name' ); } this._recordHandler = recordHandler; this._record = this._recordHandler.getRecord( name, options ); this._record._applyUpdate = this._applyUpdate.bind( this ); this._record.on( 'delete', this.emit.bind( this, 'delete' ) ); this._record.on( 'discard', this._onDiscard.bind( this ) ); this._record.on( 'ready', this._onReady.bind( this ) ); this.isDestroyed = this._record.isDestroyed; this.isReady = this._record.isReady; this.name = name; this._queuedMethods = []; this._beforeStructure = null; this._hasAddListener = null; this._hasRemoveListener = null; this._hasMoveListener = null; this.delete = this._record.delete.bind( this._record ); this.discard = this._record.discard.bind( this._record ); this.whenReady = this._record.whenReady.bind( this ); }; EventEmitter( List.prototype ); /** * Returns the array of list entries or an * empty array if the list hasn't been populated yet. * * @public * @returns {Array} entries */ List.prototype.getEntries = function() { var entries = this._record.get(); if( !( entries instanceof Array ) ) { return []; } return entries; }; /** * Returns true if the list is empty * * @public * @returns {Boolean} isEmpty */ List.prototype.isEmpty = function() { return this.getEntries().length === 0; }; /** * Updates the list with a new set of entries * * @public * @param {Array} entries */ List.prototype.setEntries = function( entries ) { var errorMsg = 'entries must be an array of record names', i; if( !( entries instanceof Array ) ) { throw new Error( errorMsg ); } for( i = 0; i < entries.length; i++ ) { if( typeof entries[ i ] !== 'string' ) { throw new Error( errorMsg ); } } if( this._record.isReady === false ) { this._queuedMethods.push( this.setEntries.bind( this, entries ) ); } else { this._beforeChange(); this._record.set( entries ); this._afterChange(); } }; /** * Removes an entry from the list * * @param {String} entry * @param {Number} [index] * * @public * @returns {void} */ List.prototype.removeEntry = function( entry, index ) { if( this._record.isReady === false ) { this._queuedMethods.push( this.removeEntry.bind( this, entry ) ); return; } var currentEntries = this._record.get(), hasIndex = this._hasIndex( index ), entries = [], i; for( i = 0; i < currentEntries.length; i++ ) { if( currentEntries[i] !== entry || ( hasIndex && index !== i ) ) { entries.push( currentEntries[i] ); } } this._beforeChange(); this._record.set( entries ); this._afterChange(); }; /** * Adds an entry to the list * * @param {String} entry * @param {Number} [index] * * @public * @returns {void} */ List.prototype.addEntry = function( entry, index ) { if( typeof entry !== 'string' ) { throw new Error( 'Entry must be a recordName' ); } if( this._record.isReady === false ) { this._queuedMethods.push( this.addEntry.bind( this, entry ) ); return; } var hasIndex = this._hasIndex( index ); var entries = this.getEntries(); if( hasIndex ) { entries.splice( index, 0, entry ); } else { entries.push( entry ); } this._beforeChange(); this._record.set( entries ); this._afterChange(); }; /** * Proxies the underlying Record's subscribe method. Makes sure * that no path is provided * * @public * @returns {void} */ List.prototype.subscribe = function() { var parameters = Record.prototype._normalizeArguments( arguments ); if( parameters.path ) { throw new Error( 'path is not supported for List.subscribe' ); } //Make sure the callback is invoked with an empty array for new records var listCallback = function( callback ) { callback( this.getEntries() ); }.bind( this, parameters.callback ); /** * Adding a property onto a function directly is terrible practice, * and we will change this as soon as we have a more seperate approach * of creating lists that doesn't have records default state. * * The reason we are holding a referencing to wrapped array is so that * on unsubscribe it can provide a reference to the actual method the * record is subscribed too. **/ parameters.callback.wrappedCallback = listCallback; parameters.callback = listCallback; this._record.subscribe( parameters ); }; /** * Proxies the underlying Record's unsubscribe method. Makes sure * that no path is provided * * @public * @returns {void} */ List.prototype.unsubscribe = function() { var parameters = Record.prototype._normalizeArguments( arguments ); if( parameters.path ) { throw new Error( 'path is not supported for List.unsubscribe' ); } parameters.callback = parameters.callback.wrappedCallback; this._record.unsubscribe( parameters ); }; /** * Listens for changes in the Record's ready state * and applies them to this list * * @private * @returns {void} */ List.prototype._onReady = function() { this.isReady = true; for( var i = 0; i < this._queuedMethods.length; i++ ) { this._queuedMethods[ i ](); } this.emit( 'ready' ); }; /** * Listens for the record discard event and applies * changes to list * * @private * @returns {void} */ List.prototype._onDiscard = function() { this.isDestroyed = true; this.emit( 'discard' ); }; /** * Proxies the underlying Record's _update method. Set's * data to an empty array if no data is provided. * * @param {null} path must (should :-)) be null * @param {Array} data * * @private * @returns {void} */ List.prototype._applyUpdate = function( message ) { if( message.action === C.ACTIONS.PATCH ) { throw new Error( 'PATCH is not supported for Lists' ); } if( message.data[ 2 ].charAt( 0 ) !== '[' ) { message.data[ 2 ] = '[]'; } this._beforeChange(); Record.prototype._applyUpdate.call( this._record, message ); this._afterChange(); }; /** * Validates that the index provided is within the current set of entries. * * @param {Number} index * * @private * @returns {Number} */ List.prototype._hasIndex = function( index ) { var hasIndex = false; var entries = this.getEntries(); if( index !== undefined ) { if( isNaN( index ) ) { throw new Error( 'Index must be a number' ); } if( index !== entries.length && ( index >= entries.length || index < 0 ) ) { throw new Error( 'Index must be within current entries' ); } hasIndex = true; } return hasIndex; }; /** * Establishes the current structure of the list, provided the client has attached any * add / move / remove listener * * This will be called before any change to the list, regardsless if the change was triggered * by an incoming message from the server or by the client * * @private * @returns {void} */ List.prototype._beforeChange = function() { this._hasAddListener = this.listeners( ENTRY_ADDED_EVENT ).length > 0; this._hasRemoveListener = this.listeners( ENTRY_REMOVED_EVENT ).length > 0; this._hasMoveListener = this.listeners( ENTRY_MOVED_EVENT ).length > 0; if( this._hasAddListener || this._hasRemoveListener || this._hasMoveListener ) { this._beforeStructure = this._getStructure(); } else { this._beforeStructure = null; } }; /** * Compares the structure of the list after a change to its previous structure and notifies * any add / move / remove listener. Won't do anything if no listeners are attached. * * @private * @returns {void} */ List.prototype._afterChange = function() { if( this._beforeStructure === null ) { return; } var after = this._getStructure(); var before = this._beforeStructure; var entry, i; if( this._hasRemoveListener ) { for( entry in before ) { for( i = 0; i < before[ entry ].length; i++ ) { if( after[ entry ] === undefined || after[ entry ][ i ] === undefined ) { this.emit( ENTRY_REMOVED_EVENT, entry, before[ entry ][ i ] ); } } } } if( this._hasAddListener || this._hasMoveListener ) { for( entry in after ) { if( before[ entry ] === undefined ) { for( i = 0; i < after[ entry ].length; i++ ) { this.emit( ENTRY_ADDED_EVENT, entry, after[ entry ][ i ] ); } } else { for( i = 0; i < after[ entry ].length; i++ ) { if( before[ entry ][ i ] !== after[ entry ][ i ] ) { if( before[ entry ][ i ] === undefined ) { this.emit( ENTRY_ADDED_EVENT, entry, after[ entry ][ i ] ); } else { this.emit( ENTRY_MOVED_EVENT, entry, after[ entry ][ i ] ); } } } } } } }; /** * Iterates through the list and creates a map with the entry as a key * and an array of its position(s) within the list as a value, e.g. * * { * 'recordA': [ 0, 3 ], * 'recordB': [ 1 ], * 'recordC': [ 2 ] * } * * @private * @returns {Array} structure */ List.prototype._getStructure = function() { var structure = {}; var i; var entries = this._record.get(); for( i = 0; i < entries.length; i++ ) { if( structure[ entries[ i ] ] === undefined ) { structure[ entries[ i ] ] = [ i ]; } else { structure[ entries[ i ] ].push( i ); } } return structure; }; module.exports = List; },{"../constants/constants":11,"./record":23,"component-emitter":2}],22:[function(_dereq_,module,exports){ var Record = _dereq_( './record' ), AnonymousRecord = _dereq_( './anonymous-record' ), List = _dereq_( './list' ), Listener = _dereq_( '../utils/listener' ), SingleNotifier = _dereq_( '../utils/single-notifier' ), C = _dereq_( '../constants/constants' ), messageParser = _dereq_( '../message/message-parser' ), EventEmitter = _dereq_( 'component-emitter' ); /** * A collection of factories for records. This class * is exposed as client.record * * @param {Object} options deepstream options * @param {Connection} connection * @param {Client} client */ var RecordHandler = function( options, connection, client ) { this._options = options; this._connection = connection; this._client = client; this._records = {}; this._lists = {}; this._listener = {}; this._destroyEventEmitter = new EventEmitter(); this._hasRegistry = new SingleNotifier( client, connection, C.TOPIC.RECORD, C.ACTIONS.HAS, this._options.recordReadTimeout ); this._snapshotRegistry = new SingleNotifier( client, connection, C.TOPIC.RECORD, C.ACTIONS.SNAPSHOT, this._options.recordReadTimeout ); }; /** * Returns an existing record or creates a new one. * * @param {String} name the unique name of the record * @param {[Object]} recordOptions A map of parameters for this particular record. * { persist: true } * * @public * @returns {Record} */ RecordHandler.prototype.getRecord = function( name, recordOptions ) { if( !this._records[ name ] ) { this._records[ name ] = new Record( name, recordOptions || {}, this._connection, this._options, this._client ); this._records[ name ].on( 'error', this._onRecordError.bind( this, name ) ); this._records[ name ].on( 'destroyPending', this._onDestroyPending.bind( this, name ) ); this._records[ name ].on( 'delete', this._removeRecord.bind( this, name ) ); this._records[ name ].on( 'discard', this._removeRecord.bind( this, name ) ); } this._records[ name ].usages++; return this._records[ name ]; }; /** * Returns an existing List or creates a new one. A list is a specialised * type of record that holds an array of recordNames. * * @param {String} name the unique name of the list * @param {[Object]} options A map of parameters for this particular list. * { persist: true } * * @public * @returns {List} */ RecordHandler.prototype.getList = function( name, options ) { if( !this._lists[ name ] ) { this._lists[ name ] = new List( this, name, options ); } else { this._records[ name ].usages++; } return this._lists[ name ]; }; /** * Returns an anonymous record. A anonymous record is effectively * a wrapper that mimicks the API of a record, but allows for the * underlying record to be swapped without loosing subscriptions etc. * * This is particularly useful when selecting from a number of similarly * structured records. E.g. a list of users that can be choosen from a list * * The only API difference to a normal record is an additional setName( name ) method. * * * @public * @returns {AnonymousRecord} */ RecordHandler.prototype.getAnonymousRecord = function() { return new AnonymousRecord( this ); }; /** * Allows to listen for record subscriptions made by this or other clients. This * is useful to create "active" data providers, e.g. providers that only provide * data for a particular record if a user is actually interested in it * * @param {String} pattern A combination of alpha numeric characters and wildcards( * ) * @param {Function} callback * * @public * @returns {void} */ RecordHandler.prototype.listen = function( pattern, callback ) { if ( typeof pattern !== 'string' || pattern.length === 0 ) { throw new Error( 'invalid argument pattern' ); } if ( typeof callback !== 'function' ) { throw new Error( 'invalid argument callback' ); } if( this._listener[ pattern ] && !this._listener[ pattern ].destroyPending ) { return this._client._$onError( C.TOPIC.RECORD, C.EVENT.LISTENER_EXISTS, pattern ); } if( this._listener[ pattern ] ) { this._listener[ pattern ].destroy(); } this._listener[ pattern ] = new Listener( C.TOPIC.RECORD, pattern, callback, this._options, this._client, this._connection ); }; /** * Removes a listener that was previously registered with listenForSubscriptions * * @param {String} pattern A combination of alpha numeric characters and wildcards( * ) * @param {Function} callback * * @public * @returns {void} */ RecordHandler.prototype.unlisten = function( pattern ) { if ( typeof pattern !== 'string' || pattern.length === 0 ) { throw new Error( 'invalid argument pattern' ); } var listener = this._listener[ pattern ]; if( listener && !listener.destroyPending ) { listener.sendDestroy(); } else if( this._listener[ pattern ] ) { this._listener[ pattern ].destroy(); delete this._listener[ pattern ]; } else { this._client._$onError( C.TOPIC.RECORD, C.EVENT.NOT_LISTENING, pattern ); } }; /** * Retrieve the current record data without subscribing to changes * * @param {String} name the unique name of the record * @param {Function} callback * * @public */ RecordHandler.prototype.snapshot = function( name, callback ) { if ( typeof name !== 'string' || name.length === 0 ) { throw new Error( 'invalid argument name' ); } if( this._records[ name ] && this._records[ name ].isReady ) { callback( null, this._records[ name ].get() ); } else { this._snapshotRegistry.request( name, callback ); } }; /** * Allows the user to query to see whether or not the record exists. * * @param {String} name the unique name of the record * @param {Function} callback * * @public */ RecordHandler.prototype.has = function( name, callback ) { if ( typeof name !== 'string' || name.length === 0 ) { throw new Error( 'invalid argument name' ); } if( this._records[ name ] ) { callback( null, true ); } else { this._hasRegistry.request( name, callback ); } }; /** * Will be called by the client for incoming messages on the RECORD topic * * @param {Object} message parsed and validated deepstream message * * @package private * @returns {void} */ RecordHandler.prototype._$handle = function( message ) { var name; if( message.action === C.ACTIONS.ERROR && ( message.data[ 0 ] !== C.EVENT.VERSION_EXISTS && message.data[ 0 ] !== C.ACTIONS.SNAPSHOT && message.data[ 0 ] !== C.ACTIONS.HAS && message.data[ 0 ] !== C.EVENT.MESSAGE_DENIED ) ) { message.processedError = true; this._client._$onError( C.TOPIC.RECORD, message.data[ 0 ], message.data[ 1 ] ); return; } if( message.action === C.ACTIONS.ACK || message.action === C.ACTIONS.ERROR ) { name = message.data[ 1 ]; /* * The following prevents errors that occur when a record is discarded or deleted and * recreated before the discard / delete ack message is received. * * A (presumably unsolvable) problem remains when a client deletes a record in the exact moment * between another clients creation and read message for the same record */ if( message.data[ 0 ] === C.ACTIONS.DELETE || message.data[ 0 ] === C.ACTIONS.UNSUBSCRIBE || ( message.data[ 0 ] === C.EVENT.MESSAGE_DENIED && message.data[ 2 ] === C.ACTIONS.DELETE ) ) { this._destroyEventEmitter.emit( 'destroy_ack_' + name, message ); if( message.data[ 0 ] === C.ACTIONS.DELETE && this._records[ name ] ) { this._records[ name ]._$onMessage( message ); } return; } if( message.data[ 0 ] === C.ACTIONS.SNAPSHOT ) { message.processedError = true; this._snapshotRegistry.recieve( name, message.data[ 2 ] ); return; } if( message.data[ 0 ] === C.ACTIONS.HAS ) { message.processedError = true; this._snapshotRegistry.recieve( name, message.data[ 2 ] ); return; } } else { name = message.data[ 0 ]; } var processed = false; if( this._records[ name ] ) { processed = true; this._records[ name ]._$onMessage( message ); } if( message.action === C.ACTIONS.READ && this._snapshotRegistry.hasRequest( name ) ) { processed = true; this._snapshotRegistry.recieve( name, null, JSON.parse( message.data[ 2 ] ) ); } if( message.action === C.ACTIONS.HAS && this._hasRegistry.hasRequest( name ) ) { processed = true; this._hasRegistry.recieve( name, null, messageParser.convertTyped( message.data[ 1 ] ) ); } if( message.action === C.ACTIONS.ACK && message.data[ 0 ] === C.ACTIONS.UNLISTEN && this._listener[ name ] && this._listener[ name ].destroyPending ) { processed = true; this._listener[ name ].destroy(); delete this._listener[ name ]; } else if( this._listener[ name ] ) { processed = true; this._listener[ name ]._$onMessage( message ); } else if( message.action === C.ACTIONS.SUBSCRIPTION_FOR_PATTERN_REMOVED ) { // An unlisten ACK was received before an PATTERN_REMOVED which is a valid case processed = true; } else if( message.action === C.ACTIONS.SUBSCRIPTION_HAS_PROVIDER ) { // record can receive a HAS_PROVIDER after discarding the record processed = true; } if( !processed ) { message.processedError = true; this._client._$onError( C.TOPIC.RECORD, C.EVENT.UNSOLICITED_MESSAGE, name ); } }; /** * Callback for 'error' events from the record. * * @param {String} recordName * @param {String} error * * @private * @returns {void} */ RecordHandler.prototype._onRecordError = function( recordName, error ) { this._client._$onError( C.TOPIC.RECORD, error, recordName ); }; /** * When the client calls discard or delete on a record, there is a short delay * before the corresponding ACK message is received from the server. To avoid * race conditions if the record is re-requested straight away the old record is * removed from the cache straight awy and will only listen for one last ACK message * * @param {String} recordName The name of the record that was just deleted / discarded * * @private * @returns {void} */ RecordHandler.prototype._onDestroyPending = function( recordName ) { if ( !this._records[ recordName ] ) { this.emit( 'error', 'Record \'' + recordName + '\' does not exists' ); return; } var onMessage = this._records[ recordName ]._$onMessage.bind( this._records[ recordName ] ); this._destroyEventEmitter.once( 'destroy_ack_' + recordName, onMessage ); this._removeRecord( recordName ); }; /** * Callback for 'deleted' and 'discard' events from a record. Removes the record from * the registry * * @param {String} recordName * * @returns {void} */ RecordHandler.prototype._removeRecord = function( recordName ) { delete this._records[ recordName ]; delete this._lists[ recordName ]; }; module.exports = RecordHandler; },{"../constants/constants":11,"../message/message-parser":17,"../utils/listener":28,"../utils/single-notifier":30,"./anonymous-record":19,"./list":21,"./record":23,"component-emitter":2}],23:[function(_dereq_,module,exports){ var jsonPath = _dereq_( './json-path' ), utils = _dereq_( '../utils/utils' ), ResubscribeNotifier = _dereq_( '../utils/resubscribe-notifier' ), EventEmitter = _dereq_( 'component-emitter' ), C = _dereq_( '../constants/constants' ), messageBuilder = _dereq_( '../message/message-builder' ), messageParser = _dereq_( '../message/message-parser' ); /** * This class represents a single record - an observable * dataset returned by client.record.getRecord() * * @extends {EventEmitter} * * @param {String} name The unique name of the record * @param {Object} recordOptions A map of options, e.g. { persist: true } * @param {Connection} Connection The instance of the server connection * @param {Object} options Deepstream options * @param {Client} client deepstream.io client * * @constructor */ var Record = function( name, recordOptions, connection, options, client ) { if ( typeof name !== 'string' || name.length === 0 ) { throw new Error( 'invalid argument name' ); } this.name = name; this.usages = 0; this._recordOptions = recordOptions; this._connection = connection; this._client = client; this._options = options; this.isReady = false; this.isDestroyed = false; this.hasProvider = false; this._$data = Object.create( null ); this.version = null; this._eventEmitter = new EventEmitter(); this._queuedMethodCalls = []; this._writeCallbacks = {}; this._mergeStrategy = null; if( options.mergeStrategy ) { this.setMergeStrategy( options.mergeStrategy ); } this._resubscribeNotifier = new ResubscribeNotifier( this._client, this._sendRead.bind( this ) ); this._readAckTimeout = setTimeout( this._onTimeout.bind( this, C.EVENT.ACK_TIMEOUT ), this._options.recordReadAckTimeout ); this._readTimeout = setTimeout( this._onTimeout.bind( this, C.EVENT.RESPONSE_TIMEOUT ), this._options.recordReadTimeout ); this._sendRead(); }; EventEmitter( Record.prototype ); /** * Set a merge strategy to resolve any merge conflicts that may occur due * to offline work or write conflicts. The function will be called with the * local record, the remote version/data and a callback to call once the merge has * completed or if an error occurs ( which leaves it in an inconsistent state until * the next update merge attempt ). * * @param {Function} mergeStrategy A Function that can resolve merge issues. * * @public * @returns {void} */ Record.prototype.setMergeStrategy = function( mergeStrategy ) { if( typeof mergeStrategy === 'function' ) { this._mergeStrategy = mergeStrategy; } else { throw new Error( 'Invalid merge strategy: Must be a Function' ); } }; /** * Returns a copy of either the entire dataset of the record * or - if called with a path - the value of that path within * the record's dataset. * * Returning a copy rather than the actual value helps to prevent * the record getting out of sync due to unintentional changes to * its data * * @param {[String]} path A JSON path, e.g. users[ 2 ].firstname * * @public * @returns {Mixed} value */ Record.prototype.get = function( path ) { return jsonPath.get( this._$data, path, this._options.recordDeepCopy ); }; /** * Sets the value of either the entire dataset * or of a specific path within the record * and submits the changes to the server * * If the new data is equal to the current data, nothing will happen * * @param {[String|Object]} pathOrData Either a JSON path when called with two arguments or the data itself * @param {Object} data The data that should be stored in the record * * @public * @returns {void} */ Record.prototype.set = function( pathOrData, dataOrCallback, callback ) { var path, data; // set( object ) if( arguments.length === 1 ) { if( typeof pathOrData !== 'object' ) throw new Error( 'invalid argument data' ); data = pathOrData; } else if( arguments.length === 2 ) { // set( path, data ) if( ( typeof pathOrData === 'string' && pathOrData.length !== 0 ) && typeof dataOrCallback !== 'function' ) { path = pathOrData; data = dataOrCallback } // set( data, callback ) else if( typeof pathOrData === 'object' && typeof dataOrCallback === 'function' ) { data = pathOrData; callback = dataOrCallback; } else { throw new Error( 'invalid argument path' ) } } // set( path, data, callback ) else if( arguments.length === 3 ) { if( typeof pathOrData !== 'string' || pathOrData.length === 0 || typeof callback !== 'function' ) { throw new Error( 'invalid arguments, must pass in a string, a value and a function') } path = pathOrData; data = dataOrCallback; } if( this._checkDestroyed( 'set' ) ) { return this; } if( !this.isReady ) { this._queuedMethodCalls.push({ method: 'set', args: arguments }); return this; } var oldValue = this._$data; var newValue = jsonPath.set( oldValue, path, data, this._options.recordDeepCopy ); if ( oldValue === newValue ) { return this; } var config; if( callback !== undefined ) { config = {}; config.writeSuccess = true; this._setUpCallback(this.version, callback) var connectionState = this._client.getConnectionState(); if( connectionState === C.CONNECTION_STATE.CLOSED || connectionState === C.CONNECTION_STATE.RECONNECTING ) { callback( 'Connection error: error updating record as connection was closed' ); } } this._sendUpdate( path, data, config ); this._applyChange( newValue ); return this; }; /** * Subscribes to changes to the records dataset. * * Callback is the only mandatory argument. * * When called with a path, it will only subscribe to updates * to that path, rather than the entire record * * If called with true for triggerNow, the callback will * be called immediatly with the current value * * @param {[String]} path A JSON path within the record to subscribe to * @param {Function} callback Callback function to notify on changes * @param {[Boolean]} triggerNow A flag to specify whether the callback should be invoked immediatly * with the current value * * @public * @returns {void} */ Record.prototype.subscribe = function( path, callback, triggerNow ) { var args = this._normalizeArguments( arguments ); if ( args.path !== undefined && ( typeof args.path !== 'string' || args.path.length === 0 ) ) { throw new Error( 'invalid argument path' ); } if ( typeof args.callback !== 'function' ) { throw new Error( 'invalid argument callback' ); } if( this._checkDestroyed( 'subscribe' ) ) { return; } if( args.triggerNow ) { this.whenReady( function () { this._eventEmitter.on( args.path, args.callback ); args.callback( this.get( args.path ) ); }.bind(this) ); } else { this._eventEmitter.on( args.path, args.callback ); } }; /** * Removes a subscription that was previously made using record.subscribe() * * Can be called with a path to remove the callback for this specific * path or only with a callback which removes it from the generic subscriptions * * Please Note: unsubscribe is a purely client side operation. If the app is no longer * interested in receiving updates for this record from the server it needs to call * discard instead * * @param {[String|Function]} pathOrCallback A JSON path * @param {Function} callback The callback method. Please note, if a bound method was passed to * subscribe, the same method must be passed to unsubscribe as well. * * @public * @returns {void} */ Record.prototype.unsubscribe = function( pathOrCallback, callback ) { var args = this._normalizeArguments( arguments ); if ( args.path !== undefined && ( typeof args.path !== 'string' || args.path.length === 0 ) ) { throw new Error( 'invalid argument path' ); } if ( args.callback !== undefined && typeof args.callback !== 'function' ) { throw new Error( 'invalid argument callback' ); } if( this._checkDestroyed( 'unsubscribe' ) ) { return; } this._eventEmitter.off( args.path, args.callback ); }; /** * Removes all change listeners and notifies the server that the client is * no longer interested in updates for this record * * @public * @returns {void} */ Record.prototype.discard = function() { if( this._checkDestroyed( 'discard' ) ) { return; } this.whenReady( function() { this.usages--; if( this.usages <= 0 ) { this.emit( 'destroyPending' ); this._discardTimeout = setTimeout( this._onTimeout.bind( this, C.EVENT.ACK_TIMEOUT ), this._options.subscriptionTimeout ); this._connection.sendMsg( C.TOPIC.RECORD, C.ACTIONS.UNSUBSCRIBE, [ this.name ] ); } }.bind( this ) ); }; /** * Deletes the record on the server. * * @public * @returns {void} */ Record.prototype.delete = function() { if( this._checkDestroyed( 'delete' ) ) { return; } this.whenReady( function() { this.emit( 'destroyPending' ); this._deleteAckTimeout = setTimeout( this._onTimeout.bind( this, C.EVENT.DELETE_TIMEOUT ), this._options.recordDeleteTimeout ); this._connection.sendMsg( C.TOPIC.RECORD, C.ACTIONS.DELETE, [ this.name ] ); }.bind( this ) ); }; /** * Convenience method, similar to promises. Executes callback * whenever the record is ready, either immediatly or once the ready * event is fired * * @param {Function} callback Will be called when the record is ready * * @returns {void} */ Record.prototype.whenReady = function( callback ) { if( this.isReady === true ) { callback( this ); } else { this.once( 'ready', callback.bind( this, this ) ); } }; /** * Callback for incoming messages from the message handler * * @param {Object} message parsed and validated deepstream message * * @package private * @returns {void} */ Record.prototype._$onMessage = function( message ) { if( message.action === C.ACTIONS.READ ) { if( this.version === null ) { clearTimeout( this._readTimeout ); this._onRead( message ); } else { this._applyUpdate( message, this._client ); } } else if( message.action === C.ACTIONS.ACK ) { this._processAckMessage( message ); } else if( message.action === C.ACTIONS.UPDATE || message.action === C.ACTIONS.PATCH ) { this._applyUpdate( message, this._client ); } else if( message.action === C.ACTIONS.WRITE_ACKNOWLEDGEMENT ) { var versions = JSON.parse(message.data[ 1 ]); for (var i = 0; i < versions.length; i++) { var callback = this._writeCallbacks[ versions[ i ] ]; if( callback !== undefined ) { callback( messageParser.convertTyped( message.data[ 2 ], this._client ) ) delete this._writeCallbacks[ versions[ i ] ]; } } } // Otherwise it should be an error, and dealt with accordingly else if( message.data[ 0 ] === C.EVENT.VERSION_EXISTS ) { this._recoverRecord( message.data[ 2 ], JSON.parse( message.data[ 3 ] ), message ); } else if( message.data[ 0 ] === C.EVENT.MESSAGE_DENIED ) { this._clearTimeouts(); } else if( message.action === C.ACTIONS.SUBSCRIPTION_HAS_PROVIDER ) { var hasProvider = messageParser.convertTyped( message.data[ 1 ], this._client ); this.hasProvider = hasProvider; this.emit( 'hasProviderChanged', hasProvider ); } }; /** * Called when a merge conflict is detected by a VERSION_EXISTS error or if an update recieved * is directly after the clients. If no merge strategy is configure it will emit a VERSION_EXISTS * error and the record will remain in an inconsistent state. * * @param {Number} remoteVersion The remote version number * @param {Object} remoteData The remote object data * @param {Object} message parsed and validated deepstream message * * @private * @returns {void} */ Record.prototype._recoverRecord = function( remoteVersion, remoteData, message ) { message.processedError = true; if( this._mergeStrategy ) { this._mergeStrategy( this, remoteData, remoteVersion, this._onRecordRecovered.bind( this, remoteVersion, remoteData, message ) ); } else { this.emit( 'error', C.EVENT.VERSION_EXISTS, 'received update for ' + remoteVersion + ' but version is ' + this.version ); } }; Record.prototype._sendUpdate = function ( path, data, config ) { this.version++; var msgData; if( !path ) { msgData = config === undefined ? [ this.name, this.version, data ] : [ this.name, this.version, data, config ]; this._connection.sendMsg( C.TOPIC.RECORD, C.ACTIONS.UPDATE, msgData ); } else { msgData = config === undefined ? [ this.name, this.version, path, messageBuilder.typed( data ) ] : [ this.name, this.version, path, messageBuilder.typed( data ), config ]; this._connection.sendMsg( C.TOPIC.RECORD, C.ACTIONS.PATCH, msgData ); } }; /** * Callback once the record merge has completed. If successful it will set the * record state, else emit and error and the record will remain in an * inconsistent state until the next update. * * @param {Number} remoteVersion The remote version number * @param {Object} remoteData The remote object data * @param {Object} message parsed and validated deepstream message * * @private * @returns {void} */ Record.prototype._onRecordRecovered = function( remoteVersion, remoteData, message, error, data ) { if( !error ) { var oldVersion = this.version; this.version = remoteVersion; var oldValue = this._$data; var newValue = jsonPath.set( oldValue, undefined, data, false ); if ( oldValue === newValue ) { return; } var config = message.data[ 4 ]; if( config && JSON.parse( config ).writeSuccess ) { var callback = this._writeCallbacks[ oldVersion ]; delete this._writeCallbacks[ oldVersion ]; this._setUpCallback( this.version, callback ) } this._sendUpdate( undefined, data, config ); this._applyChange( newValue ); } else { this.emit( 'error', C.EVENT.VERSION_EXISTS, 'received update for ' + remoteVersion + ' but version is ' + this.version ); } }; /** * Callback for ack-messages. Acks can be received for * subscriptions, discards and deletes * * @param {Object} message parsed and validated deepstream message * * @private * @returns {void} */ Record.prototype._processAckMessage = function( message ) { var acknowledgedAction = message.data[ 0 ]; if( acknowledgedAction === C.ACTIONS.SUBSCRIBE ) { clearTimeout( this._readAckTimeout ); } else if( acknowledgedAction === C.ACTIONS.DELETE ) { this.emit( 'delete' ); this._destroy(); } else if( acknowledgedAction === C.ACTIONS.UNSUBSCRIBE ) { this.emit( 'discard' ); this._destroy(); } }; /** * Applies incoming updates and patches to the record's dataset * * @param {Object} message parsed and validated deepstream message * * @private * @returns {void} */ Record.prototype._applyUpdate = function( message ) { var version = parseInt( message.data[ 1 ], 10 ); var data; if( message.action === C.ACTIONS.PATCH ) { data = messageParser.convertTyped( message.data[ 3 ], this._client ); } else { data = JSON.parse( message.data[ 2 ] ); } if( this.version === null ) { this.version = version; } else if( this.version + 1 !== version ) { if( message.action === C.ACTIONS.PATCH ) { /** * Request a snapshot so that a merge can be done with the read reply which contains * the full state of the record **/ this._connection.sendMsg( C.TOPIC.RECORD, C.ACTIONS.SNAPSHOT, [ this.name ] ); } else { this._recoverRecord( version, data, message ); } return; } this.version = version; this._applyChange( jsonPath.set( this._$data, message.action === C.ACTIONS.PATCH ? message.data[ 2 ] : undefined, data ) ); }; /** * Callback for incoming read messages * * @param {Object} message parsed and validated deepstream message * * @private * @returns {void} */ Record.prototype._onRead = function( message ) { this.version = parseInt( message.data[ 1 ], 10 ); this._applyChange( jsonPath.set( this._$data, undefined, JSON.parse( message.data[ 2 ] ) ) ); this._setReady(); }; /** * Invokes method calls that where queued while the record wasn't ready * and emits the ready event * * @private * @returns {void} */ Record.prototype._setReady = function() { this.isReady = true; for( var i = 0; i < this._queuedMethodCalls.length; i++ ) { this[ this._queuedMethodCalls[ i ].method ].apply( this, this._queuedMethodCalls[ i ].args ); } this._queuedMethodCalls = []; this.emit( 'ready' ); }; Record.prototype._setUpCallback = function(currentVersion, callback) { var newVersion = Number( this.version ) + 1; this._writeCallbacks[ newVersion ] = callback; } /** * Sends the read message, either initially at record * creation or after a lost connection has been re-established * * @private * @returns {void} */ Record.prototype._sendRead = function() { this._connection.sendMsg( C.TOPIC.RECORD, C.ACTIONS.CREATEORREAD, [ this.name ] ); }; /** * Compares the new values for every path with the previously stored ones and * updates the subscribers if the value has changed * * @private * @returns {void} */ Record.prototype._applyChange = function( newData ) { if ( this.isDestroyed ) { return; } var oldData = this._$data; this._$data = newData; if ( !this._eventEmitter._callbacks ) { return; } var paths = Object.keys( this._eventEmitter._callbacks ); for ( var i = 0; i < paths.length; i++ ) { var newValue = jsonPath.get( newData, paths[ i ], false ); var oldValue = jsonPath.get( oldData, paths[ i ], false ); if( newValue !== oldValue ) { this._eventEmitter.emit( paths[ i ], this.get( paths[ i ] ) ); } } }; /** * Creates a map based on the types of the provided arguments * * @param {Arguments} args * * @private * @returns {Object} arguments map */ Record.prototype._normalizeArguments = function( args ) { // If arguments is already a map of normalized parameters // (e.g. when called by AnonymousRecord), just return it. if( args.length === 1 && typeof args[ 0 ] === 'object' ) { return args[ 0 ]; } var result = Object.create( null ); for( var i = 0; i < args.length; i++ ) { if( typeof args[ i ] === 'string' ) { result.path = args[ i ]; } else if( typeof args[ i ] === 'function' ) { result.callback = args[ i ]; } else if( typeof args[ i ] === 'boolean' ) { result.triggerNow = args[ i ]; } } return result; }; /** * Clears all timeouts that are set when the record is created * * @private * @returns {void} */ Record.prototype._clearTimeouts = function() { clearTimeout( this._readAckTimeout ); clearTimeout( this._deleteAckTimeout ); clearTimeout( this._discardTimeout ); clearTimeout( this._deleteAckTimeout ); }; /** * A quick check that's carried out by most methods that interact with the record * to make sure it hasn't been destroyed yet - and to handle it gracefully if it has. * * @param {String} methodName The name of the method that invoked this check * * @private * @returns {Boolean} is destroyed */ Record.prototype._checkDestroyed = function( methodName ) { if( this.isDestroyed ) { this.emit( 'error', 'Can\'t invoke \'' + methodName + '\'. Record \'' + this.name + '\' is already destroyed' ); return true; } return false; }; /** * Generic handler for ack, read and delete timeouts * * @private * @returns {void} */ Record.prototype._onTimeout = function( timeoutType ) { this._clearTimeouts(); this.emit( 'error', timeoutType ); }; /** * Destroys the record and nulls all * its dependencies * * @private * @returns {void} */ Record.prototype._destroy = function() { this._clearTimeouts(); this._eventEmitter.off(); this._resubscribeNotifier.destroy(); this.isDestroyed = true; this.isReady = false; this._client = null; this._eventEmitter = null; this._connection = null; }; module.exports = Record; },{"../constants/constants":11,"../message/message-builder":16,"../message/message-parser":17,"../utils/resubscribe-notifier":29,"../utils/utils":31,"./json-path":20,"component-emitter":2}],24:[function(_dereq_,module,exports){ var C = _dereq_( '../constants/constants' ), AckTimeoutRegistry = _dereq_( '../utils/ack-timeout-registry' ), ResubscribeNotifier = _dereq_( '../utils/resubscribe-notifier' ), RpcResponse = _dereq_( './rpc-response' ), Rpc = _dereq_( './rpc' ), messageParser= _dereq_( '../message/message-parser' ), messageBuilder = _dereq_( '../message/message-builder' ); /** * The main class for remote procedure calls * * Provides the rpc interface and handles incoming messages * on the rpc topic * * @param {Object} options deepstream configuration options * @param {Connection} connection * @param {Client} client * * @constructor * @public */ var RpcHandler = function( options, connection, client ) { this._options = options; this._connection = connection; this._client = client; this._rpcs = {}; this._providers = {}; this._provideAckTimeouts = {}; this._ackTimeoutRegistry = new AckTimeoutRegistry( client, C.TOPIC.RPC, this._options.subscriptionTimeout ); this._resubscribeNotifier = new ResubscribeNotifier( this._client, this._reprovide.bind( this ) ); }; /** * Registers a callback function as a RPC provider. If another connected client calls * client.rpc.make() the request will be routed to this method * * The callback will be invoked with two arguments: * {Mixed} data The data passed to the client.rpc.make function * {RpcResponse} rpcResponse An object with methods to respons, acknowledge or reject the request * * Only one callback can be registered for a RPC at a time * * Please note: Deepstream tries to deliver data in its original format. Data passed to client.rpc.make as a String will arrive as a String, * numbers or implicitly JSON serialized objects will arrive in their respective format as well * * @public * @returns void */ RpcHandler.prototype.provide = function( name, callback ) { if ( typeof name !== 'string' || name.length === 0 ) { throw new Error( 'invalid argument name' ); } if( this._providers[ name ] ) { throw new Error( 'RPC ' + name + ' already registered' ); } if ( typeof callback !== 'function' ) { throw new Error( 'invalid argument callback' ); } this._ackTimeoutRegistry.add( name, C.ACTIONS.SUBSCRIBE ); this._providers[ name ] = callback; this._connection.sendMsg( C.TOPIC.RPC, C.ACTIONS.SUBSCRIBE, [ name ] ); }; /** * Unregisters this client as a provider for a remote procedure call * * @param {String} name the name of the rpc * * @public * @returns {void} */ RpcHandler.prototype.unprovide = function( name ) { if ( typeof name !== 'string' || name.length === 0 ) { throw new Error( 'invalid argument name' ); } if( this._providers[ name ] ) { delete this._providers[ name ]; this._ackTimeoutRegistry.add( name, C.ACTIONS.UNSUBSCRIBE ); this._connection.sendMsg( C.TOPIC.RPC, C.ACTIONS.UNSUBSCRIBE, [ name ] ); } }; /** * Executes the actual remote procedure call * * @param {String} name The name of the rpc * @param {Mixed} data Serializable data that will be passed to the provider * @param {Function} callback Will be invoked with the returned result or if the rpc failed * receives to arguments: error or null and the result * * @public * @returns {void} */ RpcHandler.prototype.make = function( name, data, callback ) { if ( typeof name !== 'string' || name.length === 0 ) { throw new Error( 'invalid argument name' ); } if ( typeof callback !== 'function' ) { throw new Error( 'invalid argument callback' ); } var uid = this._client.getUid(), typedData = messageBuilder.typed( data ); this._rpcs[ uid ] = new Rpc( this._options, callback, this._client ); this._connection.sendMsg( C.TOPIC.RPC, C.ACTIONS.REQUEST, [ name, uid, typedData ] ); }; /** * Retrieves a RPC instance for a correlationId or throws an error * if it can't be found (which should never happen) * * @param {String} correlationId * @param {String} rpcName * * @private * @returns {Rpc} */ RpcHandler.prototype._getRpc = function( correlationId, rpcName, rawMessage ) { var rpc = this._rpcs[ correlationId ]; if( !rpc ) { this._client._$onError( C.TOPIC.RPC, C.EVENT.UNSOLICITED_MESSAGE, rawMessage ); return null; } return rpc; }; /** * Handles incoming rpc REQUEST messages. Instantiates a new response object * and invokes the provider callback or rejects the request if no rpc provider * is present (which shouldn't really happen, but might be the result of a race condition * if this client sends a unprovide message whilst an incoming request is already in flight) * * @param {Object} message The parsed deepstream RPC request message. * * @private * @returns {void} */ RpcHandler.prototype._respondToRpc = function( message ) { var name = message.data[ 0 ], correlationId = message.data[ 1 ], data = null, response; if( message.data[ 2 ] ) { data = messageParser.convertTyped( message.data[ 2 ], this._client ); } if( this._providers[ name ] ) { response = new RpcResponse( this._connection, name, correlationId ); this._providers[ name ]( data, response ); } else { this._connection.sendMsg( C.TOPIC.RPC, C.ACTIONS.REJECTION, [ name, correlationId ] ); } }; /** * Distributes incoming messages from the server * based on their action * * @param {Object} message A parsed deepstream message * * @private * @returns {void} */ RpcHandler.prototype._$handle = function( message ) { var rpcName, correlationId, rpc; // RPC Requests if( message.action === C.ACTIONS.REQUEST ) { this._respondToRpc( message ); return; } // RPC subscription Acks if( message.action === C.ACTIONS.ACK && ( message.data[ 0 ] === C.ACTIONS.SUBSCRIBE || message.data[ 0 ] === C.ACTIONS.UNSUBSCRIBE ) ) { this._ackTimeoutRegistry.clear( message ); return; } // handle auth/denied subscription errors if( message.action === C.ACTIONS.ERROR ) { if( message.data[ 0 ] === C.EVENT.MESSAGE_PERMISSION_ERROR ) { return; } if( message.data[ 0 ] === C.EVENT.MESSAGE_DENIED && message.data[ 2 ] === C.ACTIONS.SUBSCRIBE ) { this._ackTimeoutRegistry.remove( message.data[ 1 ], C.ACTIONS.SUBSCRIBE ); return; } } /* * Error messages always have the error as first parameter. So the * order is different to ack and response messages */ if( message.action === C.ACTIONS.ERROR || message.action === C.ACTIONS.ACK ) { if( message.data[ 0 ] === C.EVENT.MESSAGE_DENIED && message.data[ 2 ] === C.ACTIONS.REQUEST ) { correlationId = message.data[ 3 ]; } else { correlationId = message.data[ 2 ]; } rpcName = message.data[ 1 ]; } else { rpcName = message.data[ 0 ]; correlationId = message.data[ 1 ]; } /* * Retrieve the rpc object */ rpc = this._getRpc( correlationId, rpcName, message.raw ); if( rpc === null ) { return; } // RPC Responses if( message.action === C.ACTIONS.ACK ) { rpc.ack(); } else if( message.action === C.ACTIONS.RESPONSE ) { rpc.respond( message.data[ 2 ] ); delete this._rpcs[ correlationId ]; } else if( message.action === C.ACTIONS.ERROR ) { message.processedError = true; rpc.error( message.data[ 0 ] ); delete this._rpcs[ correlationId ]; } }; /** * Reregister providers to events when connection is lost * * @package private * @returns {void} */ RpcHandler.prototype._reprovide = function() { for( var rpcName in this._providers ) { this._connection.sendMsg( C.TOPIC.RPC, C.ACTIONS.SUBSCRIBE, [ rpcName ] ); } }; module.exports = RpcHandler; },{"../constants/constants":11,"../message/message-builder":16,"../message/message-parser":17,"../utils/ack-timeout-registry":27,"../utils/resubscribe-notifier":29,"./rpc":26,"./rpc-response":25}],25:[function(_dereq_,module,exports){ var C = _dereq_( '../constants/constants' ), utils = _dereq_( '../utils/utils' ), messageBuilder = _dereq_( '../message/message-builder' ); /** * This object provides a number of methods that allow a rpc provider * to respond to a request * * @param {Connection} connection - the clients connection object * @param {String} name the name of the rpc * @param {String} correlationId the correlationId for the RPC */ var RpcResponse = function( connection, name, correlationId ) { this._connection = connection; this._name = name; this._correlationId = correlationId; this._isAcknowledged = false; this._isComplete = false; this.autoAck = true; utils.nextTick( this._performAutoAck.bind( this ) ); }; /** * Acknowledges the receipt of the request. This * will happen implicitly unless the request callback * explicitly sets autoAck to false * * @public * @returns {void} */ RpcResponse.prototype.ack = function() { if( this._isAcknowledged === false ) { this._connection.sendMsg( C.TOPIC.RPC, C.ACTIONS.ACK, [ C.ACTIONS.REQUEST, this._name, this._correlationId ] ); this._isAcknowledged = true; } }; /** * Reject the request. This might be necessary if the client * is already processing a large number of requests. If deepstream * receives a rejection message it will try to route the request to * another provider - or return a NO_RPC_PROVIDER error if there are no * providers left * * @public * @returns {void} */ RpcResponse.prototype.reject = function() { this.autoAck = false; this._isComplete = true; this._isAcknowledged = true; this._connection.sendMsg( C.TOPIC.RPC, C.ACTIONS.REJECTION, [ this._name, this._correlationId ] ); }; /** * Notifies the server that an error has occured while trying to process the request. * This will complete the rpc. * * @param {String} errorMsg the message used to describe the error that occured * @public * @returns {void} */ RpcResponse.prototype.error = function( errorMsg ) { this.autoAck = false; this._isComplete = true; this._isAcknowledged = true; this._connection.sendMsg( C.TOPIC.RPC, C.ACTIONS.ERROR, [ errorMsg, this._name, this._correlationId ] ); }; /** * Completes the request by sending the response data * to the server. If data is an array or object it will * automatically be serialised. * If autoAck is disabled and the response is sent before * the ack message the request will still be completed and the * ack message ignored * * @param {String} data the data send by the provider. Might be JSON serialized * * @public * @returns {void} */ RpcResponse.prototype.send = function( data ) { if( this._isComplete === true ) { throw new Error( 'Rpc ' + this._name + ' already completed' ); } this.ack(); var typedData = messageBuilder.typed( data ); this._connection.sendMsg( C.TOPIC.RPC, C.ACTIONS.RESPONSE, [ this._name, this._correlationId, typedData ] ); this._isComplete = true; }; /** * Callback for the autoAck timeout. Executes ack * if autoAck is not disabled * * @private * @returns {void} */ RpcResponse.prototype._performAutoAck = function() { if( this.autoAck === true ) { this.ack(); } }; module.exports = RpcResponse; },{"../constants/constants":11,"../message/message-builder":16,"../utils/utils":31}],26:[function(_dereq_,module,exports){ var C = _dereq_( '../constants/constants' ), messageParser = _dereq_( '../message/message-parser' ); /** * This class represents a single remote procedure * call made from the client to the server. It's main function * is to encapsulate the logic around timeouts and to convert the * incoming response data * * @param {Object} options deepstream client config * @param {Function} callback the function that will be called once the request is complete or failed * @param {Client} client * * @constructor */ var Rpc = function( options, callback, client ) { this._options = options; this._callback = callback; this._client = client; this._ackTimeout = setTimeout( this.error.bind( this, C.EVENT.ACK_TIMEOUT ), this._options.rpcAckTimeout ); this._responseTimeout = setTimeout( this.error.bind( this, C.EVENT.RESPONSE_TIMEOUT ), this._options.rpcResponseTimeout ); }; /** * Called once an ack message is received from the server * * @public * @returns {void} */ Rpc.prototype.ack = function() { clearTimeout( this._ackTimeout ); }; /** * Called once a response message is received from the server. * Converts the typed data and completes the request * * @param {String} data typed value * * @public * @returns {void} */ Rpc.prototype.respond = function( data ) { var convertedData = messageParser.convertTyped( data, this._client ); this._callback( null, convertedData ); this._complete(); }; /** * Callback for error messages received from the server. Once * an error is received the request is considered completed. Even * if a response arrives later on it will be ignored / cause an * UNSOLICITED_MESSAGE error * * @param {String} errorMsg @TODO should be CODE and message * * @public * @returns {void} */ Rpc.prototype.error = function( errorMsg ) { this._callback( errorMsg ); this._complete(); }; /** * Called after either an error or a response * was received * * @private * @returns {void} */ Rpc.prototype._complete = function() { clearTimeout( this._ackTimeout ); clearTimeout( this._responseTimeout ); }; module.exports = Rpc; },{"../constants/constants":11,"../message/message-parser":17}],27:[function(_dereq_,module,exports){ var C = _dereq_( '../constants/constants' ), EventEmitter = _dereq_( 'component-emitter' ); /** * Subscriptions to events are in a pending state until deepstream acknowledges * them. This is a pattern that's used by numerour classes. This registry aims * to centralise the functionality necessary to keep track of subscriptions and * their respective timeouts. * * @param {Client} client The deepstream client * @param {String} topic Constant. One of C.TOPIC * @param {Number} timeoutDuration The duration of the timeout in milliseconds * * @extends {EventEmitter} * @constructor */ var AckTimeoutRegistry = function( client, topic, timeoutDuration ) { this._client = client; this._topic = topic; this._timeoutDuration = timeoutDuration; this._register = {}; }; EventEmitter( AckTimeoutRegistry.prototype ); /** * Add an entry * * @param {String} name An identifier for the subscription, e.g. a record name or an event name. * * @public * @returns {void} */ AckTimeoutRegistry.prototype.add = function( name, action ) { var uniqueName = action ? action + name : name; this.remove( name, action ); this._register[ uniqueName ] = setTimeout( this._onTimeout.bind( this, uniqueName, name ), this._timeoutDuration ); }; /** * Remove an entry * * @param {String} name An identifier for the subscription, e.g. a record name or an event name. * * @public * @returns {void} */ AckTimeoutRegistry.prototype.remove = function( name, action ) { var uniqueName = action ? action + name : name; if( this._register[ uniqueName ] ) { this.clear( { data: [ action, name ] } ); } }; /** * Processes an incoming ACK-message and removes the corresponding subscription * * @param {Object} message A parsed deepstream ACK message * * @public * @returns {void} */ AckTimeoutRegistry.prototype.clear = function( message ) { var name = message.data[ 1 ]; var uniqueName = message.data[ 0 ] + name; var timeout = this._register[ uniqueName ] || this._register[ name ]; if( timeout ) { clearTimeout( timeout ); } else { this._client._$onError( this._topic, C.EVENT.UNSOLICITED_MESSAGE, message.raw ); } }; /** * Will be invoked if the timeout has occured before the ack message was received * * @param {String} name An identifier for the subscription, e.g. a record name or an event name. * * @private * @returns {void} */ AckTimeoutRegistry.prototype._onTimeout = function( uniqueName, name ) { delete this._register[ uniqueName ]; var msg = 'No ACK message received in time for ' + name; this._client._$onError( this._topic, C.EVENT.ACK_TIMEOUT, msg ); this.emit( 'timeout', name ); }; module.exports = AckTimeoutRegistry; },{"../constants/constants":11,"component-emitter":2}],28:[function(_dereq_,module,exports){ var C = _dereq_( '../constants/constants' ); var ResubscribeNotifier = _dereq_( './resubscribe-notifier' ); /* * Creates a listener instance which is usedby deepstream Records and Events. * * @param {String} type One of CONSTANTS.TOPIC * @param {String} pattern A pattern that can be compiled via new RegExp(pattern) * @param {Function} callback The function which is called when pattern was found and removed * @param {Connection} Connection The instance of the server connection * @param {Object} options Deepstream options * @param {Client} client deepstream.io client * * @constructor */ var Listener = function( type, pattern, callback, options, client, connection ) { this._type = type; this._callback = callback; this._pattern = pattern; this._options = options; this._client = client; this._connection = connection; this._ackTimeout = setTimeout( this._onAckTimeout.bind( this ), this._options.subscriptionTimeout ); this._resubscribeNotifier = new ResubscribeNotifier( client, this._sendListen.bind( this ) ); this._sendListen(); this.destroyPending = false; }; Listener.prototype.sendDestroy = function() { this.destroyPending = true; this._connection.sendMsg( this._type, C.ACTIONS.UNLISTEN, [ this._pattern ] ); this._resubscribeNotifier.destroy(); }; /* * Resets internal properties. Is called when provider cals unlisten. * * @returns {void} */ Listener.prototype.destroy = function() { this._callback = null; this._pattern = null; this._client = null; this._connection = null; }; /* * Accepting a listener request informs deepstream that the current provider is willing to * provide the record or event matching the subscriptionName . This will establish the current * provider as the only publisher for the actual subscription with the deepstream cluster. * Either accept or reject needs to be called by the listener, otherwise it prints out a deprecated warning. * * @returns {void} */ Listener.prototype.accept = function( name ) { this._connection.sendMsg( this._type, C.ACTIONS.LISTEN_ACCEPT, [ this._pattern, name ] ); } /* * Rejecting a listener request informs deepstream that the current provider is not willing * to provide the record or event matching the subscriptionName . This will result in deepstream * requesting another provider to do so instead. If no other provider accepts or exists, the * record will remain unprovided. * Either accept or reject needs to be called by the listener, otherwise it prints out a deprecated warning. * * @returns {void} */ Listener.prototype.reject = function( name ) { this._connection.sendMsg( this._type, C.ACTIONS.LISTEN_REJECT, [ this._pattern, name ] ); } /* * Wraps accept and reject as an argument for the callback function. * * @private * @returns {Object} */ Listener.prototype._createCallbackResponse = function(message) { return { accept: this.accept.bind( this, message.data[ 1 ] ), reject: this.reject.bind( this, message.data[ 1 ] ) } } /* * Handles the incomming message. * * @private * @returns {void} */ Listener.prototype._$onMessage = function( message ) { if( message.action === C.ACTIONS.ACK ) { clearTimeout( this._ackTimeout ); } else if ( message.action === C .ACTIONS.SUBSCRIPTION_FOR_PATTERN_FOUND ) { this._callback( message.data[ 1 ], true, this._createCallbackResponse( message) ); } else if ( message.action === C.ACTIONS.SUBSCRIPTION_FOR_PATTERN_REMOVED ) { this._callback( message.data[ 1 ], false ); } else { this._client._$onError( this._type, C.EVENT.UNSOLICITED_MESSAGE, message.data[ 0 ] + '|' + message.data[ 1 ] ); } }; /* * Sends a C.ACTIONS.LISTEN to deepstream. * * @private * @returns {void} */ Listener.prototype._sendListen = function() { this._connection.sendMsg( this._type, C.ACTIONS.LISTEN, [ this._pattern ] ); }; /* * Sends a C.EVENT.ACK_TIMEOUT to deepstream. * * @private * @returns {void} */ Listener.prototype._onAckTimeout = function() { this._client._$onError( this._type, C.EVENT.ACK_TIMEOUT, 'No ACK message received in time for ' + this._pattern ); }; module.exports = Listener; },{"../constants/constants":11,"./resubscribe-notifier":29}],29:[function(_dereq_,module,exports){ var C = _dereq_( '../constants/constants' ); /** * Makes sure that all functionality is resubscribed on reconnect. Subscription is called * when the connection drops - which seems counterintuitive, but in fact just means * that the re-subscription message will be added to the queue of messages that * need re-sending as soon as the connection is re-established. * * Resubscribe logic should only occur once per connection loss * * @param {Client} client The deepstream client * @param {Function} reconnect Function to call to allow resubscribing * * @constructor */ var ResubscribeNotifier = function( client, resubscribe ) { this._client = client; this._resubscribe = resubscribe; this._isReconnecting = false; this._connectionStateChangeHandler = this._handleConnectionStateChanges.bind( this ); this._client.on( 'connectionStateChanged', this._connectionStateChangeHandler ); }; /** * Call this whenever this functionality is no longer needed to remove links * * @returns {void} */ ResubscribeNotifier.prototype.destroy = function() { this._client.removeListener( 'connectionStateChanged', this._connectionStateChangeHandler ); this._connectionStateChangeHandler = null; this._client = null; }; /** * Check whenever the connection state changes if it is in reconnecting to resubscribe * @private * @returns {void} */ ResubscribeNotifier.prototype._handleConnectionStateChanges = function() { var state = this._client.getConnectionState(); if( state === C.CONNECTION_STATE.RECONNECTING && this._isReconnecting === false ) { this._isReconnecting = true; } if( state === C.CONNECTION_STATE.OPEN && this._isReconnecting === true ) { this._isReconnecting = false; this._resubscribe(); } }; module.exports = ResubscribeNotifier; },{"../constants/constants":11}],30:[function(_dereq_,module,exports){ var C = _dereq_( '../constants/constants' ), ResubscribeNotifier = _dereq_( './resubscribe-notifier' ); /** * Provides a scaffold for subscriptionless requests to deepstream, such as the SNAPSHOT * and HAS functionality. The SingleNotifier multiplexes all the client requests so * that they can can be notified at once, and also includes reconnection funcionality * incase the connection drops. * * @param {Client} client The deepstream client * @param {Connection} connection The deepstream connection * @param {String} topic Constant. One of C.TOPIC * @param {String} action Constant. One of C.ACTIONS * @param {Number} timeoutDuration The duration of the timeout in milliseconds * * @constructor */ var SingleNotifier = function( client, connection, topic, action, timeoutDuration ) { this._client = client; this._connection = connection; this._topic = topic; this._action = action; this._timeoutDuration = timeoutDuration; this._requests = {}; this._resubscribeNotifier = new ResubscribeNotifier( this._client, this._resendRequests.bind( this ) ); }; /** * Check if there is a request pending with a specified name * * @param {String} name An identifier for the request, e.g. a record name * * @public * @returns {void} */ SingleNotifier.prototype.hasRequest = function( name ) { return !!this._requests[ name ]; }; /** * Add a request. If one has already been made it will skip the server request * and multiplex the response * * @param {String} name An identifier for the request, e.g. a record name * * @public * @returns {void} */ SingleNotifier.prototype.request = function( name, callback ) { var responseTimeout; if( !this._requests[ name ] ) { this._requests[ name ] = []; this._connection.sendMsg( this._topic, this._action, [ name ] ); } responseTimeout = setTimeout( this._onResponseTimeout.bind( this, name ), this._timeoutDuration ); this._requests[ name ].push( { timeout: responseTimeout, callback: callback } ); }; /** * Process a response for a request. This has quite a flexible API since callback functions * differ greatly and helps maximise reuse. * * @param {String} name An identifier for the request, e.g. a record name * @param {String} error Error message * @param {Object} data If successful, the response data * * @public * @returns {void} */ SingleNotifier.prototype.recieve = function( name, error, data ) { var entries = this._requests[ name ]; if( !entries ) { this._client._$onError( this._topic, C.EVENT.UNSOLICITED_MESSAGE, 'no entry for ' + name ); return; } for( i=0; i < entries.length; i++ ) { entry = entries[ i ]; clearTimeout( entry.timeout ); entry.callback( error, data ); } delete this._requests[ name ]; }; /** * Will be invoked if a timeout occurs before a response arrives from the server * * @param {String} name An identifier for the request, e.g. a record name * * @private * @returns {void} */ SingleNotifier.prototype._onResponseTimeout = function( name ) { var msg = 'No response received in time for ' + this._topic + '|' + this._action + '|' + name; this._client._$onError( this._topic, C.EVENT.RESPONSE_TIMEOUT, msg ); }; /** * Resends all the requests once the connection is back up * * @private * @returns {void} */ SingleNotifier.prototype._resendRequests = function() { for( var request in this._requests ) { this._connection.sendMsg( this._topic, this._action, [ this._requests[ request ] ] ); } }; module.exports = SingleNotifier; },{"../constants/constants":11,"./resubscribe-notifier":29}],31:[function(_dereq_,module,exports){ (function (process){ /** * A regular expression that matches whitespace on either side, but * not in the center of a string * * @type {RegExp} */ var TRIM_REGULAR_EXPRESSION = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; /** * Used in typeof comparisons * * @type {String} */ var OBJECT = 'object'; /** * True if environment is node, false if it's a browser * This seems somewhat inelegant, if anyone knows a better solution, * let's change this (must identify browserify's pseudo node implementation though) * * @public * @type {Boolean} */ exports.isNode = typeof process !== 'undefined' && process.toString() === '[object process]'; /** * Provides as soon as possible async execution in a cross * platform way * * @param {Function} fn the function to be executed in an asynchronous fashion * * @public * @returns {void} */ exports.nextTick = function( fn ) { if( exports.isNode ) { process.nextTick( fn ); } else { setTimeout( fn, 0 ); } }; /** * Removes whitespace from the beginning and end of a string * * @param {String} inputString * * @public * @returns {String} trimmedString */ exports.trim = function( inputString ) { if( inputString.trim ) { return inputString.trim(); } else { return inputString.replace( TRIM_REGULAR_EXPRESSION, '' ); } }; /** * Compares two objects for deep (recoursive) equality * * This used to be a significantly more complex custom implementation, * but JSON.stringify has gotten so fast that it now outperforms the custom * way by a factor of 1.5 to 3. * * In IE11 / Edge the custom implementation is still slightly faster, but for * consistencies sake and the upsides of leaving edge-case handling to the native * browser / node implementation we'll go for JSON.stringify from here on. * * Please find performance test results here * * http://jsperf.com/deep-equals-code-vs-json * * @param {Mixed} objA * @param {Mixed} objB * * @public * @returns {Boolean} isEqual */ exports.deepEquals= function( objA, objB ) { if ( objA === objB ) { return true } else if( typeof objA !== OBJECT || typeof objB !== OBJECT ) { return false; } else { return JSON.stringify( objA ) === JSON.stringify( objB ); } }; /** * Similar to deepEquals above, tests have shown that JSON stringify outperforms any attempt of * a code based implementation by 50% - 100% whilst also handling edge-cases and keeping implementation * complexity low. * * If ES6/7 ever decides to implement deep copying natively (what happened to Object.clone? that was briefly * a thing...), let's switch it for the native implementation. For now though, even Object.assign({}, obj) only * provides a shallow copy. * * Please find performance test results backing these statements here: * * http://jsperf.com/object-deep-copy-assign * * @param {Mixed} obj the object that should be cloned * * @public * @returns {Mixed} clone */ exports.deepCopy = function( obj ) { if( typeof obj === OBJECT ) { return JSON.parse( JSON.stringify( obj ) ); } else { return obj; } }; /** * Copy the top level of items, but do not copy its items recourisvely. This * is much quicker than deepCopy does not guarantee the object items are new/unique. * Mainly used to change the reference to the actual object itself, but not its children. * * @param {Mixed} obj the object that should cloned * * @public * @returns {Mixed} clone */ exports.shallowCopy = function ( obj ) { if ( Array.isArray( obj ) ) { return obj.slice( 0 ); } else if ( typeof obj === OBJECT ) { var copy = Object.create( null ); var props = Object.keys( obj ); for ( var i = 0; i < props.length; i++ ) { copy[ props[ i ] ] = obj[ props[ i ] ]; } return copy; } return obj; } /** * Set timeout utility that adds support for disabling a timeout * by passing null * * @param {Function} callback the function that will be called after the given time * @param {Number} timeoutDuration the duration of the timeout in milliseconds * * @public * @returns {Number} timeoutId */ exports.setTimeout = function( callback, timeoutDuration ) { if( timeoutDuration !== null ) { return setTimeout( callback, timeoutDuration ); } else { return -1; } }; /** * Set Interval utility that adds support for disabling an interval * by passing null * * @param {Function} callback the function that will be called after the given time * @param {Number} intervalDuration the duration of the interval in milliseconds * * @public * @returns {Number} intervalId */ exports.setInterval = function( callback, intervalDuration ) { if( intervalDuration !== null ) { return setInterval( callback, intervalDuration ); } else { return -1; } }; /** * Used to see if a protocol is specified within the url * @type {RegExp} */ var hasUrlProtocol = /^wss:|^ws:|^\/\//; /** * Used to see if the protocol contains any unsupported protocols * @type {RegExp} */ var unsupportedProtocol = /^http:|^https:/; var URL = _dereq_( 'url' ); /** * Take the url passed when creating the client and ensure the correct * protocol is provided * @param {String} url Url passed in by client * @return {String} Url with supported protocol */ exports.parseUrl = function( url, defaultPath ) { if( unsupportedProtocol.test( url ) ) { throw new Error( 'Only ws and wss are supported' ); } if( !hasUrlProtocol.test( url ) ) { url = 'ws://' + url; } else if( url.indexOf( '//' ) === 0 ) { url = 'ws:' + url; } var serverUrl = URL.parse( url ); if (!serverUrl.host) { throw new Error('invalid url, missing host'); } serverUrl.protocol = serverUrl.protocol ? serverUrl.protocol : 'ws:'; serverUrl.pathname = serverUrl.pathname ? serverUrl.pathname : defaultPath; return URL.format( serverUrl ); }; }).call(this,_dereq_('_process')) },{"_process":3,"url":8}]},{},[10])(10) });
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang("codesnippet","el",{button:"Εισαγωγή Αποσπάσματος Κώδικα",codeContents:"Περιεχόμενο κώδικα",emptySnippetError:"Δεν γίνεται να είναι κενά τα αποσπάσματα κώδικα.",language:"Γλώσσα",title:"Απόσπασμα κώδικα",pathName:"απόσπασμα κώδικα"});
/*! hyperform.js.org */ var hyperform = (function () { 'use strict'; var registry = Object.create(null); /** * run all actions registered for a hook * * Every action gets called with a state object as `this` argument and with the * hook's call arguments as call arguments. * * @return mixed the returned value of the action calls or undefined */ function call_hook(hook) { var result; var call_args = Array.prototype.slice.call(arguments, 1); if (hook in registry) { result = registry[hook].reduce(function (args) { return function (previousResult, currentAction) { var interimResult = currentAction.apply({ state: previousResult, hook: hook }, args); return interimResult !== undefined ? interimResult : previousResult; }; }(call_args), result); } return result; } /** * Filter a value through hooked functions * * Allows for additional parameters: * js> do_filter('foo', null, current_element) */ function do_filter(hook, initial_value) { var result = initial_value; var call_args = Array.prototype.slice.call(arguments, 1); if (hook in registry) { result = registry[hook].reduce(function (previousResult, currentAction) { call_args[0] = previousResult; var interimResult = currentAction.apply({ state: previousResult, hook: hook }, call_args); return interimResult !== undefined ? interimResult : previousResult; }, result); } return result; } /** * remove an action again */ function remove_hook(hook, action) { if (hook in registry) { for (var i = 0; i < registry[hook].length; i++) { if (registry[hook][i] === action) { registry[hook].splice(i, 1); break; } } } } /** * add an action to a hook */ function add_hook(hook, action, position) { if (!(hook in registry)) { registry[hook] = []; } if (position === undefined) { position = registry[hook].length; } registry[hook].splice(position, 0, action); } /** * return either the data of a hook call or the result of action, if the * former is undefined * * @return function a function wrapper around action */ function return_hook_or (hook, action) { return function () { var data = call_hook(hook, Array.prototype.slice.call(arguments)); if (data !== undefined) { return data; } return action.apply(this, arguments); }; } /* the following code is borrowed from the WebComponents project, licensed * under the BSD license. Source: * <https://github.com/webcomponents/webcomponentsjs/blob/5283db1459fa2323e5bfc8b9b5cc1753ed85e3d0/src/WebComponents/dom.js#L53-L78> */ // defaultPrevented is broken in IE. // https://connect.microsoft.com/IE/feedback/details/790389/event-defaultprevented-returns-false-after-preventdefault-was-called var workingDefaultPrevented = function () { var e = document.createEvent('Event'); e.initEvent('foo', true, true); e.preventDefault(); return e.defaultPrevented; }(); if (!workingDefaultPrevented) { (function () { var origPreventDefault = window.Event.prototype.preventDefault; window.Event.prototype.preventDefault = function () { if (!this.cancelable) { return; } origPreventDefault.call(this); Object.defineProperty(this, 'defaultPrevented', { get: function get() { return true; }, configurable: true }); }; })(); } /* end of borrowed code */ function create_event(name) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _ref$bubbles = _ref.bubbles; var bubbles = _ref$bubbles === undefined ? true : _ref$bubbles; var _ref$cancelable = _ref.cancelable; var cancelable = _ref$cancelable === undefined ? false : _ref$cancelable; var event = document.createEvent('Event'); event.initEvent(name, bubbles, cancelable); return event; } function trigger_event (element, event) { var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var _ref2$bubbles = _ref2.bubbles; var bubbles = _ref2$bubbles === undefined ? true : _ref2$bubbles; var _ref2$cancelable = _ref2.cancelable; var cancelable = _ref2$cancelable === undefined ? false : _ref2$cancelable; var payload = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; if (!(event instanceof window.Event)) { event = create_event(event, { bubbles: bubbles, cancelable: cancelable }); } for (var key in payload) { if (payload.hasOwnProperty(key)) { event[key] = payload[key]; } } element.dispatchEvent(event); return event; } /* and datetime-local? Spec says “Nah!” */ var dates = ['datetime', 'date', 'month', 'week', 'time']; var plain_numbers = ['number', 'range']; /* everything that returns something meaningful for valueAsNumber and * can have the step attribute */ var numbers = dates.concat(plain_numbers, 'datetime-local'); /* the spec says to only check those for syntax in validity.typeMismatch. * ¯\_(ツ)_/¯ */ var type_checked = ['email', 'url']; /* check these for validity.badInput */ var input_checked = ['email', 'date', 'month', 'week', 'time', 'datetime', 'datetime-local', 'number', 'range', 'color']; var text_types = ['text', 'search', 'tel', 'password'].concat(type_checked); /* input element types, that are candidates for the validation API. * Missing from this set are: button, hidden, menu (from <button>), reset and * the types for non-<input> elements. */ var validation_candidates = ['checkbox', 'color', 'file', 'image', 'radio', 'submit'].concat(numbers, text_types); /* all known types of <input> */ var inputs = ['button', 'hidden', 'reset'].concat(validation_candidates); /* apparently <select> and <textarea> have types of their own */ var non_inputs = ['select-one', 'select-multiple', 'textarea']; /** * mark an object with a '__hyperform=true' property * * We use this to distinguish our properties from the native ones. Usage: * js> mark(obj); * js> assert(obj.__hyperform === true) */ function mark (obj) { if (['object', 'function'].indexOf(typeof obj) > -1) { delete obj.__hyperform; Object.defineProperty(obj, '__hyperform', { configurable: true, enumerable: false, value: true }); } return obj; } /** * the internal storage for messages */ var store = new WeakMap(); /* jshint -W053 */ var message_store = { set: function set(element, message) { var is_custom = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (element instanceof window.HTMLFieldSetElement) { var wrapped_form = get_wrapper(element); if (wrapped_form && !wrapped_form.settings.extend_fieldset) { /* make this a no-op for <fieldset> in strict mode */ return message_store; } } if (typeof message === 'string') { message = new String(message); } if (is_custom) { message.is_custom = true; } mark(message); store.set(element, message); /* allow the :invalid selector to match */ if ('_original_setCustomValidity' in element) { element._original_setCustomValidity(message.toString()); } return message_store; }, get: function get(element) { var message = store.get(element); if (message === undefined && '_original_validationMessage' in element) { /* get the browser's validation message, if we have none. Maybe it * knows more than we. */ message = new String(element._original_validationMessage); } return message ? message : new String(''); }, delete: function _delete(element) { if ('_original_setCustomValidity' in element) { element._original_setCustomValidity(''); } return store.delete(element); } }; /** * counter that will be incremented with every call * * Will enforce uniqueness, as long as no more than 1 hyperform scripts * are loaded. (In that case we still have the "random" part below.) */ var uid = 0; /** * generate a random ID * * @see https://gist.github.com/gordonbrander/2230317 */ function generate_id () { var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'hf_'; return prefix + uid++ + Math.random().toString(36).substr(2); } var warnings_cache = new WeakMap(); var DefaultRenderer = { /** * called when a warning should become visible */ attach_warning: function attach_warning(warning, element) { /* should also work, if element is last, * http://stackoverflow.com/a/4793630/113195 */ element.parentNode.insertBefore(warning, element.nextSibling); }, /** * called when a warning should vanish */ detach_warning: function detach_warning(warning, element) { warning.parentNode.removeChild(warning); }, /** * called when feedback to an element's state should be handled * * i.e., showing and hiding warnings */ show_warning: function show_warning(element) { var sub_radio = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var msg = message_store.get(element).toString(); var warning = warnings_cache.get(element); if (msg) { if (!warning) { var wrapper = get_wrapper(element); warning = document.createElement('div'); warning.className = wrapper && wrapper.settings.classes.warning || 'hf-warning'; warning.id = generate_id(); warning.setAttribute('aria-live', 'polite'); warnings_cache.set(element, warning); } element.setAttribute('aria-errormessage', warning.id); warning.textContent = msg; Renderer.attach_warning(warning, element); } else if (warning && warning.parentNode) { element.removeAttribute('aria-errormessage'); Renderer.detach_warning(warning, element); } if (!sub_radio && element.type === 'radio' && element.form) { /* render warnings for all other same-name radios, too */ Array.prototype.filter.call(document.getElementsByName(element.name), function (radio) { return radio.name === element.name && radio.form === element.form; }).map(function (radio) { return Renderer.show_warning(radio, 'sub_radio'); }); } } }; var Renderer = { attach_warning: DefaultRenderer.attach_warning, detach_warning: DefaultRenderer.detach_warning, show_warning: DefaultRenderer.show_warning, set: function set(renderer, action) { if (!action) { action = DefaultRenderer[renderer]; } Renderer[renderer] = action; } }; /** * check element's validity and report an error back to the user */ function reportValidity(element) { /* if this is a <form>, report validity of all child inputs */ if (element instanceof window.HTMLFormElement) { return Array.prototype.map.call(element.elements, reportValidity).every(function (b) { return b; }); } /* we copy checkValidity() here, b/c we have to check if the "invalid" * event was canceled. */ var valid = ValidityState(element).valid; var event; if (valid) { var wrapped_form = get_wrapper(element); if (wrapped_form && wrapped_form.settings.valid_event) { event = trigger_event(element, 'valid', { cancelable: true }); } } else { event = trigger_event(element, 'invalid', { cancelable: true }); } if (!event || !event.defaultPrevented) { Renderer.show_warning(element); } return valid; } /** * submit a form, because `element` triggered it * * This method also dispatches a submit event on the form prior to the * submission. The event contains the trigger element as `submittedVia`. * * If the element is a button with a name, the name=value pair will be added * to the submitted data. */ function submit_form_via(element) { /* apparently, the submit event is not triggered in most browsers on * the submit() method, so we do it manually here to model a natural * submit as closely as possible. * Now to the fun fact: If you trigger a submit event from a form, what * do you think should happen? * 1) the form will be automagically submitted by the browser, or * 2) nothing. * And as you already suspected, the correct answer is: both! Firefox * opts for 1), Chrome for 2). Yay! */ var event_got_cancelled; var submit_event = create_event('submit', { cancelable: true }); /* force Firefox to not submit the form, then fake preventDefault() */ submit_event.preventDefault(); Object.defineProperty(submit_event, 'defaultPrevented', { value: false, writable: true }); Object.defineProperty(submit_event, 'preventDefault', { value: function value() { return submit_event.defaultPrevented = event_got_cancelled = true; }, writable: true }); trigger_event(element.form, submit_event, {}, { submittedVia: element }); if (!event_got_cancelled) { add_submit_field(element); window.HTMLFormElement.prototype.submit.call(element.form); window.setTimeout(function () { return remove_submit_field(element); }); } } /** * if a submit button was clicked, add its name=value by means of a type=hidden * input field */ function add_submit_field(button) { if (['image', 'submit'].indexOf(button.type) > -1 && button.name) { var wrapper = get_wrapper(button.form) || {}; var submit_helper = wrapper.submit_helper; if (submit_helper) { if (submit_helper.parentNode) { submit_helper.parentNode.removeChild(submit_helper); } } else { submit_helper = document.createElement('input'); submit_helper.type = 'hidden'; wrapper.submit_helper = submit_helper; } submit_helper.name = button.name; submit_helper.value = button.value; button.form.appendChild(submit_helper); } } /** * remove a possible helper input, that was added by `add_submit_field` */ function remove_submit_field(button) { if (['image', 'submit'].indexOf(button.type) > -1 && button.name) { var wrapper = get_wrapper(button.form) || {}; var submit_helper = wrapper.submit_helper; if (submit_helper && submit_helper.parentNode) { submit_helper.parentNode.removeChild(submit_helper); } } } /** * check a form's validity and submit it * * The method triggers a cancellable `validate` event on the form. If the * event is cancelled, form submission will be aborted, too. * * If the form is found to contain invalid fields, focus the first field. */ function check(event) { /* trigger a "validate" event on the form to be submitted */ var val_event = trigger_event(event.target.form, 'validate', { cancelable: true }); if (val_event.defaultPrevented) { /* skip the whole submit thing, if the validation is canceled. A user * can still call form.submit() afterwards. */ return; } var valid = true; var first_invalid; Array.prototype.map.call(event.target.form.elements, function (element) { if (!reportValidity(element)) { valid = false; if (!first_invalid && 'focus' in element) { first_invalid = element; } } }); if (valid) { submit_form_via(event.target); } else if (first_invalid) { /* focus the first invalid element, if validation went south */ first_invalid.focus(); } } /** * test if node is a submit button */ function is_submit_button(node) { return ( /* must be an input or button element... */ (node.nodeName === 'INPUT' || node.nodeName === 'BUTTON') && ( /* ...and have a submitting type */ node.type === 'image' || node.type === 'submit') ); } /** * test, if the click event would trigger a submit */ function is_submitting_click(event) { return ( /* prevented default: won't trigger a submit */ !event.defaultPrevented && ( /* left button or middle button (submits in Chrome) */ !('button' in event) || event.button < 2) && /* must be a submit button... */ is_submit_button(event.target) && /* the button needs a form, that's going to be submitted */ event.target.form && /* again, if the form should not be validated, we're out of the game */ !event.target.form.hasAttribute('novalidate') ); } /** * test, if the keypress event would trigger a submit */ function is_submitting_keypress(event) { return ( /* prevented default: won't trigger a submit */ !event.defaultPrevented && ( /* ...and <Enter> was pressed... */ event.keyCode === 13 && /* ...on an <input> that is... */ event.target.nodeName === 'INPUT' && /* ...a standard text input field (not checkbox, ...) */ text_types.indexOf(event.target.type) > -1 || /* or <Enter> or <Space> was pressed... */ (event.keyCode === 13 || event.keyCode === 32) && /* ...on a submit button */ is_submit_button(event.target)) && /* there's a form... */ event.target.form && /* ...and the form allows validation */ !event.target.form.hasAttribute('novalidate') ); } /** * catch explicit submission by click on a button */ function click_handler(event) { if (is_submitting_click(event)) { event.preventDefault(); if (is_submit_button(event.target) && event.target.hasAttribute('formnovalidate')) { /* if validation should be ignored, we're not interested in any checks */ submit_form_via(event.target); } else { check(event); } } } /** * catch explicit submission by click on a button, but circumvent validation */ function ignored_click_handler(event) { if (is_submitting_click(event)) { event.preventDefault(); submit_form_via(event.target); } } /** * catch implicit submission by pressing <Enter> in some situations */ function keypress_handler(event) { if (is_submitting_keypress(event)) { var wrapper = get_wrapper(event.target.form) || { settings: {} }; if (wrapper.settings.prevent_implicit_submit) { /* user doesn't want an implicit submit. Cancel here. */ event.preventDefault(); return; } /* check, that there is no submit button in the form. Otherwise * that should be clicked. */ var el = event.target.form.elements.length; var submit; for (var i = 0; i < el; i++) { if (['image', 'submit'].indexOf(event.target.form.elements[i].type) > -1) { submit = event.target.form.elements[i]; break; } } event.preventDefault(); if (submit) { submit.click(); } else { check(event); } } } /** * catch implicit submission by pressing <Enter> in some situations, but circumvent validation */ function ignored_keypress_handler(event) { if (is_submitting_keypress(event)) { /* check, that there is no submit button in the form. Otherwise * that should be clicked. */ var el = event.target.form.elements.length; var submit; for (var i = 0; i < el; i++) { if (['image', 'submit'].indexOf(event.target.form.elements[i].type) > -1) { submit = event.target.form.elements[i]; break; } } event.preventDefault(); if (submit) { submit.click(); } else { submit_form_via(event.target); } } } /** * catch all relevant events _prior_ to a form being submitted * * @param bool ignore bypass validation, when an attempt to submit the * form is detected. True, when the wrapper's revalidate * setting is 'never'. */ function catch_submit(listening_node) { var ignore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (ignore) { listening_node.addEventListener('click', ignored_click_handler); listening_node.addEventListener('keypress', ignored_keypress_handler); } else { listening_node.addEventListener('click', click_handler); listening_node.addEventListener('keypress', keypress_handler); } } /** * decommission the event listeners from catch_submit() again */ function uncatch_submit(listening_node) { listening_node.removeEventListener('click', ignored_click_handler); listening_node.removeEventListener('keypress', ignored_keypress_handler); listening_node.removeEventListener('click', click_handler); listening_node.removeEventListener('keypress', keypress_handler); } /** * remove `property` from element and restore _original_property, if present */ function uninstall_property (element, property) { delete element[property]; var original_descriptor = Object.getOwnPropertyDescriptor(element, '_original_' + property); if (original_descriptor) { Object.defineProperty(element, property, original_descriptor); } } /** * add `property` to an element * * js> installer(element, 'foo', { value: 'bar' }); * js> assert(element.foo === 'bar'); */ function install_property (element, property, descriptor) { descriptor.configurable = true; descriptor.enumerable = true; if ('value' in descriptor) { descriptor.writable = true; } var original_descriptor = Object.getOwnPropertyDescriptor(element, property); if (original_descriptor) { if (original_descriptor.configurable === false) { var wrapper = get_wrapper(element); if (wrapper && wrapper.settings.debug) { /* global console */ console.log('[hyperform] cannot install custom property ' + property); } return false; } /* we already installed that property... */ if (original_descriptor.get && original_descriptor.get.__hyperform || original_descriptor.value && original_descriptor.value.__hyperform) { return; } /* publish existing property under new name, if it's not from us */ Object.defineProperty(element, '_original_' + property, original_descriptor); } delete element[property]; Object.defineProperty(element, property, descriptor); return true; } function is_field (element) { return element instanceof window.HTMLButtonElement || element instanceof window.HTMLInputElement || element instanceof window.HTMLSelectElement || element instanceof window.HTMLTextAreaElement || element instanceof window.HTMLFieldSetElement || element === window.HTMLButtonElement.prototype || element === window.HTMLInputElement.prototype || element === window.HTMLSelectElement.prototype || element === window.HTMLTextAreaElement.prototype || element === window.HTMLFieldSetElement.prototype; } /** * set a custom validity message or delete it with an empty string */ function setCustomValidity(element, msg) { message_store.set(element, msg, true); } function sprintf (str) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var args_length = args.length; var global_index = 0; return str.replace(/%([0-9]+\$)?([sl])/g, function (match, position, type) { var local_index = global_index; if (position) { local_index = Number(position.replace(/\$$/, '')) - 1; } global_index += 1; var arg = ''; if (args_length > local_index) { arg = args[local_index]; } if (arg instanceof Date || typeof arg === 'number' || arg instanceof Number) { /* try getting a localized representation of dates and numbers, if the * browser supports this */ if (type === 'l') { arg = (arg.toLocaleString || arg.toString).call(arg); } else { arg = arg.toString(); } } return arg; }); } /* For a given date, get the ISO week number * * Source: http://stackoverflow.com/a/6117889/113195 * * Based on information at: * * http://www.merlyn.demon.co.uk/weekcalc.htm#WNR * * Algorithm is to find nearest thursday, it's year * is the year of the week number. Then get weeks * between that date and the first day of that year. * * Note that dates in one year can be weeks of previous * or next year, overlap is up to 3 days. * * e.g. 2014/12/29 is Monday in week 1 of 2015 * 2012/1/1 is Sunday in week 52 of 2011 */ function get_week_of_year (d) { /* Copy date so don't modify original */ d = new Date(+d); d.setUTCHours(0, 0, 0); /* Set to nearest Thursday: current date + 4 - current day number * Make Sunday's day number 7 */ d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7)); /* Get first day of year */ var yearStart = new Date(d.getUTCFullYear(), 0, 1); /* Calculate full weeks to nearest Thursday */ var weekNo = Math.ceil(((d - yearStart) / 86400000 + 1) / 7); /* Return array of year and week number */ return [d.getUTCFullYear(), weekNo]; } function pad(num) { var size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; var s = num + ''; while (s.length < size) { s = '0' + s; } return s; } /** * calculate a string from a date according to HTML5 */ function date_to_string(date, element_type) { if (!(date instanceof Date)) { return null; } switch (element_type) { case 'datetime': return date_to_string(date, 'date') + 'T' + date_to_string(date, 'time'); case 'datetime-local': return sprintf('%s-%s-%sT%s:%s:%s.%s', date.getFullYear(), pad(date.getMonth() + 1), pad(date.getDate()), pad(date.getHours()), pad(date.getMinutes()), pad(date.getSeconds()), pad(date.getMilliseconds(), 3)).replace(/(:00)?\.000$/, ''); case 'date': return sprintf('%s-%s-%s', date.getUTCFullYear(), pad(date.getUTCMonth() + 1), pad(date.getUTCDate())); case 'month': return sprintf('%s-%s', date.getUTCFullYear(), pad(date.getUTCMonth() + 1)); case 'week': var params = get_week_of_year(date); return sprintf.call(null, '%s-W%s', params[0], pad(params[1])); case 'time': return sprintf('%s:%s:%s.%s', pad(date.getUTCHours()), pad(date.getUTCMinutes()), pad(date.getUTCSeconds()), pad(date.getUTCMilliseconds(), 3)).replace(/(:00)?\.000$/, ''); } return null; } /** * return a new Date() representing the ISO date for a week number * * @see http://stackoverflow.com/a/16591175/113195 */ function get_date_from_week (week, year) { var date = new Date(Date.UTC(year, 0, 1 + (week - 1) * 7)); if (date.getUTCDay() <= 4 /* thursday */) { date.setUTCDate(date.getUTCDate() - date.getUTCDay() + 1); } else { date.setUTCDate(date.getUTCDate() + 8 - date.getUTCDay()); } return date; } /** * calculate a date from a string according to HTML5 */ function string_to_date (string, element_type) { var date = new Date(0); var ms; switch (element_type) { case 'datetime': if (!/^([0-9]{4,})-([0-9]{2})-([0-9]{2})T([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(string)) { return null; } ms = RegExp.$7 || '000'; while (ms.length < 3) { ms += '0'; } date.setUTCFullYear(Number(RegExp.$1)); date.setUTCMonth(Number(RegExp.$2) - 1, Number(RegExp.$3)); date.setUTCHours(Number(RegExp.$4), Number(RegExp.$5), Number(RegExp.$6 || 0), Number(ms)); return date; case 'date': if (!/^([0-9]{4,})-([0-9]{2})-([0-9]{2})$/.test(string)) { return null; } date.setUTCFullYear(Number(RegExp.$1)); date.setUTCMonth(Number(RegExp.$2) - 1, Number(RegExp.$3)); return date; case 'month': if (!/^([0-9]{4,})-([0-9]{2})$/.test(string)) { return null; } date.setUTCFullYear(Number(RegExp.$1)); date.setUTCMonth(Number(RegExp.$2) - 1, 1); return date; case 'week': if (!/^([0-9]{4,})-W(0[1-9]|[1234][0-9]|5[0-3])$/.test(string)) { return null; } return get_date_from_week(Number(RegExp.$2), Number(RegExp.$1)); case 'time': if (!/^([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(string)) { return null; } ms = RegExp.$4 || '000'; while (ms.length < 3) { ms += '0'; } date.setUTCHours(Number(RegExp.$1), Number(RegExp.$2), Number(RegExp.$3 || 0), Number(ms)); return date; } return null; } /** * calculate a date from a string according to HTML5 */ function string_to_number (string, element_type) { var rval = string_to_date(string, element_type); if (rval !== null) { return +rval; } /* not parseFloat, because we want NaN for invalid values like "1.2xxy" */ return Number(string); } /** * get the element's type in a backwards-compatible way */ function get_type (element) { if (element instanceof window.HTMLTextAreaElement) { return 'textarea'; } else if (element instanceof window.HTMLSelectElement) { return element.hasAttribute('multiple') ? 'select-multiple' : 'select-one'; } else if (element instanceof window.HTMLButtonElement) { return (element.getAttribute('type') || 'submit').toLowerCase(); } else if (element instanceof window.HTMLInputElement) { var attr = (element.getAttribute('type') || '').toLowerCase(); if (attr && inputs.indexOf(attr) > -1) { return attr; } else { /* perhaps the DOM has in-depth knowledge. Take that before returning * 'text'. */ return element.type || 'text'; } } return ''; } /** * the following validation messages are from Firefox source, * http://mxr.mozilla.org/mozilla-central/source/dom/locales/en-US/chrome/dom/dom.properties * released under MPL license, http://mozilla.org/MPL/2.0/. */ var catalog = { en: { TextTooLong: 'Please shorten this text to %l characters or less (you are currently using %l characters).', ValueMissing: 'Please fill out this field.', CheckboxMissing: 'Please check this box if you want to proceed.', RadioMissing: 'Please select one of these options.', FileMissing: 'Please select a file.', SelectMissing: 'Please select an item in the list.', InvalidEmail: 'Please enter an email address.', InvalidURL: 'Please enter a URL.', PatternMismatch: 'Please match the requested format.', PatternMismatchWithTitle: 'Please match the requested format: %l.', NumberRangeOverflow: 'Please select a value that is no more than %l.', DateRangeOverflow: 'Please select a value that is no later than %l.', TimeRangeOverflow: 'Please select a value that is no later than %l.', NumberRangeUnderflow: 'Please select a value that is no less than %l.', DateRangeUnderflow: 'Please select a value that is no earlier than %l.', TimeRangeUnderflow: 'Please select a value that is no earlier than %l.', StepMismatch: 'Please select a valid value. The two nearest valid values are %l and %l.', StepMismatchOneValue: 'Please select a valid value. The nearest valid value is %l.', BadInputNumber: 'Please enter a number.' } }; var language = 'en'; function set_language(newlang) { language = newlang; } function add_translation(lang, new_catalog) { if (!(lang in catalog)) { catalog[lang] = {}; } for (var key in new_catalog) { if (new_catalog.hasOwnProperty(key)) { catalog[lang][key] = new_catalog[key]; } } } function _ (s) { if (language in catalog && s in catalog[language]) { return catalog[language][s]; } else if (s in catalog.en) { return catalog.en[s]; } return s; } var default_step = { 'datetime-local': 60, datetime: 60, time: 60 }; var step_scale_factor = { 'datetime-local': 1000, datetime: 1000, date: 86400000, week: 604800000, time: 1000 }; var default_step_base = { week: -259200000 }; var default_min = { range: 0 }; var default_max = { range: 100 }; /** * get previous and next valid values for a stepped input element */ function get_next_valid (element) { var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var type = get_type(element); var aMin = element.getAttribute('min'); var min = default_min[type] || NaN; if (aMin) { var pMin = string_to_number(aMin, type); if (!isNaN(pMin)) { min = pMin; } } var aMax = element.getAttribute('max'); var max = default_max[type] || NaN; if (aMax) { var pMax = string_to_number(aMax, type); if (!isNaN(pMax)) { max = pMax; } } var aStep = element.getAttribute('step'); var step = default_step[type] || 1; if (aStep && aStep.toLowerCase() === 'any') { /* quick return: we cannot calculate prev and next */ return [_('any value'), _('any value')]; } else if (aStep) { var pStep = string_to_number(aStep, type); if (!isNaN(pStep)) { step = pStep; } } var default_value = string_to_number(element.getAttribute('value'), type); var value = string_to_number(element.value || element.getAttribute('value'), type); if (isNaN(value)) { /* quick return: we cannot calculate without a solid base */ return [_('any valid value'), _('any valid value')]; } var step_base = !isNaN(min) ? min : !isNaN(default_value) ? default_value : default_step_base[type] || 0; var scale = step_scale_factor[type] || 1; var prev = step_base + Math.floor((value - step_base) / (step * scale)) * (step * scale) * n; var next = step_base + (Math.floor((value - step_base) / (step * scale)) + 1) * (step * scale) * n; if (prev < min) { prev = null; } else if (prev > max) { prev = max; } if (next > max) { next = null; } else if (next < min) { next = min; } /* convert to date objects, if appropriate */ if (dates.indexOf(type) > -1) { prev = date_to_string(new Date(prev), type); next = date_to_string(new Date(next), type); } return [prev, next]; } /** * implement the valueAsDate functionality * * @see https://html.spec.whatwg.org/multipage/forms.html#dom-input-valueasdate */ function valueAsDate(element) { var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; var type = get_type(element); if (dates.indexOf(type) > -1) { if (value !== undefined) { /* setter: value must be null or a Date() */ if (value === null) { element.value = ''; } else if (value instanceof Date) { if (isNaN(value.getTime())) { element.value = ''; } else { element.value = date_to_string(value, type); } } else { throw new window.DOMException('valueAsDate setter encountered invalid value', 'TypeError'); } return; } var value_date = string_to_date(element.value, type); return value_date instanceof Date ? value_date : null; } else if (value !== undefined) { /* trying to set a date on a not-date input fails */ throw new window.DOMException('valueAsDate setter cannot set date on this element', 'InvalidStateError'); } return null; } /** * implement the valueAsNumber functionality * * @see https://html.spec.whatwg.org/multipage/forms.html#dom-input-valueasnumber */ function valueAsNumber(element) { var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; var type = get_type(element); if (numbers.indexOf(type) > -1) { if (type === 'range' && element.hasAttribute('multiple')) { /* @see https://html.spec.whatwg.org/multipage/forms.html#do-not-apply */ return NaN; } if (value !== undefined) { /* setter: value must be NaN or a finite number */ if (isNaN(value)) { element.value = ''; } else if (typeof value === 'number' && window.isFinite(value)) { try { /* try setting as a date, but... */ valueAsDate(element, new Date(value)); } catch (e) { /* ... when valueAsDate is not responsible, ... */ if (!(e instanceof window.DOMException)) { throw e; } /* ... set it via Number.toString(). */ element.value = value.toString(); } } else { throw new window.DOMException('valueAsNumber setter encountered invalid value', 'TypeError'); } return; } return string_to_number(element.value, type); } else if (value !== undefined) { /* trying to set a number on a not-number input fails */ throw new window.DOMException('valueAsNumber setter cannot set number on this element', 'InvalidStateError'); } return NaN; } /** * */ function stepDown(element) { var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; if (numbers.indexOf(get_type(element)) === -1) { throw new window.DOMException('stepDown encountered invalid type', 'InvalidStateError'); } if ((element.getAttribute('step') || '').toLowerCase() === 'any') { throw new window.DOMException('stepDown encountered step "any"', 'InvalidStateError'); } var prev = get_next_valid(element, n)[0]; if (prev !== null) { valueAsNumber(element, prev); } } /** * */ function stepUp(element) { var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; if (numbers.indexOf(get_type(element)) === -1) { throw new window.DOMException('stepUp encountered invalid type', 'InvalidStateError'); } if ((element.getAttribute('step') || '').toLowerCase() === 'any') { throw new window.DOMException('stepUp encountered step "any"', 'InvalidStateError'); } var next = get_next_valid(element, n)[1]; if (next !== null) { valueAsNumber(element, next); } } /** * get the validation message for an element, empty string, if the element * satisfies all constraints. */ function validationMessage(element) { var msg = message_store.get(element); if (!msg) { return ''; } /* make it a primitive again, since message_store returns String(). */ return msg.toString(); } /** * check, if an element will be subject to HTML5 validation at all */ function willValidate(element) { return is_validation_candidate(element); } var gA = function gA(prop) { return function () { return do_filter('attr_get_' + prop, this.getAttribute(prop), this); }; }; var sA = function sA(prop) { return function (value) { this.setAttribute(prop, do_filter('attr_set_' + prop, value, this)); }; }; var gAb = function gAb(prop) { return function () { return do_filter('attr_get_' + prop, this.hasAttribute(prop), this); }; }; var sAb = function sAb(prop) { return function (value) { if (do_filter('attr_set_' + prop, value, this)) { this.setAttribute(prop, prop); } else { this.removeAttribute(prop); } }; }; var gAn = function gAn(prop) { return function () { return do_filter('attr_get_' + prop, Math.max(0, Number(this.getAttribute(prop))), this); }; }; var sAn = function sAn(prop) { return function (value) { value = do_filter('attr_set_' + prop, value, this); if (/^[0-9]+$/.test(value)) { this.setAttribute(prop, value); } }; }; function install_properties(element) { var _arr = ['accept', 'max', 'min', 'pattern', 'placeholder', 'step']; for (var _i = 0; _i < _arr.length; _i++) { var prop = _arr[_i]; install_property(element, prop, { get: gA(prop), set: sA(prop) }); } var _arr2 = ['multiple', 'required', 'readOnly']; for (var _i2 = 0; _i2 < _arr2.length; _i2++) { var _prop = _arr2[_i2]; install_property(element, _prop, { get: gAb(_prop.toLowerCase()), set: sAb(_prop.toLowerCase()) }); } var _arr3 = ['minLength', 'maxLength']; for (var _i3 = 0; _i3 < _arr3.length; _i3++) { var _prop2 = _arr3[_i3]; install_property(element, _prop2, { get: gAn(_prop2.toLowerCase()), set: sAn(_prop2.toLowerCase()) }); } } function uninstall_properties(element) { var _arr4 = ['accept', 'max', 'min', 'pattern', 'placeholder', 'step', 'multiple', 'required', 'readOnly', 'minLength', 'maxLength']; for (var _i4 = 0; _i4 < _arr4.length; _i4++) { var prop = _arr4[_i4]; uninstall_property(element, prop); } } var polyfills = { checkValidity: { value: mark(function () { return checkValidity(this); }) }, reportValidity: { value: mark(function () { return reportValidity(this); }) }, setCustomValidity: { value: mark(function (msg) { return setCustomValidity(this, msg); }) }, stepDown: { value: mark(function () { var n = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; return stepDown(this, n); }) }, stepUp: { value: mark(function () { var n = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; return stepUp(this, n); }) }, validationMessage: { get: mark(function () { return validationMessage(this); }) }, validity: { get: mark(function () { return ValidityState(this); }) }, valueAsDate: { get: mark(function () { return valueAsDate(this); }), set: mark(function (value) { valueAsDate(this, value); }) }, valueAsNumber: { get: mark(function () { return valueAsNumber(this); }), set: mark(function (value) { valueAsNumber(this, value); }) }, willValidate: { get: mark(function () { return willValidate(this); }) } }; function polyfill (element) { if (is_field(element)) { for (var prop in polyfills) { install_property(element, prop, polyfills[prop]); } install_properties(element); } else if (element instanceof window.HTMLFormElement || element === window.HTMLFormElement.prototype) { install_property(element, 'checkValidity', polyfills.checkValidity); install_property(element, 'reportValidity', polyfills.reportValidity); } } function polyunfill (element) { if (is_field(element)) { uninstall_property(element, 'checkValidity'); uninstall_property(element, 'reportValidity'); uninstall_property(element, 'setCustomValidity'); uninstall_property(element, 'stepDown'); uninstall_property(element, 'stepUp'); uninstall_property(element, 'validationMessage'); uninstall_property(element, 'validity'); uninstall_property(element, 'valueAsDate'); uninstall_property(element, 'valueAsNumber'); uninstall_property(element, 'willValidate'); uninstall_properties(element); } else if (element instanceof window.HTMLFormElement) { uninstall_property(element, 'checkValidity'); uninstall_property(element, 'reportValidity'); } } var instances = new WeakMap(); /** * wrap <form>s, window or document, that get treated with the global * hyperform() */ function Wrapper(form, settings) { /* do not allow more than one instance per form. Otherwise we'd end * up with double event handlers, polyfills re-applied, ... */ var existing = instances.get(form); if (existing) { existing.settings = settings; return existing; } this.form = form; this.settings = settings; this.revalidator = this.revalidate.bind(this); instances.set(form, this); catch_submit(form, settings.revalidate === 'never'); if (form === window || form instanceof window.HTMLDocument) { /* install on the prototypes, when called for the whole document */ this.install([window.HTMLButtonElement.prototype, window.HTMLInputElement.prototype, window.HTMLSelectElement.prototype, window.HTMLTextAreaElement.prototype, window.HTMLFieldSetElement.prototype]); polyfill(window.HTMLFormElement); } else if (form instanceof window.HTMLFormElement || form instanceof window.HTMLFieldSetElement) { this.install(form.elements); if (form instanceof window.HTMLFormElement) { polyfill(form); } } if (settings.revalidate === 'oninput' || settings.revalidate === 'hybrid') { /* in a perfect world we'd just bind to "input", but support here is * abysmal: http://caniuse.com/#feat=input-event */ form.addEventListener('keyup', this.revalidator); form.addEventListener('change', this.revalidator); } if (settings.revalidate === 'onblur' || settings.revalidate === 'hybrid') { /* useCapture=true, because `blur` doesn't bubble. See * https://developer.mozilla.org/en-US/docs/Web/Events/blur#Event_delegation * for a discussion */ form.addEventListener('blur', this.revalidator, true); } } Wrapper.prototype = { destroy: function destroy() { uncatch_submit(this.form); instances.delete(this.form); this.form.removeEventListener('keyup', this.revalidator); this.form.removeEventListener('change', this.revalidator); this.form.removeEventListener('blur', this.revalidator, true); if (this.form === window || this.form instanceof window.HTMLDocument) { this.uninstall([window.HTMLButtonElement.prototype, window.HTMLInputElement.prototype, window.HTMLSelectElement.prototype, window.HTMLTextAreaElement.prototype, window.HTMLFieldSetElement.prototype]); polyunfill(window.HTMLFormElement); } else if (this.form instanceof window.HTMLFormElement || this.form instanceof window.HTMLFieldSetElement) { this.uninstall(this.form.elements); if (this.form instanceof window.HTMLFormElement) { polyunfill(this.form); } } }, /** * revalidate an input element */ revalidate: function revalidate(event) { if (event.target instanceof window.HTMLButtonElement || event.target instanceof window.HTMLTextAreaElement || event.target instanceof window.HTMLSelectElement || event.target instanceof window.HTMLInputElement) { if (this.settings.revalidate === 'hybrid') { /* "hybrid" somewhat simulates what browsers do. See for example * Firefox's :-moz-ui-invalid pseudo-class: * https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-ui-invalid */ if (event.type === 'blur' && event.target.value !== event.target.defaultValue || ValidityState(event.target).valid) { /* on blur, update the report when the value has changed from the * default or when the element is valid (possibly removing a still * standing invalidity report). */ reportValidity(event.target); } else if (event.type === 'keyup' || event.type === 'change') { if (ValidityState(event.target).valid) { // report instantly, when an element becomes valid, // postpone report to blur event, when an element is invalid reportValidity(event.target); } } } else { reportValidity(event.target); } } }, /** * install the polyfills on each given element * * If you add elements dynamically, you have to call install() on them * yourself: * * js> var form = hyperform(document.forms[0]); * js> document.forms[0].appendChild(input); * js> form.install(input); * * You can skip this, if you called hyperform on window or document. */ install: function install(els) { if (els instanceof window.Element) { els = [els]; } var els_length = els.length; for (var i = 0; i < els_length; i++) { polyfill(els[i]); } }, uninstall: function uninstall(els) { if (els instanceof window.Element) { els = [els]; } var els_length = els.length; for (var i = 0; i < els_length; i++) { polyunfill(els[i]); } } }; /** * try to get the appropriate wrapper for a specific element by looking up * its parent chain * * @return Wrapper | undefined */ function get_wrapper(element) { var wrapped; if (element.form) { /* try a shortcut with the element's <form> */ wrapped = instances.get(element.form); } /* walk up the parent nodes until document (including) */ while (!wrapped && element) { wrapped = instances.get(element); element = element.parentNode; } if (!wrapped) { /* try the global instance, if exists. This may also be undefined. */ wrapped = instances.get(window); } return wrapped; } /** * check if an element is a candidate for constraint validation * * @see https://html.spec.whatwg.org/multipage/forms.html#barred-from-constraint-validation */ function is_validation_candidate (element) { /* allow a shortcut via filters, e.g. to validate type=hidden fields */ var filtered = do_filter('is_validation_candidate', null, element); if (filtered !== null) { return !!filtered; } /* it must be any of those elements */ if (element instanceof window.HTMLSelectElement || element instanceof window.HTMLTextAreaElement || element instanceof window.HTMLButtonElement || element instanceof window.HTMLInputElement) { var type = get_type(element); /* its type must be in the whitelist or missing (select, textarea) */ if (!type || non_inputs.indexOf(type) > -1 || validation_candidates.indexOf(type) > -1) { /* it mustn't be disabled or readonly */ if (!element.hasAttribute('disabled') && !element.hasAttribute('readonly')) { var wrapped_form = get_wrapper(element); /* it hasn't got the (non-standard) attribute 'novalidate' or its * parent form has got the strict parameter */ if (wrapped_form && wrapped_form.settings.novalidate_on_elements || !element.hasAttribute('novalidate') || !element.noValidate) { /* it isn't part of a <fieldset disabled> */ var p = element.parentNode; while (p && p.nodeType === 1) { if (p instanceof window.HTMLFieldSetElement && p.hasAttribute('disabled')) { /* quick return, if it's a child of a disabled fieldset */ return false; } else if (p.nodeName.toUpperCase() === 'DATALIST') { /* quick return, if it's a child of a datalist * Do not use HTMLDataListElement to support older browsers, * too. * @see https://html.spec.whatwg.org/multipage/forms.html#the-datalist-element:barred-from-constraint-validation */ return false; } else if (p === element.form) { /* the outer boundary. We can stop looking for relevant * fieldsets. */ break; } p = p.parentNode; } /* then it's a candidate */ return true; } } } } /* this is no HTML5 validation candidate... */ return false; } function format_date (date) { var part = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; switch (part) { case 'date': return (date.toLocaleDateString || date.toDateString).call(date); case 'time': return (date.toLocaleTimeString || date.toTimeString).call(date); case 'month': return 'toLocaleDateString' in date ? date.toLocaleDateString(undefined, { year: 'numeric', month: '2-digit' }) : date.toDateString(); // case 'week': // TODO default: return (date.toLocaleString || date.toString).call(date); } } /** * patch String.length to account for non-BMP characters * * @see https://mathiasbynens.be/notes/javascript-unicode * We do not use the simple [...str].length, because it needs a ton of * polyfills in older browsers. */ function unicode_string_length (str) { return str.match(/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/g).length; } /** * internal storage for custom error messages */ var store$1 = new WeakMap(); /** * register custom error messages per element */ var custom_messages = { set: function set(element, validator, message) { var messages = store$1.get(element) || {}; messages[validator] = message; store$1.set(element, messages); return custom_messages; }, get: function get(element, validator) { var _default = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; var messages = store$1.get(element); if (messages === undefined || !(validator in messages)) { var data_id = 'data-' + validator.replace(/[A-Z]/g, '-$&').toLowerCase(); if (element.hasAttribute(data_id)) { /* if the element has a data-validator attribute, use this as fallback. * E.g., if validator == 'valueMissing', the element can specify a * custom validation message like this: * <input data-value-missing="Oh noes!"> */ return element.getAttribute(data_id); } return _default; } return messages[validator]; }, delete: function _delete(element) { var validator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; if (!validator) { return store$1.delete(element); } var messages = store$1.get(element) || {}; if (validator in messages) { delete messages[validator]; store$1.set(element, messages); return true; } return false; } }; var internal_registry = new WeakMap(); /** * A registry for custom validators * * slim wrapper around a WeakMap to ensure the values are arrays * (hence allowing > 1 validators per element) */ var custom_validator_registry = { set: function set(element, validator) { var current = internal_registry.get(element) || []; current.push(validator); internal_registry.set(element, current); return custom_validator_registry; }, get: function get(element) { return internal_registry.get(element) || []; }, delete: function _delete(element) { return internal_registry.delete(element); } }; /** * test whether the element suffers from bad input */ function test_bad_input (element) { var type = get_type(element); if (!is_validation_candidate(element) || input_checked.indexOf(type) === -1) { /* we're not interested, thanks! */ return true; } /* the browser hides some bad input from the DOM, e.g. malformed numbers, * email addresses with invalid punycode representation, ... We try to resort * to the original method here. The assumption is, that a browser hiding * bad input will hopefully also always support a proper * ValidityState.badInput */ if (!element.value) { if ('_original_validity' in element && !element._original_validity.__hyperform) { return !element._original_validity.badInput; } /* no value and no original badInput: Assume all's right. */ return true; } var result = true; switch (type) { case 'color': result = /^#[a-f0-9]{6}$/.test(element.value); break; case 'number': case 'range': result = !isNaN(Number(element.value)); break; case 'datetime': case 'date': case 'month': case 'week': case 'time': result = string_to_date(element.value, type) !== null; break; case 'datetime-local': result = /^([0-9]{4,})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(element.value); break; case 'tel': /* spec says No! Phone numbers can have all kinds of formats, so this * is expected to be a free-text field. */ // TODO we could allow a setting 'phone_regex' to be evaluated here. break; case 'email': break; } return result; } /** * test the max attribute * * we use Number() instead of parseFloat(), because an invalid attribute * value like "123abc" should result in an error. */ function test_max (element) { var type = get_type(element); if (!is_validation_candidate(element) || !element.value || !element.hasAttribute('max')) { /* we're not responsible here */ return true; } var value = void 0, max = void 0; if (dates.indexOf(type) > -1) { value = 1 * string_to_date(element.value, type); max = 1 * (string_to_date(element.getAttribute('max'), type) || NaN); } else { value = Number(element.value); max = Number(element.getAttribute('max')); } return isNaN(max) || value <= max; } /** * test the maxlength attribute */ function test_maxlength (element) { if (!is_validation_candidate(element) || !element.value || text_types.indexOf(get_type(element)) === -1 || !element.hasAttribute('maxlength') || !element.getAttribute('maxlength') // catch maxlength="" ) { return true; } var maxlength = parseInt(element.getAttribute('maxlength'), 10); /* check, if the maxlength value is usable at all. * We allow maxlength === 0 to basically disable input (Firefox does, too). */ if (isNaN(maxlength) || maxlength < 0) { return true; } return unicode_string_length(element.value) <= maxlength; } /** * test the min attribute * * we use Number() instead of parseFloat(), because an invalid attribute * value like "123abc" should result in an error. */ function test_min (element) { var type = get_type(element); if (!is_validation_candidate(element) || !element.value || !element.hasAttribute('min')) { /* we're not responsible here */ return true; } var value = void 0, min = void 0; if (dates.indexOf(type) > -1) { value = 1 * string_to_date(element.value, type); min = 1 * (string_to_date(element.getAttribute('min'), type) || NaN); } else { value = Number(element.value); min = Number(element.getAttribute('min')); } return isNaN(min) || value >= min; } /** * test the minlength attribute */ function test_minlength (element) { if (!is_validation_candidate(element) || !element.value || text_types.indexOf(get_type(element)) === -1 || !element.hasAttribute('minlength') || !element.getAttribute('minlength') // catch minlength="" ) { return true; } var minlength = parseInt(element.getAttribute('minlength'), 10); /* check, if the minlength value is usable at all. */ if (isNaN(minlength) || minlength < 0) { return true; } return unicode_string_length(element.value) >= minlength; } /** * test the pattern attribute */ function test_pattern (element) { return !is_validation_candidate(element) || !element.value || !element.hasAttribute('pattern') || new RegExp('^(?:' + element.getAttribute('pattern') + ')$').test(element.value); } /** * test the required attribute */ function test_required (element) { if (!is_validation_candidate(element) || !element.hasAttribute('required')) { /* nothing to do */ return true; } /* we don't need get_type() for element.type, because "checkbox" and "radio" * are well supported. */ switch (element.type) { case 'checkbox': return element.checked; //break; case 'radio': /* radio inputs have "required" fulfilled, if _any_ other radio * with the same name in this form is checked. */ return !!(element.checked || element.form && Array.prototype.filter.call(document.getElementsByName(element.name), function (radio) { return radio.name === element.name && radio.form === element.form && radio.checked; }).length > 0); //break; default: return !!element.value; } } /** * test the step attribute */ function test_step (element) { var type = get_type(element); if (!is_validation_candidate(element) || !element.value || numbers.indexOf(type) === -1 || (element.getAttribute('step') || '').toLowerCase() === 'any') { /* we're not responsible here. Note: If no step attribute is given, we * need to validate against the default step as per spec. */ return true; } var step = element.getAttribute('step'); if (step) { step = string_to_number(step, type); } else { step = default_step[type] || 1; } if (step <= 0 || isNaN(step)) { /* error in specified "step". We cannot validate against it, so the value * is true. */ return true; } var scale = step_scale_factor[type] || 1; var value = string_to_number(element.value, type); var min = string_to_number(element.getAttribute('min') || element.getAttribute('value') || '', type); if (isNaN(min)) { min = default_step_base[type] || 0; } if (type === 'month') { /* type=month has month-wide steps. See * https://html.spec.whatwg.org/multipage/forms.html#month-state-%28type=month%29 */ min = new Date(min).getUTCFullYear() * 12 + new Date(min).getUTCMonth(); value = new Date(value).getUTCFullYear() * 12 + new Date(value).getUTCMonth(); } var result = Math.abs(min - value) % (step * scale); return result < 0.00000001 || /* crappy floating-point arithmetics! */ result > step * scale - 0.00000001; } var ws_on_start_or_end = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; /** * trim a string of whitespace * * We don't use String.trim() to remove the need to polyfill it. */ function trim (str) { return str.replace(ws_on_start_or_end, ''); } /** * split a string on comma and trim the components * * As specified at * https://html.spec.whatwg.org/multipage/infrastructure.html#split-a-string-on-commas * plus removing empty entries. */ function comma_split (str) { return str.split(',').map(function (item) { return trim(item); }).filter(function (b) { return b; }); } /* we use a dummy <a> where we set the href to test URL validity * The definition is out of the "global" scope so that JSDOM can be instantiated * after loading Hyperform for tests. */ var url_canary; /* see https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address */ var email_pattern = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; /** * test the type-inherent syntax */ function test_type (element) { var type = get_type(element); if (!is_validation_candidate(element) || type !== 'file' && !element.value || type !== 'file' && type_checked.indexOf(type) === -1) { /* we're not responsible for this element */ return true; } var is_valid = true; switch (type) { case 'url': if (!url_canary) { url_canary = document.createElement('a'); } var value = trim(element.value); url_canary.href = value; is_valid = url_canary.href === value || url_canary.href === value + '/'; break; case 'email': if (element.hasAttribute('multiple')) { is_valid = comma_split(element.value).every(function (value) { return email_pattern.test(value); }); } else { is_valid = email_pattern.test(trim(element.value)); } break; case 'file': if ('files' in element && element.files.length && element.hasAttribute('accept')) { var patterns = comma_split(element.getAttribute('accept')).map(function (pattern) { if (/^(audio|video|image)\/\*$/.test(pattern)) { pattern = new RegExp('^' + RegExp.$1 + '/.+$'); } return pattern; }); if (!patterns.length) { break; } fileloop: for (var i = 0; i < element.files.length; i++) { /* we need to match a whitelist, so pre-set with false */ var file_valid = false; patternloop: for (var j = 0; j < patterns.length; j++) { var file = element.files[i]; var pattern = patterns[j]; var fileprop = file.type; if (typeof pattern === 'string' && pattern.substr(0, 1) === '.') { if (file.name.search('.') === -1) { /* no match with any file ending */ continue patternloop; } fileprop = file.name.substr(file.name.lastIndexOf('.')); } if (fileprop.search(pattern) === 0) { /* we found one match and can quit looking */ file_valid = true; break patternloop; } } if (!file_valid) { is_valid = false; break fileloop; } } } } return is_valid; } /** * boilerplate function for all tests but customError */ function check$1(test, react) { return function (element) { var invalid = !test(element); if (invalid) { react(element); } return invalid; }; } /** * create a common function to set error messages */ function set_msg(element, msgtype, _default) { message_store.set(element, custom_messages.get(element, msgtype, _default)); } var badInput = check$1(test_bad_input, function (element) { return set_msg(element, 'badInput', _('Please match the requested type.')); }); function customError(element) { /* check, if there are custom validators in the registry, and call * them. */ var custom_validators = custom_validator_registry.get(element); var cvl = custom_validators.length; var valid = true; if (cvl) { for (var i = 0; i < cvl; i++) { var result = custom_validators[i](element); if (result !== undefined && !result) { valid = false; /* break on first invalid response */ break; } } } /* check, if there are other validity messages already */ if (valid) { var msg = message_store.get(element); valid = !(msg.toString() && 'is_custom' in msg); } return !valid; } var patternMismatch = check$1(test_pattern, function (element) { set_msg(element, 'patternMismatch', element.title ? sprintf(_('PatternMismatchWithTitle'), element.title) : _('PatternMismatch')); }); /** * TODO: when rangeOverflow and rangeUnderflow are both called directly and * successful, the inRange and outOfRange classes won't get removed, unless * element.validityState.valid is queried, too. */ var rangeOverflow = check$1(test_max, function (element) { var type = get_type(element); var wrapper = get_wrapper(element); var outOfRangeClass = wrapper && wrapper.settings.classes.outOfRange || 'hf-out-of-range'; var inRangeClass = wrapper && wrapper.settings.classes.inRange || 'hf-in-range'; var msg = void 0; switch (type) { case 'date': case 'datetime': case 'datetime-local': msg = sprintf(_('DateRangeOverflow'), format_date(string_to_date(element.getAttribute('max'), type), type)); break; case 'time': msg = sprintf(_('TimeRangeOverflow'), format_date(string_to_date(element.getAttribute('max'), type), type)); break; // case 'number': default: msg = sprintf(_('NumberRangeOverflow'), string_to_number(element.getAttribute('max'), type)); break; } set_msg(element, 'rangeOverflow', msg); element.classList.add(outOfRangeClass); element.classList.remove(inRangeClass); }); var rangeUnderflow = check$1(test_min, function (element) { var type = get_type(element); var wrapper = get_wrapper(element); var outOfRangeClass = wrapper && wrapper.settings.classes.outOfRange || 'hf-out-of-range'; var inRangeClass = wrapper && wrapper.settings.classes.inRange || 'hf-in-range'; var msg = void 0; switch (type) { case 'date': case 'datetime': case 'datetime-local': msg = sprintf(_('DateRangeUnderflow'), format_date(string_to_date(element.getAttribute('min'), type), type)); break; case 'time': msg = sprintf(_('TimeRangeUnderflow'), format_date(string_to_date(element.getAttribute('min'), type), type)); break; // case 'number': default: msg = sprintf(_('NumberRangeUnderflow'), string_to_number(element.getAttribute('min'), type)); break; } set_msg(element, 'rangeUnderflow', msg); element.classList.add(outOfRangeClass); element.classList.remove(inRangeClass); }); var stepMismatch = check$1(test_step, function (element) { var list = get_next_valid(element); var min = list[0]; var max = list[1]; var sole = false; var msg = void 0; if (min === null) { sole = max; } else if (max === null) { sole = min; } if (sole !== false) { msg = sprintf(_('StepMismatchOneValue'), sole); } else { msg = sprintf(_('StepMismatch'), min, max); } set_msg(element, 'stepMismatch', msg); }); var tooLong = check$1(test_maxlength, function (element) { set_msg(element, 'tooLong', sprintf(_('TextTooLong'), element.getAttribute('maxlength'), unicode_string_length(element.value))); }); var tooShort = check$1(test_minlength, function (element) { set_msg(element, 'tooShort', sprintf(_('Please lengthen this text to %l characters or more (you are currently using %l characters).'), element.getAttribute('maxlength'), unicode_string_length(element.value))); }); var typeMismatch = check$1(test_type, function (element) { var msg = _('Please use the appropriate format.'); var type = get_type(element); if (type === 'email') { if (element.hasAttribute('multiple')) { msg = _('Please enter a comma separated list of email addresses.'); } else { msg = _('InvalidEmail'); } } else if (type === 'url') { msg = _('InvalidURL'); } else if (type === 'file') { msg = _('Please select a file of the correct type.'); } set_msg(element, 'typeMismatch', msg); }); var valueMissing = check$1(test_required, function (element) { var msg = _('ValueMissing'); var type = get_type(element); if (type === 'checkbox') { msg = _('CheckboxMissing'); } else if (type === 'radio') { msg = _('RadioMissing'); } else if (type === 'file') { if (element.hasAttribute('multiple')) { msg = _('Please select one or more files.'); } else { msg = _('FileMissing'); } } else if (element instanceof window.HTMLSelectElement) { msg = _('SelectMissing'); } set_msg(element, 'valueMissing', msg); }); var validity_state_checkers = { badInput: badInput, customError: customError, patternMismatch: patternMismatch, rangeOverflow: rangeOverflow, rangeUnderflow: rangeUnderflow, stepMismatch: stepMismatch, tooLong: tooLong, tooShort: tooShort, typeMismatch: typeMismatch, valueMissing: valueMissing }; /** * the validity state constructor */ var ValidityState = function ValidityState(element) { if (!(element instanceof window.HTMLElement)) { throw new Error('cannot create a ValidityState for a non-element'); } var cached = ValidityState.cache.get(element); if (cached) { return cached; } if (!(this instanceof ValidityState)) { /* working around a forgotten `new` */ return new ValidityState(element); } this.element = element; ValidityState.cache.set(element, this); }; /** * the prototype for new validityState instances */ var ValidityStatePrototype = {}; ValidityState.prototype = ValidityStatePrototype; ValidityState.cache = new WeakMap(); /** * copy functionality from the validity checkers to the ValidityState * prototype */ for (var prop in validity_state_checkers) { Object.defineProperty(ValidityStatePrototype, prop, { configurable: true, enumerable: true, get: function (func) { return function () { return func(this.element); }; }(validity_state_checkers[prop]), set: undefined }); } /** * the "valid" property calls all other validity checkers and returns true, * if all those return false. * * This is the major access point for _all_ other API methods, namely * (check|report)Validity(). */ Object.defineProperty(ValidityStatePrototype, 'valid', { configurable: true, enumerable: true, get: function get() { var wrapper = get_wrapper(this.element); var validClass = wrapper && wrapper.settings.classes.valid || 'hf-valid'; var invalidClass = wrapper && wrapper.settings.classes.invalid || 'hf-invalid'; var userInvalidClass = wrapper && wrapper.settings.classes.userInvalid || 'hf-user-invalid'; var userValidClass = wrapper && wrapper.settings.classes.userValid || 'hf-user-valid'; var inRangeClass = wrapper && wrapper.settings.classes.inRange || 'hf-in-range'; var outOfRangeClass = wrapper && wrapper.settings.classes.outOfRange || 'hf-out-of-range'; var validatedClass = wrapper && wrapper.settings.classes.validated || 'hf-validated'; this.element.classList.add(validatedClass); if (is_validation_candidate(this.element)) { for (var _prop in validity_state_checkers) { if (validity_state_checkers[_prop](this.element)) { this.element.classList.add(invalidClass); this.element.classList.remove(validClass); this.element.classList.remove(userValidClass); if (this.element.value !== this.element.defaultValue) { this.element.classList.add(userInvalidClass); } else { this.element.classList.remove(userInvalidClass); } this.element.setAttribute('aria-invalid', 'true'); return false; } } } message_store.delete(this.element); this.element.classList.remove(invalidClass, userInvalidClass, outOfRangeClass); this.element.classList.add(validClass, inRangeClass); if (this.element.value !== this.element.defaultValue) { this.element.classList.add(userValidClass); } else { this.element.classList.remove(userValidClass); } this.element.setAttribute('aria-invalid', 'false'); return true; }, set: undefined }); /** * mark the validity prototype, because that is what the client-facing * code deals with mostly, not the property descriptor thing */ mark(ValidityStatePrototype); /** * check an element's validity with respect to it's form */ var checkValidity = return_hook_or('checkValidity', function (element) { /* if this is a <form>, check validity of all child inputs */ if (element instanceof window.HTMLFormElement) { return Array.prototype.map.call(element.elements, checkValidity).every(function (b) { return b; }); } /* default is true, also for elements that are no validation candidates */ var valid = ValidityState(element).valid; if (valid) { var wrapped_form = get_wrapper(element); if (wrapped_form && wrapped_form.settings.valid_event) { trigger_event(element, 'valid'); } } else { trigger_event(element, 'invalid', { cancelable: true }); } return valid; }); var active = false; /** * this small CSS snippet fixes a problem in Chrome, where a click on * a button's child node has this child as event.target. This confuses * our "is this a submitting click" check. * * Why not just check the parent node? Because we check _every_ click, * and _every_ keypress possibly on on the whole page, to determine, if * this one might be a form submitting event. And checking all parent nodes * on every user interaction seems a bit... excessive. */ function fixButtonEvents () { if (!active) { var style = document.createElement("style"); style.className = 'hf-styles'; /* WebKit :(. See https://davidwalsh.name/add-rules-stylesheets */ style.appendChild(document.createTextNode("")); document.head.appendChild(style); style.sheet.insertRule('button:not([type]) *,button[type="submit"] *,button[type="image"] *{pointer-events:none}', 0); active = true; } } var version = '0.8.14'; /** * public hyperform interface: */ function hyperform(form) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _ref$debug = _ref.debug; var debug = _ref$debug === undefined ? false : _ref$debug; var _ref$strict = _ref.strict; var strict = _ref$strict === undefined ? false : _ref$strict; var _ref$prevent_implicit = _ref.prevent_implicit_submit; var prevent_implicit_submit = _ref$prevent_implicit === undefined ? false : _ref$prevent_implicit; var revalidate = _ref.revalidate; var valid_event = _ref.valid_event; var extend_fieldset = _ref.extend_fieldset; var novalidate_on_elements = _ref.novalidate_on_elements; var classes = _ref.classes; /* run this only, when we really create a Hyperform instance */ fixButtonEvents(); if (revalidate === undefined) { /* other recognized values: 'oninput', 'onblur', 'onsubmit' and 'never' */ revalidate = strict ? 'onsubmit' : 'hybrid'; } if (valid_event === undefined) { valid_event = !strict; } if (extend_fieldset === undefined) { extend_fieldset = !strict; } if (novalidate_on_elements === undefined) { novalidate_on_elements = !strict; } if (!classes) { classes = {}; } var settings = { debug: debug, strict: strict, prevent_implicit_submit: prevent_implicit_submit, revalidate: revalidate, valid_event: valid_event, extend_fieldset: extend_fieldset, classes: classes }; if (form instanceof window.NodeList || form instanceof window.HTMLCollection || form instanceof Array) { return Array.prototype.map.call(form, function (element) { return hyperform(element, settings); }); } return new Wrapper(form, settings); } hyperform.version = version; hyperform.checkValidity = checkValidity; hyperform.reportValidity = reportValidity; hyperform.setCustomValidity = setCustomValidity; hyperform.stepDown = stepDown; hyperform.stepUp = stepUp; hyperform.validationMessage = validationMessage; hyperform.ValidityState = ValidityState; hyperform.valueAsDate = valueAsDate; hyperform.valueAsNumber = valueAsNumber; hyperform.willValidate = willValidate; hyperform.set_language = function (lang) { set_language(lang);return hyperform; }; hyperform.add_translation = function (lang, catalog) { add_translation(lang, catalog);return hyperform; }; hyperform.set_renderer = function (renderer, action) { Renderer.set(renderer, action);return hyperform; }; hyperform.add_validator = function (element, validator) { custom_validator_registry.set(element, validator);return hyperform; }; hyperform.set_message = function (element, validator, message) { custom_messages.set(element, validator, message);return hyperform; }; hyperform.add_hook = function (hook, action, position) { add_hook(hook, action, position);return hyperform; }; hyperform.remove_hook = function (hook, action) { remove_hook(hook, action);return hyperform; }; return hyperform; }());
/*! * json-schema-faker library v0.3.4 * http://json-schema-faker.js.org * @preserve * * Copyright (c) 2014-2016 Alvaro Cabrera & Tomasz Ducin * Released under the MIT license * * Date: 2016-07-06 12:54:51.655Z */ (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":155}],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; /** * 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 = Math.random() * (max - min) + min; 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; } 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, 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'); 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'); 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; }; 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; } if (Array.isArray(value.items)) { return Array.prototype.concat.apply(items, value.items.map(function (item, key) { return traverseCallback(item, path.concat(['items', key]), 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++) { items.push(traverseCallback(value.items || sample, path.concat(['items', current]), resolve)); } 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]; } return genFunction.apply(contextObject, args); }; 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":146,"./name":147,"./phone_number":148,"./random":149,"./system":150}],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":153,"../vendor/user-agent":154}],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"] = [ "Canada" ]; },{}],136:[function(require,module,exports){ var address = {}; module['exports'] = address; address.state = require("./state"); address.state_abbr = require("./state_abbr"); address.default_country = require("./default_country"); address.postcode = require('./postcode.js'); },{"./default_country":135,"./postcode.js":137,"./state":138,"./state_abbr":139}],137:[function(require,module,exports){ module["exports"] = [ "?#? #?#" ]; },{}],138:[function(require,module,exports){ module["exports"] = [ "Alberta", "British Columbia", "Manitoba", "New Brunswick", "Newfoundland and Labrador", "Nova Scotia", "Northwest Territories", "Nunavut", "Ontario", "Prince Edward Island", "Quebec", "Saskatchewan", "Yukon" ]; },{}],139:[function(require,module,exports){ module["exports"] = [ "AB", "BC", "MB", "NB", "NL", "NS", "NU", "NT", "ON", "PE", "QC", "SK", "YT" ]; },{}],140:[function(require,module,exports){ var en_CA = {}; module['exports'] = en_CA; en_CA.title = "Canada (English)"; en_CA.address = require("./address"); en_CA.internet = require("./internet"); en_CA.phone_number = require("./phone_number"); },{"./address":136,"./internet":143,"./phone_number":145}],141:[function(require,module,exports){ module["exports"] = [ "ca", "com", "biz", "info", "name", "net", "org" ]; },{}],142:[function(require,module,exports){ module["exports"] = [ "gmail.com", "yahoo.ca", "hotmail.com" ]; },{}],143:[function(require,module,exports){ var internet = {}; module['exports'] = internet; internet.free_email = require("./free_email"); internet.domain_suffix = require("./domain_suffix"); },{"./domain_suffix":141,"./free_email":142}],144:[function(require,module,exports){ module["exports"] = [ "###-###-####", "(###)###-####", "###.###.####", "1-###-###-####", "###-###-#### x###", "(###)###-#### x###", "1-###-###-#### x###", "###.###.#### x###", "###-###-#### x####", "(###)###-#### x####", "1-###-###-#### x####", "###.###.#### x####", "###-###-#### x#####", "(###)###-#### x#####", "1-###-###-#### x#####", "###.###.#### x#####" ]; },{}],145:[function(require,module,exports){ arguments[4][129][0].apply(exports,arguments) },{"./formats":144,"dup":129}],146:[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; },{}],147:[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; },{}],148:[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; },{}],149:[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":152}],150:[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; },{}],151:[function(require,module,exports){ var Faker = require('../lib'); var faker = new Faker({ locale: 'en_CA', localeFallback: 'en' }); faker.locales['en_CA'] = require('../lib/locales/en_CA'); faker.locales['en'] = require('../lib/locales/en'); module['exports'] = faker; },{"../lib":45,"../lib/locales/en":112,"../lib/locales/en_CA":140}],152:[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); } },{}],153:[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)); },{}],154:[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]); }; },{}],155:[function(require,module,exports){ var ret = require('ret'); var DRange = require('discontinuous-range'); var types = ret.types; /** * If code is alphabetic, converts to other case. * If not alphabetic, returns back code. * * @param {Number} code * @return {Number} */ function toOtherCase(code) { return code + (97 <= code && code <= 122 ? -32 : 65 <= code && code <= 90 ? 32 : 0); } /** * Randomly returns a true or false value. * * @return {Boolean} */ function randBool() { return !this.randInt(0, 1); } /** * Randomly selects and returns a value from the array. * * @param {Array.<Object>} arr * @return {Object} */ function randSelect(arr) { if (arr instanceof DRange) { return arr.index(this.randInt(0, arr.length - 1)); } return arr[this.randInt(0, arr.length - 1)]; } /** * expands a token to a DiscontinuousRange of characters which has a * length and an index function (for random selecting) * * @param {Object} token * @return {DiscontinuousRange} */ function expand(token) { if (token.type === ret.types.CHAR) return new DRange(token.value); if (token.type === ret.types.RANGE) return new DRange(token.from, token.to); if (token.type === ret.types.SET) { var drange = new DRange(); for (var i = 0; i < token.set.length; i++) { var subrange = expand.call(this, token.set[i]); drange.add(subrange); if (this.ignoreCase) { for (var j = 0; j < subrange.length; j++) { var code = subrange.index(j); var otherCaseCode = toOtherCase(code); if (code !== otherCaseCode) { drange.add(otherCaseCode); } } } } if (token.not) { return this.defaultRange.clone().subtract(drange); } else { return drange; } } throw new Error('unexpandable token type: ' + token.type); } /** * @constructor * @param {RegExp|String} regexp * @param {String} m */ var RandExp = module.exports = function(regexp, m) { this.defaultRange = this.defaultRange.clone(); if (regexp instanceof RegExp) { this.ignoreCase = regexp.ignoreCase; this.multiline = regexp.multiline; if (typeof regexp.max === 'number') { this.max = regexp.max; } regexp = regexp.source; } else if (typeof regexp === 'string') { this.ignoreCase = m && m.indexOf('i') !== -1; this.multiline = m && m.indexOf('m') !== -1; } else { throw new Error('Expected a regexp or string'); } this.tokens = ret(regexp); }; // When a repetitional token has its max set to Infinite, // randexp won't actually generate a random amount between min and Infinite // instead it will see Infinite as min + 100. RandExp.prototype.max = 100; // Generates the random string. RandExp.prototype.gen = function() { return gen.call(this, this.tokens, []); }; // Enables use of randexp with a shorter call. RandExp.randexp = function(regexp, m) { var randexp; if (regexp._randexp === undefined) { randexp = new RandExp(regexp, m); regexp._randexp = randexp; } else { randexp = regexp._randexp; if (typeof regexp.max === 'number') { randexp.max = regexp.max; } if (regexp.defaultRange instanceof DRange) { randexp.defaultRange = regexp.defaultRange; } if (typeof regexp.randInt === 'function') { randexp.randInt = regexp.randInt; } } return randexp.gen(); }; // This enables sugary /regexp/.gen syntax. RandExp.sugar = function() { /* jshint freeze:false */ RegExp.prototype.gen = function() { return RandExp.randexp(this); }; }; // This allows expanding to include additional characters // for instance: RandExp.defaultRange.add(0, 65535); RandExp.prototype.defaultRange = new DRange(32, 126); /** * Randomly generates and returns a number between a and b (inclusive). * * @param {Number} a * @param {Number} b * @return {Number} */ RandExp.prototype.randInt = function(a, b) { return a + Math.floor(Math.random() * (1 + b - a)); }; /** * Generate random string modeled after given tokens. * * @param {Object} token * @param {Array.<String>} groups * @return {String} */ function gen(token, groups) { var stack, str, n, i, l; switch (token.type) { case types.ROOT: case types.GROUP: if (token.notFollowedBy) { return ''; } // Insert placeholder until group string is generated. if (token.remember && token.groupNumber === undefined) { token.groupNumber = groups.push(null) - 1; } stack = token.options ? randSelect.call(this, token.options) : token.stack; str = ''; for (i = 0, l = stack.length; i < l; i++) { str += gen.call(this, stack[i], groups); } if (token.remember) { groups[token.groupNumber] = str; } return str; case types.POSITION: // Do nothing for now. return ''; case types.SET: var expanded_set = expand.call(this, token); if (!expanded_set.length) return ''; return String.fromCharCode(randSelect.call(this, expanded_set)); case types.REPETITION: // Randomly generate number between min and max. n = this.randInt(token.min, token.max === Infinity ? token.min + this.max : token.max); str = ''; for (i = 0; i < n; i++) { str += gen.call(this, token.value, groups); } return str; case types.REFERENCE: return groups[token.value - 1] || ''; case types.CHAR: var code = this.ignoreCase && randBool.call(this) ? toOtherCase(token.value) : token.value; return String.fromCharCode(code); } } },{"discontinuous-range":156,"ret":157}],156:[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; },{}],157:[function(require,module,exports){ var util = require('./util'); var types = require('./types'); var sets = require('./sets'); var positions = require('./positions'); module.exports = function(regexpStr) { var i = 0, l, c, start = { type: types.ROOT, stack: []}, // Keep track of last clause/group and stack. lastGroup = start, last = start.stack, groupStack = []; var repeatErr = function(i) { util.error(regexpStr, 'Nothing to repeat at column ' + (i - 1)); }; // Decode a few escaped characters. var str = util.strToChars(regexpStr); l = str.length; // Iterate through each character in string. while (i < l) { c = str[i++]; switch (c) { // Handle escaped characters, inclues a few sets. case '\\': c = str[i++]; switch (c) { case 'b': last.push(positions.wordBoundary()); break; case 'B': last.push(positions.nonWordBoundary()); break; case 'w': last.push(sets.words()); break; case 'W': last.push(sets.notWords()); break; case 'd': last.push(sets.ints()); break; case 'D': last.push(sets.notInts()); break; case 's': last.push(sets.whitespace()); break; case 'S': last.push(sets.notWhitespace()); break; default: // Check if c is integer. // In which case it's a reference. if (/\d/.test(c)) { last.push({ type: types.REFERENCE, value: parseInt(c, 10) }); // Escaped character. } else { last.push({ type: types.CHAR, value: c.charCodeAt(0) }); } } break; // Positionals. case '^': last.push(positions.begin()); break; case '$': last.push(positions.end()); break; // Handle custom sets. case '[': // Check if this class is 'anti' i.e. [^abc]. var not; if (str[i] === '^') { not = true; i++; } else { not = false; } // Get all the characters in class. var classTokens = util.tokenizeClass(str.slice(i), regexpStr); // Increase index by length of class. i += classTokens[1]; last.push({ type: types.SET , set: classTokens[0] , not: not }); break; // Class of any character except \n. case '.': last.push(sets.anyChar()); break; // Push group onto stack. case '(': // Create group. var group = { type: types.GROUP , stack: [] , remember: true }; c = str[i]; // if if this is a special kind of group. if (c === '?') { c = str[i + 1]; i += 2; // Match if followed by. if (c === '=') { group.followedBy = true; // Match if not followed by. } else if (c === '!') { group.notFollowedBy = true; } else if (c !== ':') { util.error(regexpStr, 'Invalid group, character \'' + c + '\' after \'?\' at column ' + (i - 1)); } group.remember = false; } // Insert subgroup into current group stack. last.push(group); // Remember the current group for when the group closes. groupStack.push(lastGroup); // Make this new group the current group. lastGroup = group; last = group.stack; break; // Pop group out of stack. case ')': if (groupStack.length === 0) { util.error(regexpStr, 'Unmatched ) at column ' + (i - 1)); } lastGroup = groupStack.pop(); // Check if this group has a PIPE. // To get back the correct last stack. last = lastGroup.options ? lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack; break; // Use pipe character to give more choices. case '|': // Create array where options are if this is the first PIPE // in this clause. if (!lastGroup.options) { lastGroup.options = [lastGroup.stack]; delete lastGroup.stack; } // Create a new stack and add to options for rest of clause. var stack = []; lastGroup.options.push(stack); last = stack; break; // Repetition. // For every repetition, remove last element from last stack // then insert back a RANGE object. // This design is chosen because there could be more than // one repetition symbols in a regex i.e. `a?+{2,3}`. case '{': var rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max; if (rs !== null) { min = parseInt(rs[1], 10); max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min; i += rs[0].length; last.push({ type: types.REPETITION , min: min , max: max , value: last.pop() }); } else { last.push({ type: types.CHAR , value: 123 }); } break; case '?': if (last.length === 0) { repeatErr(i); } last.push({ type: types.REPETITION , min: 0 , max: 1 , value: last.pop() }); break; case '+': if (last.length === 0) { repeatErr(i); } last.push({ type: types.REPETITION , min: 1 , max: Infinity , value: last.pop() }); break; case '*': if (last.length === 0) { repeatErr(i); } last.push({ type: types.REPETITION , min: 0 , max: Infinity , value: last.pop() }); break; // Default is a character that is not `\[](){}?+*^$`. default: last.push({ type: types.CHAR , value: c.charCodeAt(0) }); } } // Check if any groups have not been closed. if (groupStack.length !== 0) { util.error(regexpStr, 'Unterminated group'); } return start; }; module.exports.types = types; },{"./positions":158,"./sets":159,"./types":160,"./util":161}],158:[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":160}],159:[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":160}],160:[function(require,module,exports){ module.exports = { ROOT : 0 , GROUP : 1 , POSITION : 2 , SET : 3 , RANGE : 4 , REPETITION : 5 , REFERENCE : 6 , CHAR : 7 }; },{}],161:[function(require,module,exports){ var types = require('./types'); var sets = require('./sets'); // All of these are private and only used by randexp. // It's assumed that they will always be called with the correct input. var CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?'; var SLSH = { '0': 0, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13 }; /** * Finds character representations in str and convert all to * their respective characters * * @param {String} str * @return {String} */ exports.strToChars = function(str) { var chars_regex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z\[\\\]\^?])|([0tnvfr]))/g; str = str.replace(chars_regex, function(s, b, lbs, a16, b16, c8, dctrl, eslsh) { if (lbs) { return s; } var code = b ? 8 : a16 ? parseInt(a16, 16) : b16 ? parseInt(b16, 16) : c8 ? parseInt(c8, 8) : dctrl ? CTRL.indexOf(dctrl) : eslsh ? SLSH[eslsh] : undefined; var c = String.fromCharCode(code); // Escape special regex characters. if (/[\[\]{}\^$.|?*+()]/.test(c)) { c = '\\' + c; } return c; }); return str; }; /** * turns class into tokens * reads str until it encounters a ] not preceeded by a \ * * @param {String} str * @param {String} regexpStr * @return {Array.<Array.<Object>, Number>} */ exports.tokenizeClass = function(str, regexpStr) { var tokens = [] , regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g , rs, c ; while ((rs = regexp.exec(str)) != null) { if (rs[1]) { tokens.push(sets.words()); } else if (rs[2]) { tokens.push(sets.ints()); } else if (rs[3]) { tokens.push(sets.whitespace()); } else if (rs[4]) { tokens.push(sets.notWords()); } else if (rs[5]) { tokens.push(sets.notInts()); } else if (rs[6]) { tokens.push(sets.notWhitespace()); } else if (rs[7]) { tokens.push({ type: types.RANGE , from: (rs[8] || rs[9]).charCodeAt(0) , to: rs[10].charCodeAt(0) }); } else if (c = rs[12]) { tokens.push({ type: types.CHAR , value: c.charCodeAt(0) }); } else { return [tokens, regexp.lastIndex]; } } exports.error(regexpStr, 'Unterminated character class'); }; /** * Shortcut to throw errors. * * @param {String} regexp * @param {String} msg */ exports.error = function(regexp, msg) { throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg); }; },{"./sets":159,"./types":160}],"json-schema-faker":[function(require,module,exports){ module.exports = require('../lib/') .extend('faker', function() { try { return require('faker/locale/en_CA'); } catch (e) { return null; } }); },{"../lib/":19,"faker/locale/en_CA":151}]},{},["json-schema-faker"])("json-schema-faker") });
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v4.1.1 * @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 utils_1 = require('../utils'); var svgFactory_1 = require("../svgFactory"); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var context_1 = require("../context/context"); var context_2 = require("../context/context"); var svgFactory = svgFactory_1.SvgFactory.getInstance(); var HeaderTemplateLoader = (function () { function HeaderTemplateLoader() { } HeaderTemplateLoader.prototype.createHeaderElement = function (column) { var params = { column: column, colDef: column.getColDef, context: this.gridOptionsWrapper.getContext(), api: this.gridOptionsWrapper.getApi() }; // option 1 - see if user provided a template in colDef var userProvidedTemplate = column.getColDef().headerCellTemplate; if (typeof userProvidedTemplate === 'function') { var colDefFunc = userProvidedTemplate; userProvidedTemplate = colDefFunc(params); } // option 2 - check the gridOptions for cellTemplate if (!userProvidedTemplate && this.gridOptionsWrapper.getHeaderCellTemplate()) { userProvidedTemplate = this.gridOptionsWrapper.getHeaderCellTemplate(); } // option 3 - check the gridOptions for templateFunction if (!userProvidedTemplate && this.gridOptionsWrapper.getHeaderCellTemplateFunc()) { var gridOptionsFunc = this.gridOptionsWrapper.getHeaderCellTemplateFunc(); userProvidedTemplate = gridOptionsFunc(params); } // finally, if still no template, use the default if (!userProvidedTemplate) { userProvidedTemplate = this.createDefaultHeaderElement(column); } // template can be a string or a dom element, if string we need to convert to a dom element var result; if (typeof userProvidedTemplate === 'string') { result = utils_1.Utils.loadTemplate(userProvidedTemplate); } else if (utils_1.Utils.isNodeOrElement(userProvidedTemplate)) { result = userProvidedTemplate; } else { console.error('ag-Grid: header template must be a string or an HTML element'); } return result; }; HeaderTemplateLoader.prototype.createDefaultHeaderElement = function (column) { var eTemplate = utils_1.Utils.loadTemplate(HeaderTemplateLoader.HEADER_CELL_TEMPLATE); this.addInIcon(eTemplate, 'sortAscending', '#agSortAsc', column, svgFactory.createArrowUpSvg); this.addInIcon(eTemplate, 'sortDescending', '#agSortDesc', column, svgFactory.createArrowDownSvg); this.addInIcon(eTemplate, 'sortUnSort', '#agNoSort', column, svgFactory.createArrowUpDownSvg); this.addInIcon(eTemplate, 'menu', '#agMenu', column, svgFactory.createMenuSvg); this.addInIcon(eTemplate, 'filter', '#agFilter', column, svgFactory.createFilterSvg); return eTemplate; }; HeaderTemplateLoader.prototype.addInIcon = function (eTemplate, iconName, cssSelector, column, defaultIconFactory) { var eIcon = utils_1.Utils.createIconNoSpan(iconName, this.gridOptionsWrapper, column, defaultIconFactory); eTemplate.querySelector(cssSelector).appendChild(eIcon); }; // used when cell is dragged HeaderTemplateLoader.HEADER_CELL_DND_TEMPLATE = '<div class="ag-header-cell ag-header-cell-ghost">' + ' <span id="eGhostIcon" class="ag-header-cell-ghost-icon ag-shake-left-to-right"></span>' + ' <div id="agHeaderCellLabel" class="ag-header-cell-label">' + ' <span id="agText" class="ag-header-cell-text"></span>' + ' </div>' + '</div>'; HeaderTemplateLoader.HEADER_CELL_TEMPLATE = '<div class="ag-header-cell">' + ' <div id="agResizeBar" class="ag-header-cell-resize"></div>' + ' <span id="agMenu" class="ag-header-icon ag-header-cell-menu-button"></span>' + ' <div id="agHeaderCellLabel" class="ag-header-cell-label">' + ' <span id="agSortAsc" class="ag-header-icon ag-sort-ascending-icon"></span>' + ' <span id="agSortDesc" class="ag-header-icon ag-sort-descending-icon"></span>' + ' <span id="agNoSort" class="ag-header-icon ag-sort-none-icon"></span>' + ' <span id="agFilter" class="ag-header-icon ag-filter-icon"></span>' + ' <span id="agText" class="ag-header-cell-text"></span>' + ' </div>' + '</div>'; __decorate([ context_2.Autowired('gridOptionsWrapper'), __metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper) ], HeaderTemplateLoader.prototype, "gridOptionsWrapper", void 0); HeaderTemplateLoader = __decorate([ context_1.Bean('headerTemplateLoader'), __metadata('design:paramtypes', []) ], HeaderTemplateLoader); return HeaderTemplateLoader; })(); exports.HeaderTemplateLoader = HeaderTemplateLoader;
/* Usage: <wysiwyg textarea-id="question" textarea-class="form-control" textarea-height="80px" textarea-name="textareaQuestion" textarea-required ng-model="question.question" enable-bootstrap-title="true"></wysiwyg> options textarea-id The id to assign to the editable div textarea-class The class(es) to assign to the the editable div textarea-height If not specified in a text-area class then the hight of the editable div (default: 80px) textarea-name The name attribute of the editable div textarea-required HTML/AngularJS required validation textarea-menu Array of Arrays that contain the groups of buttons to show Defualt:Show all button groups ng-model The angular data model enable-bootstrap-title True/False whether or not to show the button hover title styled with bootstrap Requires: Twitter-bootstrap, fontawesome, jquery, angularjs, bootstrap-color-picker (https://github.com/buberdds/angular-bootstrap-colorpicker) */ /* TODO: tab support custom button fuctions limit use of scope use compile fuction instead of $compile move button elements to js objects and use doc fragments */ (function (angular, undefined) { 'use strict'; var DEFAULT_MENU = [ [ 'bold', 'italic', 'underline', 'strikethrough', 'subscript', 'superscript' ], ['format-block'], ['font'], ['font-size'], [ 'font-color', 'hilite-color' ], ['remove-format'], [ 'ordered-list', 'unordered-list', 'outdent', 'indent' ], [ 'left-justify', 'center-justify', 'right-justify' ], [ 'code', 'quote', 'paragraph' ], [ 'link', 'image' ] ]; angular.module('wysiwyg.module', ['colorpicker.module']).directive('wysiwyg', [ '$timeout', 'wysiwgGui', '$compile', function ($timeout, wysiwgGui, $compile) { return { template: '<div>' + '<style>' + ' .wysiwyg-textarea[contentEditable="false"] { background-color:#eee}' + ' .wysiwyg-btn-group-margin { margin-right:5px; }' + ' .wysiwyg-select { height:30px;margin-bottom:1px;}' + ' .wysiwyg-colorpicker { font-family: arial, sans-serif !important;font-size:16px !important; padding:2px 10px !important;}' + '</style>' + '<div class="wysiwyg-menu"></div>' + '<div id="{{textareaId}}" ng-attr-style="resize:vertical;height:{{textareaHeight || \'80px\'}}; overflow:auto" contentEditable="{{!disabled}}" class="{{textareaClass}} wysiwyg-textarea" rows="{{textareaRows}}" name="{{textareaName}}" required="{{textareaRequired}}" placeholder="{{textareaPlaceholder}}" ng-model="value"></div>' + '</div>', restrict: 'E', scope: { value: '=ngModel', textareaHeight: '@textareaHeight', textareaName: '@textareaName', textareaPlaceholder: '@textareaPlaceholder', textareaClass: '@textareaClass', textareaRequired: '@textareaRequired', textareaId: '@textareaId', textareaMenu: '=textareaMenu', textareaCustomMenu: '=textareaCustomMenu', fn: '&', disabled: '=?disabled' }, replace: true, require: 'ngModel', link: link, transclude: true }; function link(scope, element, attrs, ngModelController) { var textarea = element.find('div.wysiwyg-textarea'); scope.isLink = false; scope.fontSizes = [ { value: '1', size: '10px' }, { value: '2', size: '13px' }, { value: '3', size: '16px' }, { value: '4', size: '18px' }, { value: '5', size: '24px' }, { value: '6', size: '32px' }, { value: '7', size: '48px' } ]; scope.formatBlocks = [ { name: 'Heading Blocks', value: 'div' }, { name: 'Heading 1', value: 'h1' }, { name: 'Heading 2', value: 'h2' }, { name: 'Heading 3', value: 'h3' }, { name: 'Heading 4', value: 'h4' }, { name: 'Heading 5', value: 'h5' }, { name: 'Heading 6', value: 'h6' } ]; scope.formatBlock = scope.formatBlocks[0]; scope.fontSize = scope.fontSizes[1]; scope.fonts = [ 'Georgia', 'Palatino Linotype', 'Times New Roman', 'Arial', 'Helvetica', 'Arial Black', 'Comic Sans MS', 'Impact', 'Lucida Sans Unicode', 'Tahoma', 'Trebuchet MS', 'Verdana', 'Courier New', 'Lucida Console', 'Helvetica Neue' ].sort(); scope.font = scope.fonts[6]; init(); function init() { compileMenu(); configureDisabledWatch(); configureBootstrapTitle(); configureListeners(); } function compileMenu() { wysiwgGui.setCustomElements(scope.textareaCustomMenu); var menuDiv = element.children('div.wysiwyg-menu')[0]; menuDiv.appendChild(wysiwgGui.createMenu(scope.textareaMenu)); $compile(menuDiv)(scope); } function configureDisabledWatch() { scope.$watch('disabled', function (newValue) { angular.element('div.wysiwyg-menu').find('button').each(function () { angular.element(this).attr('disabled', newValue); }); angular.element('div.wysiwyg-menu').find('select').each(function () { angular.element(this).attr('disabled', newValue); }); }); } function configureBootstrapTitle() { if (attrs.enableBootstrapTitle === 'true' && attrs.enableBootstrapTitle !== undefined) { element.find('button[title]').tooltip({ container: 'body' }); } } function configureListeners() { //Send message to calling controller that a button has been clicked. angular.element('.wysiwyg-menu').find('button').on('click', function () { var title = angular.element(this); scope.$emit('wysiwyg.click', title.attr('title') || title.attr('data-original-title')); }); textarea.on('input keyup paste mouseup', function (e) { var html = textarea.html(); if (html == '<br>') { html = ''; } ngModelController.$setViewValue(html); }); textarea.on('click keyup focus mouseup', function () { $timeout(function () { scope.isBold = scope.cmdState('bold'); scope.isUnderlined = scope.cmdState('underline'); scope.isStrikethrough = scope.cmdState('strikethrough'); scope.isItalic = scope.cmdState('italic'); scope.isSuperscript = itemIs('SUP'); //scope.cmdState('superscript'); scope.isSubscript = itemIs('SUB'); //scope.cmdState('subscript'); scope.isRightJustified = scope.cmdState('justifyright'); scope.isLeftJustified = scope.cmdState('justifyleft'); scope.isCenterJustified = scope.cmdState('justifycenter'); scope.isPre = scope.cmdValue('formatblock') == 'pre'; scope.isBlockquote = scope.cmdValue('formatblock') == 'blockquote'; scope.isOrderedList = scope.cmdState('insertorderedlist'); scope.isUnorderedList = scope.cmdState('insertunorderedlist'); scope.fonts.forEach(function (v, k) { //works but kinda crappy. if (scope.cmdValue('fontname').indexOf(v) > -1) { scope.font = v; return false; } }); scope.cmdValue('formatblock').toLowerCase(); scope.formatBlocks.forEach(function (v, k) { if (scope.cmdValue('formatblock').toLowerCase() === v.value.toLowerCase()) { scope.formatBlock = v; return false; } }); scope.fontSizes.forEach(function (v, k) { if (scope.cmdValue('fontsize') === v.value) { scope.fontSize = v; return false; } }); scope.hiliteColor = getHiliteColor(); element.find('button.wysiwyg-hiliteColor').css('background-color', scope.hiliteColor); scope.fontColor = scope.cmdValue('forecolor'); element.find('button.wysiwyg-fontcolor').css('color', scope.fontColor); scope.isLink = itemIs('A'); }, 0); }); } //Used to detect things like A tags and others that dont work with cmdValue(). function itemIs(tag) { var selection = window.getSelection().getRangeAt(0); if (selection) { if (selection.startContainer.parentNode.tagName === tag.toUpperCase() || selection.endContainer.parentNode.tagName === tag.toUpperCase()) { return true; } else { return false; } } else { return false; } } //Used to detect things like A tags and others that dont work with cmdValue(). function getHiliteColor() { var selection = window.getSelection().getRangeAt(0); if (selection) { var style = $(selection.startContainer.parentNode).attr('style'); if (!angular.isDefined(style)) return false; var a = style.split(';'); for (var i = 0; i < a.length; i++) { var s = a[i].split(':'); if (s[0] === 'background-color') return s[1]; } return '#fff'; } else { return '#fff'; } } // model -> view ngModelController.$render = function () { textarea.html(ngModelController.$viewValue); }; scope.format = function (cmd, arg) { document.execCommand(cmd, false, arg); }; scope.cmdState = function (cmd, id) { return document.queryCommandState(cmd); }; scope.cmdValue = function (cmd) { return document.queryCommandValue(cmd); }; scope.createLink = function () { var input = prompt('Enter the link URL'); if (input && input !== undefined) scope.format('createlink', input); }; scope.insertImage = function () { var input = prompt('Enter the image URL'); if (input && input !== undefined) scope.format('insertimage', input); }; scope.setFont = function () { scope.format('fontname', scope.font); }; scope.setFontSize = function () { scope.format('fontsize', scope.fontSize.value); }; scope.setFormatBlock = function () { scope.format('formatBlock', scope.formatBlock.value); }; scope.setFontColor = function () { scope.format('forecolor', scope.fontColor); }; scope.setHiliteColor = function () { scope.format('hiliteColor', scope.hiliteColor); }; scope.format('enableobjectresizing', true); scope.format('styleWithCSS', true); } ; } ]).factory('wysiwgGui', [ 'wysiwgGuiElements', function (wysiwgGuiElements) { var ELEMENTS = wysiwgGuiElements; var custom = {}; var setCustomElements = function (el) { custom = el; }; var getMenuGroup = function () { return { tag: 'div', classes: 'btn-group btn-group-sm wysiwyg-btn-group-margin' }; }; var getMenuItem = function (item) { return ELEMENTS[item] || {}; }; var createMenu = function (menu) { angular.extend(ELEMENTS, custom); //Get the default menu or the passed in menu if (angular.isDefined(menu) && menu !== '') menu = menu; else menu = DEFAULT_MENU; //create div to add everything to. var startDiv = document.createElement('div'); for (var i = 0; i < menu.length; i++) { var menuGroup = create(getMenuGroup()); for (var j = 0; j < menu[i].length; j++) { //link has two functions link and unlink if (menu[i][j] === 'link') { var el = create(getMenuItem('unlink')); menuGroup.appendChild(el); } var el = create(getMenuItem(menu[i][j])); menuGroup.appendChild(el); } startDiv.appendChild(menuGroup); } return startDiv; }; function create(obj) { var el; if (obj.tag) { el = document.createElement(obj.tag); } else if (obj.text) { el = document.createElement('span'); } else { console.log('cannot create this element.'); el = document.createElement('span'); return el; } if (obj.text) { el.innerText = obj.text; } if (obj.classes) { el.className = obj.classes; } if (obj.html) { el.innerHTML = obj.html; } if (obj.attributes && obj.attributes.length) { for (var i in obj.attributes) { var attr = obj.attributes[i]; if (attr.name && attr.value) { el.setAttribute(attr.name, attr.value); } } } if (obj.data && obj.data.length) { for (var item in obj.data) { el.appendChild(create(obj.data[item])); } } return el; } var stringToArray = function (string) { var ret; try { ret = JSON.parse(string.replace(/'/g, '"')); } catch (e) { } return ret; }; return { createMenu: createMenu, setCustomElements: setCustomElements }; } ]).value('wysiwgGuiElements', { 'bold': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Bold' }, { name: 'ng-click', value: 'format(\'bold\')' }, { name: 'ng-class', value: '{ active: isBold }' } ], data: [{ tag: 'i', classes: 'fa fa-bold' }] }, 'italic': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Italic' }, { name: 'ng-click', value: 'format(\'italic\')' }, { name: 'ng-class', value: '{ active: isItalic }' } ], data: [{ tag: 'i', classes: 'fa fa-italic' }] }, 'underline': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Underline' }, { name: 'ng-click', value: 'format(\'underline\')' }, { name: 'ng-class', value: '{ active: isUnderlined }' } ], data: [{ tag: 'i', classes: 'fa fa-underline' }] }, 'strikethrough': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Strikethrough' }, { name: 'ng-click', value: 'format(\'strikethrough\')' }, { name: 'ng-class', value: '{ active: isStrikethrough }' } ], data: [{ tag: 'i', classes: 'fa fa-strikethrough' }] }, 'subscript': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Subscript' }, { name: 'ng-click', value: 'format(\'subscript\')' }, { name: 'ng-class', value: '{ active: isSubscript }' } ], data: [{ tag: 'i', classes: 'fa fa-subscript' }] }, 'superscript': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Superscript' }, { name: 'ng-click', value: 'format(\'superscript\')' }, { name: 'ng-class', value: '{ active: isSuperscript }' } ], data: [{ tag: 'i', classes: 'fa fa-superscript' }] }, 'remove-format': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Remove Formatting' }, { name: 'ng-click', value: 'format(\'removeFormat\')' } ], data: [{ tag: 'i', classes: 'fa fa-eraser' }] }, 'ordered-list': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Ordered List' }, { name: 'ng-click', value: 'format(\'insertorderedlist\')' }, { name: 'ng-class', value: '{ active: isOrderedList }' } ], data: [{ tag: 'i', classes: 'fa fa-list-ol' }] }, 'unordered-list': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Unordered List' }, { name: 'ng-click', value: 'format(\'insertunorderedlist\')' }, { name: 'ng-class', value: '{ active: isUnorderedList }' } ], data: [{ tag: 'i', classes: 'fa fa-list-ul' }] }, 'outdent': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Outdent' }, { name: 'ng-click', value: 'format(\'outdent\')' } ], data: [{ tag: 'i', classes: 'fa fa-outdent' }] }, 'indent': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Indent' }, { name: 'ng-click', value: 'format(\'indent\')' } ], data: [{ tag: 'i', classes: 'fa fa-indent' }] }, 'left-justify': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Left Justify' }, { name: 'ng-click', value: 'format(\'justifyleft\')' }, { name: 'ng-class', value: '{ active: isLeftJustified }' } ], data: [{ tag: 'i', classes: 'fa fa-align-left' }] }, 'center-justify': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Center Justify' }, { name: 'ng-click', value: 'format(\'justifycenter\')' }, { name: 'ng-class', value: '{ active: isCenterJustified }' } ], data: [{ tag: 'i', classes: 'fa fa-align-center' }] }, 'right-justify': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Right Justify' }, { name: 'ng-click', value: 'format(\'justifyright\')' }, { name: 'ng-class', value: '{ active: isRightJustified }' } ], data: [{ tag: 'i', classes: 'fa fa-align-right' }] }, 'code': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Code' }, { name: 'ng-click', value: 'format(\'formatblock\', \'pre\')' }, { name: 'ng-class', value: '{ active: isPre }' } ], data: [{ tag: 'i', classes: 'fa fa-code' }] }, 'quote': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Quote' }, { name: 'ng-click', value: 'format(\'formatblock\', \'blockquote\')' }, { name: 'ng-class', value: '{ active: isBlockquote }' } ], data: [{ tag: 'i', classes: 'fa fa-quote-right' }] }, 'paragraph': { tag: 'button', classes: 'btn btn-default', text: 'P', attributes: [ { name: 'title', value: 'Paragragh' }, { name: 'ng-click', value: 'format(\'insertParagraph\')' }, { name: 'ng-class', value: '{ active: isParagraph }' } ] }, 'image': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Image' }, { name: 'ng-click', value: 'insertImage()' } ], data: [{ tag: 'i', classes: 'fa fa-picture-o' }] }, 'font-color': { tag: 'button', classes: 'btn btn-default wysiwyg-colorpicker wysiwyg-fontcolor', text: 'A', attributes: [ { name: 'title', value: 'Font Color' }, { name: 'colorpicker', value: 'rgba' }, { name: 'colorpicker-position', value: 'top' }, { name: 'ng-model', value: 'fontColor' }, { name: 'ng-change', value: 'setFontColor()' } ] }, 'hilite-color': { tag: 'button', classes: 'btn btn-default wysiwyg-colorpicker wysiwyg-fontcolor', text: 'H', attributes: [ { name: 'title', value: 'Hilite Color' }, { name: 'colorpicker', value: 'rgba' }, { name: 'colorpicker-position', value: 'top' }, { name: 'ng-model', value: 'hiliteColor' }, { name: 'ng-change', value: 'setHiliteColor()' } ] }, 'font': { tag: 'select', classes: 'form-control wysiwyg-select', attributes: [ { name: 'title', value: 'Image' }, { name: 'ng-model', value: 'font' }, { name: 'ng-options', value: 'f for f in fonts' }, { name: 'ng-change', value: 'setFont()' } ] }, 'font-size': { tag: 'select', classes: 'form-control wysiwyg-select', attributes: [ { name: 'title', value: 'Image' }, { name: 'ng-model', value: 'fontSize' }, { name: 'ng-options', value: 'f.size for f in fontSizes' }, { name: 'ng-change', value: 'setFontSize()' } ] }, 'format-block': { tag: 'select', classes: 'form-control wysiwyg-select', attributes: [ { name: 'title', value: 'Format Block' }, { name: 'ng-model', value: 'formatBlock' }, { name: 'ng-options', value: 'f.name for f in formatBlocks' }, { name: 'ng-change', value: 'setFormatBlock()' } ] }, 'link': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Link' }, { name: 'ng-click', value: 'createLink()' }, { name: 'ng-show', value: '!isLink' } ], data: [{ tag: 'i', classes: 'fa fa-link' }] }, 'unlink': { tag: 'button', classes: 'btn btn-default', attributes: [ { name: 'title', value: 'Unlink' }, { name: 'ng-click', value: 'format(\'unlink\')' }, { name: 'ng-show', value: 'isLink' } ], data: [{ tag: 'i', classes: 'fa fa-unlink' }] } }); }(angular));
define(['./isKind'], function (isKind) { /** */ function isBoolean(val) { return isKind(val, 'Boolean'); } return isBoolean; });
/** * @ngdoc object * @name ui.router.router.$urlRouterProvider * * @requires ui.router.util.$urlMatcherFactoryProvider * @requires $locationProvider * * @description * `$urlRouterProvider` has the responsibility of watching `$location`. * When `$location` changes it runs through a list of rules one by one until a * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify * a url in a state configuration. All urls are compiled into a UrlMatcher object. * * There are several methods on `$urlRouterProvider` that make it useful to use directly * in your module config. */ $UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider']; function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) { var rules = [], otherwise = null, interceptDeferred = false, listener; // Returns a string that is a prefix of all strings matching the RegExp function regExpPrefix(re) { var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source); return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : ''; } // Interpolates matched values into a String.replace()-style pattern function interpolate(pattern, match) { return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) { return match[what === '$' ? 0 : Number(what)]; }); } /** * @ngdoc function * @name ui.router.router.$urlRouterProvider#rule * @methodOf ui.router.router.$urlRouterProvider * * @description * Defines rules that are used by `$urlRouterProvider` to find matches for * specific URLs. * * @example * <pre> * var app = angular.module('app', ['ui.router.router']); * * app.config(function ($urlRouterProvider) { * // Here's an example of how you might allow case insensitive urls * $urlRouterProvider.rule(function ($injector, $location) { * var path = $location.path(), * normalized = path.toLowerCase(); * * if (path !== normalized) { * return normalized; * } * }); * }); * </pre> * * @param {function} rule Handler function that takes `$injector` and `$location` * services as arguments. You can use them to return a valid path as a string. * * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance */ this.rule = function (rule) { if (!isFunction(rule)) throw new Error("'rule' must be a function"); rules.push(rule); return this; }; /** * @ngdoc object * @name ui.router.router.$urlRouterProvider#otherwise * @methodOf ui.router.router.$urlRouterProvider * * @description * Defines a path that is used when an invalid route is requested. * * @example * <pre> * var app = angular.module('app', ['ui.router.router']); * * app.config(function ($urlRouterProvider) { * // if the path doesn't match any of the urls you configured * // otherwise will take care of routing the user to the * // specified url * $urlRouterProvider.otherwise('/index'); * * // Example of using function rule as param * $urlRouterProvider.otherwise(function ($injector, $location) { * return '/a/valid/url'; * }); * }); * </pre> * * @param {string|function} rule The url path you want to redirect to or a function * rule that returns the url path. The function version is passed two params: * `$injector` and `$location` services, and must return a url string. * * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance */ this.otherwise = function (rule) { if (isString(rule)) { var redirect = rule; rule = function () { return redirect; }; } else if (!isFunction(rule)) throw new Error("'rule' must be a function"); otherwise = rule; return this; }; function handleIfMatch($injector, handler, match) { if (!match) return false; var result = $injector.invoke(handler, handler, { $match: match }); return isDefined(result) ? result : true; } /** * @ngdoc function * @name ui.router.router.$urlRouterProvider#when * @methodOf ui.router.router.$urlRouterProvider * * @description * Registers a handler for a given url matching. * * If the handler is a string, it is * treated as a redirect, and is interpolated according to the syntax of match * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise). * * If the handler is a function, it is injectable. It gets invoked if `$location` * matches. You have the option of inject the match object as `$match`. * * The handler can return * * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter` * will continue trying to find another one that matches. * - **string** which is treated as a redirect and passed to `$location.url()` * - **void** or any **truthy** value tells `$urlRouter` that the url was handled. * * @example * <pre> * var app = angular.module('app', ['ui.router.router']); * * app.config(function ($urlRouterProvider) { * $urlRouterProvider.when($state.url, function ($match, $stateParams) { * if ($state.$current.navigable !== state || * !equalForKeys($match, $stateParams) { * $state.transitionTo(state, $match, false); * } * }); * }); * </pre> * * @param {string|object} what The incoming path that you want to redirect. * @param {string|function} handler The path you want to redirect your user to. */ this.when = function (what, handler) { var redirect, handlerIsString = isString(handler); if (isString(what)) what = $urlMatcherFactory.compile(what); if (!handlerIsString && !isFunction(handler) && !isArray(handler)) throw new Error("invalid 'handler' in when()"); var strategies = { matcher: function (what, handler) { if (handlerIsString) { redirect = $urlMatcherFactory.compile(handler); handler = ['$match', function ($match) { return redirect.format($match); }]; } return extend(function ($injector, $location) { return handleIfMatch($injector, handler, what.exec($location.path(), $location.search())); }, { prefix: isString(what.prefix) ? what.prefix : '' }); }, regex: function (what, handler) { if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky"); if (handlerIsString) { redirect = handler; handler = ['$match', function ($match) { return interpolate(redirect, $match); }]; } return extend(function ($injector, $location) { return handleIfMatch($injector, handler, what.exec($location.path())); }, { prefix: regExpPrefix(what) }); } }; var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp }; for (var n in check) { if (check[n]) return this.rule(strategies[n](what, handler)); } throw new Error("invalid 'what' in when()"); }; /** * @ngdoc function * @name ui.router.router.$urlRouterProvider#deferIntercept * @methodOf ui.router.router.$urlRouterProvider * * @description * Disables (or enables) deferring location change interception. * * If you wish to customize the behavior of syncing the URL (for example, if you wish to * defer a transition but maintain the current URL), call this method at configuration time. * Then, at run time, call `$urlRouter.listen()` after you have configured your own * `$locationChangeSuccess` event handler. * * @example * <pre> * var app = angular.module('app', ['ui.router.router']); * * app.config(function ($urlRouterProvider) { * * // Prevent $urlRouter from automatically intercepting URL changes; * // this allows you to configure custom behavior in between * // location changes and route synchronization: * $urlRouterProvider.deferIntercept(); * * }).run(function ($rootScope, $urlRouter, UserService) { * * $rootScope.$on('$locationChangeSuccess', function(e) { * // UserService is an example service for managing user state * if (UserService.isLoggedIn()) return; * * // Prevent $urlRouter's default handler from firing * e.preventDefault(); * * UserService.handleLogin().then(function() { * // Once the user has logged in, sync the current URL * // to the router: * $urlRouter.sync(); * }); * }); * * // Configures $urlRouter's listener *after* your custom listener * $urlRouter.listen(); * }); * </pre> * * @param {boolean} defer Indicates whether to defer location change interception. Passing no parameter is equivalent to `true`. */ this.deferIntercept = function (defer) { if (defer === undefined) defer = true; interceptDeferred = defer; }; /** * @ngdoc object * @name ui.router.router.$urlRouter * * @requires $location * @requires $rootScope * @requires $injector * @requires $browser * * @description * */ this.$get = $get; $get.$inject = ['$location', '$rootScope', '$injector', '$browser', '$sniffer']; function $get( $location, $rootScope, $injector, $browser, $sniffer) { var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl; function appendBasePath(url, isHtml5, absolute) { if (baseHref === '/') return url; if (isHtml5) return baseHref.slice(0, -1) + url; if (absolute) return baseHref.slice(1) + url; return url; } // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree function update(evt) { if (evt && evt.defaultPrevented) return; var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl; lastPushedUrl = undefined; // TODO: Re-implement this in 1.0 for https://github.com/angular-ui/ui-router/issues/1573 //if (ignoreUpdate) return true; function check(rule) { var handled = rule($injector, $location); if (!handled) return false; if (isString(handled)) $location.replace().url(handled); return true; } var n = rules.length, i; for (i = 0; i < n; i++) { if (check(rules[i])) return; } // always check otherwise last to allow dynamic updates to the set of rules if (otherwise) check(otherwise); } function listen() { listener = listener || $rootScope.$on('$locationChangeSuccess', update); return listener; } rules.sort(function(ruleA, ruleB) { var aLength = ruleA.prefix ? ruleA.prefix.length : 0; var bLength = ruleB.prefix ? ruleB.prefix.length : 0; return bLength - aLength; }); if (!interceptDeferred) listen(); return { /** * @ngdoc function * @name ui.router.router.$urlRouter#sync * @methodOf ui.router.router.$urlRouter * * @description * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`. * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event, * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed * with the transition by calling `$urlRouter.sync()`. * * @example * <pre> * angular.module('app', ['ui.router']) * .run(function($rootScope, $urlRouter) { * $rootScope.$on('$locationChangeSuccess', function(evt) { * // Halt state change from even starting * evt.preventDefault(); * // Perform custom logic * var meetsRequirement = ... * // Continue with the update and state transition if logic allows * if (meetsRequirement) $urlRouter.sync(); * }); * }); * </pre> */ sync: function() { update(); }, listen: function() { return listen(); }, update: function(read) { if (read) { location = $location.url(); return; } if ($location.url() === location) return; $location.url(location); $location.replace(); }, push: function(urlMatcher, params, options) { var url = urlMatcher.format(params || {}); // Handle the special hash param, if needed if (url !== null && params && params['#']) { url += '#' + params['#']; } $location.url(url); lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined; if (options && options.replace) $location.replace(); }, /** * @ngdoc function * @name ui.router.router.$urlRouter#href * @methodOf ui.router.router.$urlRouter * * @description * A URL generation method that returns the compiled URL for a given * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters. * * @example * <pre> * $bob = $urlRouter.href(new UrlMatcher("/about/:person"), { * person: "bob" * }); * // $bob == "/about/bob"; * </pre> * * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate. * @param {object=} params An object of parameter values to fill the matcher's required parameters. * @param {object=} options Options object. The options are: * * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl". * * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher` */ href: function(urlMatcher, params, options) { if (!urlMatcher.validates(params)) return null; var isHtml5 = $locationProvider.html5Mode(); if (angular.isObject(isHtml5)) { isHtml5 = isHtml5.enabled; } isHtml5 = isHtml5 && $sniffer.history; var url = urlMatcher.format(params); options = options || {}; if (!isHtml5 && url !== null) { url = "#" + $locationProvider.hashPrefix() + url; } // Handle special hash param, if needed if (url !== null && params && params['#']) { url += '#' + params['#']; } url = appendBasePath(url, isHtml5, options.absolute); if (!options.absolute || !url) { return url; } var slash = (!isHtml5 && url ? '/' : ''), port = $location.port(); port = (port === 80 || port === 443 ? '' : ':' + port); return [$location.protocol(), '://', $location.host(), port, slash, url].join(''); } }; } } angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('./core'), View = _dereq_('../lib/View'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/View":33,"./core":2}],2:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":7,"../lib/Shim.IE8":32}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver; /** * Creates an always-sorted multi-key bucket that allows ForerunnerDB to * know the index that a document will occupy in an array with minimal * processing, speeding up things like sorted views. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; this._keyArr = sharedPathSolver.parse(orderBy, true); }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); sharedPathSolver = new Path(); /** * Gets / sets the primary key used by the active bucket. * @returns {String} The current primary key. */ Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); /** * Quicksorts a single document into the passed array and * returns the index that the document should occupy. * @param {object} obj The document to calculate index for. * @param {array} arr The array the document index will be * calculated for. * @param {string} item The string key representation of the * document whose index is being calculated. * @param {function} fn The comparison function that is used * to determine if a document is sorted below or above the * document we are calculating the index for. * @returns {number} The index the document should occupy. */ ActiveBucket.prototype.qs = function (obj, arr, item, fn) { // If the array is empty then return index zero if (!arr.length) { return 0; } var lastMidwayIndex = -1, midwayIndex, lookupItem, result, start = 0, end = arr.length - 1; // Loop the data until our range overlaps while (end >= start) { // Calculate the midway point (divide and conquer) midwayIndex = Math.floor((start + end) / 2); if (lastMidwayIndex === midwayIndex) { // No more items to scan break; } // Get the item to compare against lookupItem = arr[midwayIndex]; if (lookupItem !== undefined) { // Compare items result = fn(this, obj, item, lookupItem); if (result > 0) { start = midwayIndex + 1; } if (result < 0) { end = midwayIndex - 1; } } lastMidwayIndex = midwayIndex; } if (result > 0) { return midwayIndex + 1; } else { return midwayIndex; } }; /** * Calculates the sort position of an item against another item. * @param {object} sorter An object or instance that contains * sortAsc and sortDesc methods. * @param {object} obj The document to compare. * @param {string} a The first key to compare. * @param {string} b The second key to compare. * @returns {number} Either 1 for sort a after b or -1 to sort * a before b. * @private */ ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) { var aVals = a.split('.:.'), bVals = b.split('.:.'), arr = sorter._keyArr, count = arr.length, index, sortType, castType; for (index = 0; index < count; index++) { sortType = arr[index]; castType = typeof sharedPathSolver.get(obj, sortType.path); if (castType === 'number') { aVals[index] = Number(aVals[index]); bVals[index] = Number(bVals[index]); } // Check for non-equal items if (aVals[index] !== bVals[index]) { // Return the sorted items if (sortType.value === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.value === -1) { return sorter.sortDesc(aVals[index], bVals[index]); } } } }; /** * Inserts a document into the active bucket. * @param {object} obj The document to insert. * @returns {number} The index the document now occupies. */ ActiveBucket.prototype.insert = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Insert key keyIndex = this.qs(obj, this._data, key, this._sortFunc); this._data.splice(keyIndex, 0, key); } else { this._data.splice(keyIndex, 0, key); } this._objLookup[obj[this._primaryKey]] = key; this._count++; return keyIndex; }; /** * Removes a document from the active bucket. * @param {object} obj The document to remove. * @returns {boolean} True if the document was removed * successfully or false if it wasn't found in the active * bucket. */ ActiveBucket.prototype.remove = function (obj) { var key, keyIndex; key = this._objLookup[obj[this._primaryKey]]; if (key) { keyIndex = this._data.indexOf(key); if (keyIndex > -1) { this._data.splice(keyIndex, 1); delete this._objLookup[obj[this._primaryKey]]; this._count--; return true; } else { return false; } } return false; }; /** * Get the index that the passed document currently occupies * or the index it will occupy if added to the active bucket. * @param {object} obj The document to get the index for. * @returns {number} The index. */ ActiveBucket.prototype.index = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Get key index keyIndex = this.qs(obj, this._data, key, this._sortFunc); } return keyIndex; }; /** * The key that represents the passed document. * @param {object} obj The document to get the key for. * @returns {string} The document key. */ ActiveBucket.prototype.documentKey = function (obj) { var key = '', arr = this._keyArr, count = arr.length, index, sortType; for (index = 0; index < count; index++) { sortType = arr[index]; if (key) { key += '.:.'; } key += sharedPathSolver.get(obj, sortType.path); } // Add the unique identifier on the end of the key key += '.:.' + obj[this._primaryKey]; return key; }; /** * Get the number of documents currently indexed in the active * bucket instance. * @returns {number} The number of documents. */ ActiveBucket.prototype.count = function () { return this._count; }; Shared.finishModule('ActiveBucket'); module.exports = ActiveBucket; },{"./Path":28,"./Shared":31}],4:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver = new Path(); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) { this._store = []; this._keys = []; if (primaryKey !== undefined) { this.primaryKey(primaryKey); } if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'primaryKey'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (this.debug()) { console.log('Setting index', index, sharedPathSolver.parse(index, true)); } // Convert the index object to an array of key val objects this.keys(sharedPathSolver.parse(index, true)); } return this.$super.call(this, index); }); /** * Remove all data from the binary tree. */ BinaryTree.prototype.clear = function () { delete this._data; delete this._left; delete this._right; this._store = []; }; /** * Sets this node's data object. All further inserted documents that * match this node's key and value will be pushed via the push() * method into the this._store array. When deciding if a new data * should be created left, right or middle (pushed) of this node the * new data is checked against the data set via this method. * @param val * @returns {*} */ BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (indexData.value === 1) { result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (this.debug()) { console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result); } if (result !== 0) { if (this.debug()) { console.log('Retuning result %d', result); } return result; } } if (this.debug()) { console.log('Retuning result %d', result); } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.path]; } return hash;*/ return obj[this._keys[0].path]; }; /** * Removes (deletes reference to) either left or right child if the passed * node matches one of them. * @param {BinaryTree} node The node to remove. */ BinaryTree.prototype.removeChildNode = function (node) { if (this._left === node) { // Remove left delete this._left; } else if (this._right === node) { // Remove right delete this._right; } }; /** * Returns the branch this node matches (left or right). * @param node * @returns {String} */ BinaryTree.prototype.nodeBranch = function (node) { if (this._left === node) { return 'left'; } else if (this._right === node) { return 'right'; } }; /** * Inserts a document into the binary tree. * @param data * @returns {*} */ BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (this.debug()) { console.log('Inserting', data); } if (!this._data) { if (this.debug()) { console.log('Node has no data, setting data', data); } // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { if (this.debug()) { console.log('Data is equal (currrent, new)', this._data, data); } //this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } if (result === -1) { if (this.debug()) { console.log('Data is greater (currrent, new)', this._data, data); } // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._right._parent = this; } return true; } if (result === 1) { if (this.debug()) { console.log('Data is less (currrent, new)', this._data, data); } // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } return false; }; BinaryTree.prototype.remove = function (data) { var pk = this.primaryKey(), result, removed, i; if (data instanceof Array) { // Insert array of data removed = []; for (i = 0; i < data.length; i++) { if (this.remove(data[i])) { removed.push(data[i]); } } return removed; } if (this.debug()) { console.log('Removing', data); } if (this._data[pk] === data[pk]) { // Remove this node return this._remove(this); } // Compare the data to work out which branch to send the remove command down result = this._compareFunc(this._data, data); if (result === -1 && this._right) { return this._right.remove(data); } if (result === 1 && this._left) { return this._left.remove(data); } return false; }; BinaryTree.prototype._remove = function (node) { var leftNode, rightNode; if (this._left) { // Backup branch data leftNode = this._left; rightNode = this._right; // Copy data from left node this._left = leftNode._left; this._right = leftNode._right; this._data = leftNode._data; this._store = leftNode._store; if (rightNode) { // Attach the rightNode data to the right-most node // of the leftNode leftNode.rightMost()._right = rightNode; } } else if (this._right) { // Backup branch data rightNode = this._right; // Copy data from right node this._left = rightNode._left; this._right = rightNode._right; this._data = rightNode._data; this._store = rightNode._store; } else { this.clear(); } return true; }; BinaryTree.prototype.leftMost = function () { if (!this._left) { return this; } else { return this._left.leftMost(); } }; BinaryTree.prototype.rightMost = function () { if (!this._right) { return this; } else { return this._right.rightMost(); } }; /** * Searches the binary tree for all matching documents based on the data * passed (query). * @param data * @param options * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.lookup = function (data, options, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, resultArr); } } return resultArr; }; /** * Returns the entire binary tree ordered. * @param {String} type * @param resultArr * @returns {*|Array} */ BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /** * Searches the binary tree for all matching documents based on the regular * expression passed. * @param path * @param val * @param regex * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) { var reTest, thisDataPathVal = sharedPathSolver.get(this._data, path), thisDataPathValSubStr = thisDataPathVal.substr(0, val.length), result; regex = regex || new RegExp('^' + val); resultArr = resultArr || []; if (resultArr._visited === undefined) { resultArr._visited = 0; } resultArr._visited++; result = this.sortAsc(thisDataPathVal, val); reTest = thisDataPathValSubStr === val; if (result === 0) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === -1) { if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === 1) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ /** * Determines if the passed query and options object will be served * by this index successfully or not and gives a score so that the * DB search system can determine how useful this index is in comparison * to other indexes on the same collection. * @param query * @param queryOptions * @param matchOptions * @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}} */ BinaryTree.prototype.match = function (query, queryOptions, matchOptions) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = sharedPathSolver.parseArr(this._index, { verbose: true }); queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return sharedPathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":28,"./Shared":31}],5:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Crc, Overload, ReactorIO, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); sharedPathSolver = new Path(); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. */ Shared.synthesize(Collection.prototype, 'cappedSize'); Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', keyName, {oldData: oldKey}); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = new Date(); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = this.jStringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } // Handle transform update = this.transformIn(update); if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data'); } var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: updated }, options); op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback(false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback(resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback(resultObj); } this._onChange(); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); self.chainSend('insert', doc, {index: index}); //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = this.jStringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = this.jStringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback('Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearchQuery, joinSearchOptions, joinMulti, joinRequire, joinFindResults, joinFindResult, joinItem, joinPrefix, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, l, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinCollectionName]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB if (joinCollection[joinCollectionName]) { joinCollectionInstance = joinCollection[joinCollectionName]; } else { joinCollectionInstance = this._db.collection(joinCollectionName); } // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatch[joinMatchIndex].query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatch[joinMatchIndex].query; joinSearchQuery = self._resolveDynamicQuery(joinMatch[joinMatchIndex].query, resultArr[resultIndex]); } if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; } break; case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatch[joinMatchIndex]; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatch[joinMatchIndex]; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatch[joinMatchIndex]; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatch[joinMatchIndex]; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultCollectionName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = resultArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; Collection.prototype._resolveDynamicQuery = function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = new Path(query.substr(3, query.length - 3)).value(item); } else { pathResult = new Path(query).value(item); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self._resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformIn(data[i]); } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformOut(data[i]); } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } };*/ /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ /*Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } };*/ /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ /*Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; };*/ /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents that matches * the subDocQuery parameter. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; case '2d': index = new Index2d(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data); self.update({}, obj1); } else { self.insert(packet.data); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":8,"./Index2d":11,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":28,"./ReactorIO":29,"./Shared":31}],6:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {Name=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Remove old data this._data.remove(chainPacket.options.oldData); // Add new data this._data.insert(chainPacket.data); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Add new data this._data.insert(chainPacket.data); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); delete this._listeners; if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; Db.prototype.collectionGroup = function (collectionGroupName) { if (collectionGroupName) { // Handle being passed an instance if (collectionGroupName instanceof CollectionGroup) { return collectionGroupName; } this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this); return this._collectionGroup[collectionGroupName]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":5,"./Shared":31}],7:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":9,"./Metrics.js":15,"./Overload":27,"./Shared":31}],8:[function(_dereq_,module,exports){ "use strict"; /** * @mixin */ var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],9:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Collection.js":5,"./Crc.js":8,"./Metrics.js":15,"./Overload":27,"./Shared":31}],10:[function(_dereq_,module,exports){ // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License // Original at: https://github.com/davetroy/geohash-js // Modified by Irrelon Software Limited (http://www.irrelon.com) // to clean up and modularise the code using Node.js-style exports // and add a few helper methods. // @by Rob Evans - rob@irrelon.com "use strict"; /* Define some shared constants that will be used by all instances of the module. */ var bits, base32, neighbors, borders; bits = [16, 8, 4, 2, 1]; base32 = "0123456789bcdefghjkmnpqrstuvwxyz"; neighbors = { right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"}, left: {even: "238967debc01fg45kmstqrwxuvhjyznp"}, top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"}, bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"} }; borders = { right: {even: "bcfguvyz"}, left: {even: "0145hjnp"}, top: {even: "prxz"}, bottom: {even: "028b"} }; neighbors.bottom.odd = neighbors.left.even; neighbors.top.odd = neighbors.right.even; neighbors.left.odd = neighbors.bottom.even; neighbors.right.odd = neighbors.top.even; borders.bottom.odd = borders.left.even; borders.top.odd = borders.right.even; borders.left.odd = borders.bottom.even; borders.right.odd = borders.top.even; var GeoHash = function () {}; GeoHash.prototype.refineInterval = function (interval, cd, mask) { if (cd & mask) { //jshint ignore: line interval[0] = (interval[0] + interval[1]) / 2; } else { interval[1] = (interval[0] + interval[1]) / 2; } }; /** * Calculates all surrounding neighbours of a hash and returns them. * @param {String} centerHash The hash at the center of the grid. * @param options * @returns {*} */ GeoHash.prototype.calculateNeighbours = function (centerHash, options) { var response; if (!options || options.type === 'object') { response = { center: centerHash, left: this.calculateAdjacent(centerHash, 'left'), right: this.calculateAdjacent(centerHash, 'right'), top: this.calculateAdjacent(centerHash, 'top'), bottom: this.calculateAdjacent(centerHash, 'bottom') }; response.topLeft = this.calculateAdjacent(response.left, 'top'); response.topRight = this.calculateAdjacent(response.right, 'top'); response.bottomLeft = this.calculateAdjacent(response.left, 'bottom'); response.bottomRight = this.calculateAdjacent(response.right, 'bottom'); } else { response = []; response[4] = centerHash; response[3] = this.calculateAdjacent(centerHash, 'left'); response[5] = this.calculateAdjacent(centerHash, 'right'); response[1] = this.calculateAdjacent(centerHash, 'top'); response[7] = this.calculateAdjacent(centerHash, 'bottom'); response[0] = this.calculateAdjacent(response[3], 'top'); response[2] = this.calculateAdjacent(response[5], 'top'); response[6] = this.calculateAdjacent(response[3], 'bottom'); response[8] = this.calculateAdjacent(response[5], 'bottom'); } return response; }; /** * Calculates an adjacent hash to the hash passed, in the direction * specified. * @param {String} srcHash The hash to calculate adjacent to. * @param {String} dir Either "top", "left", "bottom" or "right". * @returns {String} The resulting geohash. */ GeoHash.prototype.calculateAdjacent = function (srcHash, dir) { srcHash = srcHash.toLowerCase(); var lastChr = srcHash.charAt(srcHash.length - 1), type = (srcHash.length % 2) ? 'odd' : 'even', base = srcHash.substring(0, srcHash.length - 1); if (borders[dir][type].indexOf(lastChr) !== -1) { base = this.calculateAdjacent(base, dir); } return base + base32[neighbors[dir][type].indexOf(lastChr)]; }; /** * Decodes a string geohash back to longitude/latitude. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { latitude: lat, longitude: lon }; }; /** * Encodes a longitude/latitude to geohash string. * @param latitude * @param longitude * @param {Number=} precision Length of the geohash string. Defaults to 12. * @returns {String} */ GeoHash.prototype.encode = function (latitude, longitude, precision) { var isEven = 1, mid, lat = [], lon = [], bit = 0, ch = 0, geoHash = ""; if (!precision) { precision = 12; } lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; while (geoHash.length < precision) { if (isEven) { mid = (lon[0] + lon[1]) / 2; if (longitude > mid) { ch |= bits[bit]; //jshint ignore: line lon[0] = mid; } else { lon[1] = mid; } } else { mid = (lat[0] + lat[1]) / 2; if (latitude > mid) { ch |= bits[bit]; //jshint ignore: line lat[0] = mid; } else { lat[1] = mid; } } isEven = !isEven; if (bit < 4) { bit++; } else { geoHash += base32[ch]; bit = 0; ch = 0; } } return geoHash; }; module.exports = GeoHash; },{}],11:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.lookup = function (query, options) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options) { var self = this, geoHash, neighbours, visited, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } // Get the lngLat geohash from the query geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision); // Calculate 9 box geohashes neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'}); // Lookup all matching co-ordinates from the btree results = []; visited = 0; for (i = 0; i < 9; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visited += search._visited; results = results.concat(search); } // Work with original data results = this._collection._primaryIndex.lookup(results); if (results.length) { distance = {}; // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { // Add item inside radius distance finalResults.push(results[i]); } } // Sort by distance from center finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var φ1 = this.toRadians(lat1); var φ2 = this.toRadians(lat2); var Δφ = this.toRadians(lat2-lat1); var Δλ = this.toRadians(lng2-lng1); var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ/2) * Math.sin(Δλ/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; Index2d.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; Index2d.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":4,"./GeoHash":10,"./Path":28,"./Shared":31}],12:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * The index class used to instantiate btree indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query, options) { return this._btree.lookup(query, options); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":4,"./Path":28,"./Shared":31}],13:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":28,"./Shared":31}],14:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} val A lookup query. * @returns {*} */ KeyValueStore.prototype.lookup = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, result = []; // Check for early exit conditions if (valType === 'string' || valType === 'number') { lookupItem = this.get(val); if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } else if (valType === 'object') { if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this.lookup(val[arrIndex]); if (lookupItem) { if (lookupItem instanceof Array) { result = result.concat(lookupItem); } else { result.push(lookupItem); } } } return result; } else if (val[pk]) { return this.lookup(val[pk]); } } // COMMENTED AS CODE WILL NEVER BE REACHED // Complex lookup /*lookupData = this._lookupKeys(val); keys = lookupData.keys; negate = lookupData.negate; if (!negate) { // Loop keys and return values for (arrIndex = 0; arrIndex < keys.length; arrIndex++) { result.push(this.get(keys[arrIndex])); } } else { // Loop data and return non-matching keys for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (keys.indexOf(arrIndex) === -1) { result.push(this.get(arrIndex)); } } } } return result;*/ }; // COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES /*KeyValueStore.prototype._lookupKeys = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, bool, result; if (valType === 'string' || valType === 'number') { return { keys: [val], negate: false }; } else if (valType === 'object') { if (val instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (val.test(arrIndex)) { result.push(arrIndex); } } } return { keys: result, negate: false }; } else if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { result = result.concat(this._lookupKeys(val[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val.$in && (val.$in instanceof Array)) { return { keys: this._lookupKeys(val.$in).keys, negate: false }; } else if (val.$nin && (val.$nin instanceof Array)) { return { keys: this._lookupKeys(val.$nin).keys, negate: true }; } else if (val.$ne) { return { keys: this._lookupKeys(val.$ne, true).keys, negate: true }; } else if (val.$or && (val.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) { result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val[pk]) { return this._lookupKeys(val[pk]); } } };*/ /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":31}],15:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":26,"./Shared":31}],16:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],17:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * * @param obj */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index; for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } if (arrItem.chainReceive) { arrItem.chainReceive(this, type, data, options); } } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; if (this.debug && this.debug()) { console.log(this.logIdentifier() + 'Received data from parent reactor node'); } // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],18:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined && data !== "") { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return serialiser.parse(data); //return JSON.parse(data); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { return serialiser.stringify(data); //return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return this.classIdentifier() + ': ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; } }; module.exports = Common; },{"./Overload":27,"./Serialiser":30}],19:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],20:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":27}],21:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; } }; module.exports = Matching; },{}],22:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],23:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],24:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":27}],25:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],26:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":28,"./Shared":31}],27:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, name; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } name = typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload: ', def); throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],28:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Gets a single value from the passed object and given path. * @param {Object} obj The object to inspect. * @param {String} path The path to retrieve data from. * @returns {*} */ Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; // Detect early exit if (path && path.indexOf('.') === -1) { return [obj[path]]; } if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.get(obj[i], path)); } return returnArr; } } valuesArr = []; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":31}],29:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); delete this._listeners; } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":31}],30:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { this._encoder = []; this._decoder = {}; // Handler for Date() objects this.registerEncoder('$date', function (data) { if (data instanceof Date) { return data.toISOString(); } }); this.registerDecoder('$date', function (data) { return new Date(data); }); // Handler for RegExp() objects this.registerEncoder('$regexp', function (data) { if (data instanceof RegExp) { return { source: data.source, params: '' + (data.global ? 'g' : '') + (data.ignoreCase ? 'i' : '') }; } }); this.registerDecoder('$regexp', function (data) { var type = typeof data; if (type === 'object') { return new RegExp(data.source, data.params); } else if (type === 'string') { return new RegExp(data); } }); }; /** * Register an encoder that can handle encoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. * @param {Function} method The encoder method. */ Serialiser.prototype.registerEncoder = function (handles, method) { this._encoder.push(function (data) { var methodVal = method(data), returnObj; if (methodVal !== undefined) { returnObj = {}; returnObj[handles] = methodVal; } return returnObj; }); }; /** * Register a decoder that can handle decoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. When an object * has a field matching this handler name then this decode will be invoked * to provide a decoded version of the data that was previously encoded by * it's counterpart encoder method. * @param {Function} method The decoder method. */ Serialiser.prototype.registerDecoder = function (handles, method) { this._decoder[handles] = method; }; /** * Loops the encoders and asks each one if it wants to handle encoding for * the passed data object. If no value is returned (undefined) then the data * will be passed to the next encoder and so on. If a value is returned the * loop will break and the encoded data will be used. * @param {Object} data The data object to handle. * @returns {*} The encoded data. * @private */ Serialiser.prototype._encode = function (data) { // Loop the encoders and if a return value is given by an encoder // the loop will exit and return that value. var count = this._encoder.length, retVal; while (count-- && !retVal) { retVal = this._encoder[count](data); } return retVal; }; /** * Converts a previously encoded string back into an object. * @param {String} data The string to convert to an object. * @returns {Object} The reconstituted object. */ Serialiser.prototype.parse = function (data) { return this._parse(JSON.parse(data)); }; /** * Handles restoring an object with special data markers back into * it's original format. * @param {Object} data The object to recurse. * @param {Object=} target The target object to restore data to. * @returns {Object} The final restored object. * @private */ Serialiser.prototype._parse = function (data, target) { var i; if (typeof data === 'object' && data !== null) { if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and handle // special object types and restore them for (i in data) { if (data.hasOwnProperty(i)) { if (i.substr(0, 1) === '$' && this._decoder[i]) { // This is a special object type and a handler // exists, restore it return this._decoder[i](data[i]); } // Not a special object or no handler, recurse as normal target[i] = this._parse(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; /** * Converts an object to a encoded string representation. * @param {Object} data The object to encode. */ Serialiser.prototype.stringify = function (data) { return JSON.stringify(this._stringify(data)); }; /** * Recurse down an object and encode special objects so they can be * stringified and later restored. * @param {Object} data The object to parse. * @param {Object=} target The target object to store converted data to. * @returns {Object} The converted object. * @private */ Serialiser.prototype._stringify = function (data, target) { var handledData, i; if (typeof data === 'object' && data !== null) { // Handle special object types so they can be encoded with // a special marker and later restored by a decoder counterpart handledData = this._encode(data); if (handledData) { // An encoder handled this object type so return it now return handledData; } if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and serialise for (i in data) { if (data.hasOwnProperty(i)) { target[i] = this._stringify(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; module.exports = Serialiser; },{}],31:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.549', modules: {}, plugins: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, /** * Adds the properties and methods defined in the mixin to the passed object. * @memberof Shared * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ mixin: new Overload({ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":27}],32:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}],33:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket; Shared = _dereq_('./Shared'); /** * Creates a new view instance. * @param {String} name The name of the view. * @param {Object=} query The view's query. * @param {Object=} options An options object. * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; View.prototype.init = function (name, query, options) { var self = this; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, false); this.queryOptions(options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._privateData = new Collection(this.name() + '_internalPrivate'); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); Shared.mixin(View.prototype, 'Mixin.Triggers'); Shared.mixin(View.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); /** * Gets / sets the current name. * @param {String=} val The new name to set. * @returns {*} */ Shared.synthesize(View.prototype, 'name'); /** * Gets / sets the current cursor. * @param {String=} val The new cursor to set. * @returns {*} */ Shared.synthesize(View.prototype, 'cursor', function (val) { if (val === undefined) { return this._cursor || {}; } this.$super.apply(this, arguments); }); /** * Executes an insert against the view's underlying data-source. * @see Collection::insert() */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. * @see Collection::update() */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. * @see Collection::updateById() */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. * @see Collection::remove() */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. * @see Collection::find() * @returns {Array} The result of the find query. */ View.prototype.find = function (query, options) { return this.publicData().find(query, options); }; /** * Queries the view data for a single document. * @see Collection::findOne() * @returns {Object} The result of the find query. */ View.prototype.findOne = function (query, options) { return this.publicData().findOne(query, options); }; /** * Queries the view data by specific id. * @see Collection::findById() * @returns {Array} The result of the find query. */ View.prototype.findById = function (id, options) { return this.publicData().findById(id, options); }; /** * Queries the view data in a sub-array. * @see Collection::findSub() * @returns {Array} The result of the find query. */ View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this.publicData().findSub(match, path, subDocQuery, subDocOptions); }; /** * Queries the view data in a sub-array and returns first match. * @see Collection::findSubOne() * @returns {Object} The result of the find query. */ View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.publicData().findSubOne(match, path, subDocQuery, subDocOptions); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._privateData; }; /** * Sets the source from which the view will assemble its data. * @param {Collection|View} source The source to use to assemble view data. * @param {Function=} callback A callback method. * @returns {*} If no argument is passed, returns the current value of from, * otherwise returns itself for chaining. */ View.prototype.from = function (source, callback) { var self = this; if (source !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); delete this._from; } // Check if we have an existing reactor io if (this._io) { // Drop the io and remove it this._io.drop(); delete this._io; } if (typeof(source) === 'string') { source = this._db.collection(source); } if (source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } this._from = source; this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's "from" source and determines how they should be interpreted by // this view. If the view does not have a query then this reactor IO will // simply pass along the chain packet without modifying it. this._io = new ReactorIO(source, this, function (chainPacket) { var data, diff, query, filteredData, doSend, pk, i; // Check that the state of the "self" object is not dropped if (self && !self.isDropped()) { // Check if we have a constraining query if (self._querySettings.query) { if (chainPacket.type === 'insert') { data = chainPacket.data; // Check if the data matches our query if (data instanceof Array) { filteredData = []; for (i = 0; i < data.length; i++) { if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData.push(data[i]); doSend = true; } } } else { if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData = data; doSend = true; } } if (doSend) { this.chainSend('insert', filteredData); } return true; } if (chainPacket.type === 'update') { // Do a DB diff between this view's data and the underlying collection it reads from // to see if something has changed diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options)); if (diff.insert.length || diff.remove.length) { // Now send out new chain packets for each operation if (diff.insert.length) { this.chainSend('insert', diff.insert); } if (diff.update.length) { pk = self._privateData.primaryKey(); for (i = 0; i < diff.update.length; i++) { query = {}; query[pk] = diff.update[i][pk]; this.chainSend('update', { query: query, update: diff.update[i] }); } } if (diff.remove.length) { pk = self._privateData.primaryKey(); var $or = [], removeQuery = { query: { $or: $or } }; for (i = 0; i < diff.remove.length; i++) { $or.push({_id: diff.remove[i][pk]}); } this.chainSend('remove', removeQuery); } // Return true to stop further propagation of the chain packet return true; } else { // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } } } } // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; }); var collData = source.find(this._querySettings.query, this._querySettings.options); this._privateData.primaryKey(source.primaryKey()); this._privateData.setData(collData, {}, callback); if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; } return this._from; }; /** * Handles when an underlying collection the view is using as a data * source is dropped. * @param {Collection} collection The collection that has been dropped. * @private */ View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; /** * Creates an index on the view. * @see Collection::ensureIndex() * @returns {*} */ View.prototype.ensureIndex = function () { return this._privateData.ensureIndex.apply(this._privateData, arguments); }; /** * The chain reaction handler method for the view. * @param {Object} chainPacket The chain reaction packet to handle. * @private */ View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, updates, primaryKey, item, currentIndex; if (this.debug()) { console.log(this.logIdentifier() + ' Received chain reactor data'); } switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); this._privateData.setData(collData); break; case 'insert': if (this.debug()) { console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Make sure we are working with an array if (!(chainPacket.data instanceof Array)) { chainPacket.data = [chainPacket.data]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); this._privateData._insertHandle(chainPacket.data, insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._privateData._data.length; this._privateData._insertHandle(chainPacket.data, insertIndex); } break; case 'update': if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"'); } primaryKey = this._privateData.primaryKey(); // Do the update updates = this._privateData.update( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._privateData._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex); } } } break; case 'remove': if (this.debug()) { console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"'); } this._privateData.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; /** * Listens for an event. * @see Mixin.Events::on() */ View.prototype.on = function () { return this._privateData.on.apply(this._privateData, arguments); }; /** * Cancels an event listener. * @see Mixin.Events::off() */ View.prototype.off = function () { return this._privateData.off.apply(this._privateData, arguments); }; /** * Emits an event. * @see Mixin.Events::emit() */ View.prototype.emit = function () { return this._privateData.emit.apply(this._privateData, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { var coll = this.publicData(); return coll.distinct.apply(coll, arguments); }; /** * Gets the primary key for this view from the assigned collection. * @see Collection::primaryKey() * @returns {String} */ View.prototype.primaryKey = function () { return this.publicData().primaryKey(); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._privateData) { this._privateData.drop(); } if (this._publicData && this._publicData !== this._privateData) { this._publicData.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._chain; delete this._from; delete this._privateData; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } return false; }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @memberof View * @returns {*} */ Shared.synthesize(View.prototype, 'db', function (db) { if (db) { this.privateData().db(db); this.publicData().db(db); // Apply the same debug settings this.debug(db.debug()); this.privateData().debug(db.debug()); this.publicData().debug(db.debug()); } return this.$super.apply(this, arguments); }); /** * Gets / sets the query object and query options that the view uses * to build it's data set. This call modifies both the query and * query options at the same time. * @param {Object=} query The query to set. * @param {Boolean=} options The query options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._privateData.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._privateData.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (query) { if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } } }; /** * Gets / sets the query being used to generate the view data. It * does not change or modify the view's query options. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = function (query, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._privateData.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._privateData.name(); } if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings.query; }; /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { this.rebuildActiveBucket(options.$orderBy); } return this; } return this._querySettings.options; }; View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._privateData._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._privateData.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { if (this._from) { var pubData = this.publicData(), refreshResults; // Re-grab all the data for the view from the collection this._privateData.remove(); //pubData.remove(); refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); this._privateData.insert(refreshResults); this._privateData._data.$cursor = refreshResults.$cursor; pubData._data.$cursor = refreshResults.$cursor; /*if (pubData._linked) { // Update data and observers //var transformedData = this._privateData.find(); // TODO: Shouldn't this data get passed into a transformIn first? // TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data // TODO: Is this even required anymore? After commenting it all seems to work // TODO: Might be worth setting up a test to check transforms and linking then remove this if working? //jQuery.observable(pubData._data).refresh(transformedData); }*/ } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { if (this.publicData()) { return this.publicData().count.apply(this.publicData(), arguments); } return 0; }; // Call underlying View.prototype.subset = function () { return this.publicData().subset.apply(this._privateData, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { var self = this; if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } if (this._transformEnabled) { // Check for / create the public data collection if (!this._publicData) { // Create the public data collection this._publicData = new Collection('__FDB__view_publicData_' + this._name); this._publicData.db(this._privateData._db); this._publicData.transform({ enabled: true, dataIn: this._transformIn, dataOut: this._transformOut }); // Create a chain reaction IO node to keep the private and // public data collections in sync this._transformIo = new ReactorIO(this._privateData, this._publicData, function (chainPacket) { var data = chainPacket.data; switch (chainPacket.type) { case 'primaryKey': self._publicData.primaryKey(data); this.chainSend('primaryKey', data); break; case 'setData': self._publicData.setData(data); this.chainSend('setData', data); break; case 'insert': self._publicData.insert(data); this.chainSend('insert', data); break; case 'update': // Do the update self._publicData.update( data.query, data.update, data.options ); this.chainSend('update', data); break; case 'remove': self._publicData.remove(data.query, chainPacket.options); this.chainSend('remove', data); break; default: break; } }); } // Set initial data and settings this._publicData.primaryKey(this.privateData().primaryKey()); this._publicData.setData(this.privateData().find()); } else { // Remove the public data collection if (this._publicData) { this._publicData.drop(); delete this._publicData; if (this._transformIo) { this._transformIo.drop(); delete this._transformIo; } } } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return (this.publicData()).filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.privateData = function () { return this._privateData; }; /** * Returns a data object representing the public data this view * contains. This can change depending on if transforms are being * applied to the view or not. * * If no transforms are applied then the public data will be the * same as the private data the view holds. If transforms are * applied then the public data will contain the transformed version * of the private data. * * The public data collection is also used by data binding to only * changes to the publicData will show in a data-bound element. */ View.prototype.publicData = function () { if (this._transformEnabled) { return this._publicData; } else { return this._privateData; } }; // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (viewName) { var self = this; // Handle being passed an instance if (viewName instanceof View) { return viewName; } if (this._view[viewName]) { return this._view[viewName]; } else { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating view ' + viewName); } } this._view[viewName] = this._view[viewName] || new View(viewName).db(this); self.emit('create', [self._view[viewName], 'view', viewName]); return this._view[viewName]; }; /** * Determine if a view with the passed name already exists. * @param {String} viewName The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (viewName) { return Boolean(this._view[viewName]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], view, i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { view = this._view[i]; arr.push({ name: i, count: view.count(), linked: view.isLinked !== undefined ? view.isLinked() : false }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./ReactorIO":29,"./Shared":31}]},{},[1]);
/** * @class Ext.draw.sprite.Rect * @extends Ext.draw.sprite.Path * * A sprite that represents a rectangle. * * @example preview miniphone * var component = new Ext.draw.Component({ * items: [{ * type: 'rect', * x: 50, * y: 50, * width: 50, * height: 50, * fillStyle: 'blue' * }] * }); * Ext.Viewport.setLayout('fit'); * Ext.Viewport.add(component); */ Ext.define("Ext.draw.sprite.Rect", { extend: "Ext.draw.sprite.Path", alias: 'sprite.rect', type: 'rect', inheritableStatics: { def: { processors: { /** * @cfg {Number} [x=0] The position of the sprite on the x-axis. */ x: 'number', /** * @cfg {Number} [y=0] The position of the sprite on the y-axis. */ y: 'number', /** * @cfg {Number} [width=1] The width of the sprite. */ width: 'number', /** * @cfg {Number} [height=1] The height of the sprite. */ height: 'number', /** * @cfg {Number} [radius=0] The radius of the rounded corners. */ radius: 'number' }, aliases: { }, dirtyTriggers: { x: 'path', y: 'path', width: 'path', height: 'path', radius: 'path' }, defaults: { x: 0, y: 0, width: 1, height: 1, radius: 0 } } }, updatePlainBBox: function (plain) { var attr = this.attr; plain.x = attr.x; plain.y = attr.y; plain.width = attr.width; plain.height = attr.height; }, updateTransformedBBox: function (transform, plain) { this.attr.matrix.transformBBox(plain, this.attr.radius, transform); }, updatePath: function (path, attr) { var x = attr.x, y = attr.y, width = attr.width, height = attr.height, radius = Math.min(attr.radius, Math.abs(attr.height) * 0.5, Math.abs(attr.width) * 0.5); if (radius === 0) { path.rect(x, y, width, height); } else { path.moveTo(x + radius, y); path.arcTo(x + width, y, x + width, y + height, radius); path.arcTo(x + width, y + height, x, y + height, radius); path.arcTo(x, y + height, x, y, radius); path.arcTo(x, y, x + radius, y, radius); } } });
var TokenExpiredError = require('./TokenExpiredError'); var JsonWebTokenError = require('./JsonWebTokenError'); var ms = require('ms'); function audCheck(payload, options, context) { if (!options.audience) { return; } var audiences = Array.isArray(options.audience) ? options.audience : [options.audience]; var target = Array.isArray(payload.aud) ? payload.aud : [payload.aud]; var match = target.some(function (aud) { return audiences.indexOf(aud) != -1; }); if (!match) { return new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or ')); } } function issCheck(payload, options, context) { if (!options.issuer) { return; } var invalid_issuer = (typeof options.issuer === 'string' && payload.iss !== options.issuer) || (Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1); if (invalid_issuer) { return new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer); } } function subCheck(payload, options, context) { if (!options.subject) { return; } if (payload.sub !== options.subject) { return new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject); } } function jtiCheck(payload, options, context) { if (!options.jwtid) { return; } if (payload.jti !== options.jwtid) { return new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid); } } function maxAgeCheck(payload, options, context) { if (!options.maxAge) { return; } var maxAge = ms(options.maxAge); if (typeof payload.iat !== 'number') { return new JsonWebTokenError('iat required when maxAge is specified'); } // We have to compare against either options.clockTimestamp or the currentDate _with_ millis // to not change behaviour (version 7.2.1). Should be resolve somehow for next major. var nowOrClockTimestamp = ((options.clockTimestamp || 0) * 1000) || Date.now(); if (nowOrClockTimestamp - (payload.iat * 1000) > maxAge + context.clockTolerance * 1000) { return new TokenExpiredError('maxAge exceeded', new Date(payload.iat * 1000 + maxAge)); } } var PayloadVerifier = function(){ this.checks = []; } PayloadVerifier.prototype.use = function(checks) { if (Array.isArray(checks)) { this.checks = this.checks.concat(checks); } else { this.checks.push(checks); } return this; }; PayloadVerifier.prototype.eval = function(payload, options, context) { var i; var checkError; for (i = 0; i < this.checks.length; i++) { checkError = this.checks[i](payload, options, context); if (checkError) { return checkError; } } }; module.exports.defaultChecks = [ require('./verify_checks/nbf'), require('./verify_checks/exp'), require('./verify_checks/aud'), audCheck, issCheck, subCheck, jtiCheck, maxAgeCheck ]; module.exports.PayloadVerifier = PayloadVerifier;
'use strict'; module.exports = { set: function (v) { this.setProperty('margin-right', v); }, get: function () { return this.getPropertyValue('margin-right'); }, enumerable: true };
/*! jQuery-ui-Slider-Pips - v1.5.1 - 2014-04-25 * Copyright (c) 2014 ; Licensed */ // PIPS (function($) { var extensionMethods = { pips: function( settings ) { var slider = this, $pip, pips = ( slider.options.max - slider.options.min ) / slider.options.step; var options = { first: "label", // "label", "pip", false last: "label", // "label", "pip", false rest: "pip", // "label", "pip", false labels: false, // [array], false prefix: "", // "", string suffix: "", // "", string step: ( pips > 100 ) ? Math.floor( pips * 0.1 ) : 1, // number formatLabel: function(value) { return this.prefix + value + this.suffix; } // function // must return a value to display in the pip labels }; $.extend( options, settings ); // get rid of all pips that might already exist. slider.element .addClass("ui-slider-pips") .find(".ui-slider-pip") .remove(); // when we click on a label, we want to make sure the // slider's handle actually goes to that label! function labelClick() { var val = $(this).data("value"), $thisSlider = $(slider.element); if( slider.options.range ) { var sliderVals = $thisSlider.slider("values"); // if the handles are at the same value if ( Math.abs( sliderVals[0] - val ) === Math.abs( sliderVals[1] - val ) ) { $thisSlider.slider("values", [ val , val ] ); // or if the second handle is closest to our label } else if ( Math.abs( sliderVals[0] - val ) < Math.abs( sliderVals[1] - val ) ) { $thisSlider.slider("values", [ val , sliderVals[1] ] ); // of if the first handle is closest to our label } else { $thisSlider.slider("values", [ sliderVals[0], val ] ); } } else { $thisSlider.slider("value", val ); } } // for every stop in the slider; we create a pip. for( var i=0; i<=pips; i++ ) { if( 0 === i || pips === i || i % options.step === 0 ) { // create the label name, it's either the item in the array, or a number. var label, labelValue = slider.options.min + ( slider.options.step * i ); if(options.labels) { label = options.labels[i]; } else { label = labelValue; } if( typeof(label) === "undefined" ) { label = ""; } // hold a span element for the pip var pipHtml = "<span class=\"ui-slider-pip ui-slider-pip-"+i+"\">"+ "<span class=\"ui-slider-line\"></span>"+ "<span class=\"ui-slider-label\">"+ options.formatLabel(label) +"</span>"+ "</span>"; $pip = $(pipHtml) .data("value", labelValue ) .on("click", labelClick ); // first pip if( 0 === i ) { $pip.addClass("ui-slider-pip-first"); if( "label" === options.first ) { $pip.addClass("ui-slider-pip-label"); } if( false === options.first ) { $pip.addClass("ui-slider-pip-hide"); } // last pip } else if ( pips === i ) { $pip.addClass("ui-slider-pip-last"); if( "label" === options.last ) { $pip.addClass("ui-slider-pip-label"); } if( false === options.last ) { $pip.addClass("ui-slider-pip-hide"); } // all other pips } else { if( "label" === options.rest ) { $pip.addClass("ui-slider-pip-label"); } if( false === options.rest ) { $pip.addClass("ui-slider-pip-hide"); } } // if it's a horizontal slider we'll set the left offset, // and the top if it's vertical. if( slider.options.orientation === "horizontal" ) { $pip.css({ left: "" + (100/pips)*i + "%" }); } else { $pip.css({ bottom: "" + (100/pips)*i + "%" }); } // append the span to the slider. slider.element.append( $pip ); } } } }; $.extend(true, $["ui"]["slider"].prototype, extensionMethods); })(jQuery); // FLOATS (function($) { var extensionMethods = { float: function( settings ) { var slider = this, $tip, vals = [], val; var options = { handle: true, // false pips: false, // true labels: false, // array prefix: "", // "", string suffix: "", // "", string event: "slidechange slide", // "slidechange", "slide", "slidechange slide" formatLabel: function(value) { return this.prefix + value + this.suffix; } // function // must return a value to display in the floats }; $.extend( options, settings ); if( slider.options.value < slider.options.min ) { slider.options.value = slider.options.min; } if( slider.options.value > slider.options.max ) { slider.options.value = slider.options.max; } if( slider.options.values ) { if( slider.options.values[0] < slider.options.min ) { slider.options.values[0] = slider.options.min; } if( slider.options.values[1] < slider.options.min ) { slider.options.values[1] = slider.options.min; } if( slider.options.values[0] > slider.options.max ) { slider.options.values[0] = slider.options.max; } if( slider.options.values[1] > slider.options.max ) { slider.options.values[1] = slider.options.max; } } // add a class for the CSS slider.element .addClass("ui-slider-float") .find(".ui-slider-tip, .ui-slider-tip-label") .remove(); // apply handle tip if settings allows. if( options.handle ) { // if this is a range slider if( slider.options.values ) { if( options.labels ) { vals[0] = options.labels[ slider.options.values[0] - slider.options.min ]; vals[1] = options.labels[ slider.options.values[1] - slider.options.min ]; if( typeof(vals[0]) === "undefined" ) { vals[0] = slider.options.values[0]; } if( typeof(vals[1]) === "undefined" ) { vals[1] = slider.options.values[1]; } } else { vals[0] = slider.options.values[0]; vals[1] = slider.options.values[1]; } $tip = [ $("<span class=\"ui-slider-tip\">"+ options.formatLabel(vals[0]) +"</span>"), $("<span class=\"ui-slider-tip\">"+ options.formatLabel(vals[1]) +"</span>") ]; // else if its just a normal slider } else { if( options.labels ) { val = options.labels[ slider.options.value - slider.options.min ]; if( typeof(val) === "undefined" ) { val = slider.options.value; } } else { val = slider.options.value; } // create a tip element $tip = $("<span class=\"ui-slider-tip\">"+ options.formatLabel(val) +"</span>"); } // now we append it to all the handles slider.element.find(".ui-slider-handle").each( function(k,v) { $(v).append($tip[k]); }); } if( options.pips ) { // if this slider also has pip-labels, we"ll make those into tips, too; by cloning and changing class. slider.element.find(".ui-slider-label").each(function(k,v) { var $e = $(v).clone().removeClass("ui-slider-label").addClass("ui-slider-tip-label"); $e.insertAfter($(v)); }); } if( options.event !== "slide" && options.event !== "slidechange" && options.event !== "slide slidechange" && options.event !== "slidechange slide" ) { options.event = "slidechange slide"; } // when slider changes, update handle tip label. slider.element.on( options.event , function( e, ui ) { var val; if( options.labels ) { val = options.labels[ui.value-slider.options.min]; if( typeof(val) === "undefined" ) { val = ui.value; } } else { val = ui.value; } $(ui.handle).find(".ui-slider-tip").html( options.formatLabel(val) ); }); } }; $.extend(true, $["ui"]["slider"].prototype, extensionMethods); })(jQuery);
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /** * Copyright (c) Nicolas Gallagher. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AnimatedImplementation from '../../vendor/react-native/Animated/AnimatedImplementation'; import FlatList from '../FlatList'; import Image from '../Image'; import SectionList from '../SectionList'; import ScrollView from '../ScrollView'; import Text from '../Text'; import View from '../View'; var Animated = _objectSpread({}, AnimatedImplementation, { FlatList: AnimatedImplementation.createAnimatedComponent(FlatList, { scrollEventThrottle: 0.0001 }), Image: AnimatedImplementation.createAnimatedComponent(Image), ScrollView: AnimatedImplementation.createAnimatedComponent(ScrollView, { scrollEventThrottle: 0.0001 }), SectionList: AnimatedImplementation.createAnimatedComponent(SectionList, { scrollEventThrottle: 0.0001 }), View: AnimatedImplementation.createAnimatedComponent(View), Text: AnimatedImplementation.createAnimatedComponent(Text) }); export default Animated;
var path = require('path'); var flattenGlob = function(arr){ var out = []; var flat = true; for(var i = 0; i < arr.length; i++) { if (typeof arr[i] !== 'string') { flat = false; break; } out.push(arr[i]); } if (flat) out.pop(); // last one is a file or specific dir return out; }; var flattenExpansion = function(set) { // dirty trick // use the first two items in the set to figure out // where the expansion starts return findCommon(set[0], set[1]); }; // algorithm assumes both arrays have the same length // because this is how globs work var findCommon = function(a1, a2) { var len = a1.length; for (var i = 0; i < len; i++) { if (a1[i] !== a2[i]) { if(typeof a1[i - 1] == 'string') return a1.slice(0, i); return a1.slice(0, i - 1); // fix for double bracket expansion } } return a1; // identical }; var setToBase = function(set) { // normal something/*.js if (set.length <= 1) { return flattenGlob(set[0]); } // has expansion return flattenExpansion(set); }; module.exports = function(glob) { var cwd = (glob.options && glob.options.cwd) ? glob.options.cwd : process.cwd(); var set = glob.minimatch.set; var basePath = path.normalize(setToBase(set).join(path.sep))+path.sep; return basePath; };
/*! * froala_editor v2.0.3 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms * Copyright 2014-2015 Froala Labs */ /** * Swedish */ $.FroalaEditor.LANGUAGE['sv'] = { translation: { // Place holder "Type something": "Ange n\u00e5got", // Basic formatting "Bold": "Fetstil", "Italic": "Kursiv stil", "Underline": "Understruken", "Strikethrough": "Genomstruken", // Main buttons "Insert": "Infoga", "Delete": "Radera", "Cancel": "Avbryt", "OK": "Ok", "Back": "Tillbaka", "Remove": "Avl\u00e4gsna", "More": "Vi\u0161e", "Update": "Uppdatera", "Style": "Stil", // Font "Font Family": "Teckensnitt", "Font Size": "Storlek", // Colors "Colors": "F\u00e4rger", "Background": "Bakgrund", "Text": "Text", // Paragraphs "Paragraph Format": "Format", "Normal": "Normal", "Code": "Kod", "Heading 1": "Rubrik 1", "Heading 2": "Rubrik 2", "Heading 3": "Rubrik 3", "Heading 4": "Rubrik 4", // Style "Paragraph Style": "Styckeformat", "Inline Style": "Infogad stil", // Alignment "Align": "Justera", "Align Left": "V\u00e4nsterst\u00e4ll", "Align Center": "Centrera", "Align Right": "H\u00f6gerst\u00e4ll", "Align Justify": "Justera", "None": "Inget", // Lists "Ordered List": "Ordnad lista", "Unordered List": "Oordnad lista", // Indent "Decrease Indent": "Minska indrag", "Increase Indent": "\u00d6ka indrag", // Links "Insert Link": "Infoga l\u00e4nk", "Open in new tab": "\u00d6ppna i ny flik", "Open Link": "\u00d6ppna l\u00e4nk", "Edit Link": "Redigera l\u00e4nk", "Unlink": "Ta bort l\u00e4nk", "Choose Link": "V\u00e4lj l\u00e4nk", // Images "Insert Image": "Infoga bild", "Upload Image": "Ladda upp en bild", "By URL": "Genom URL", "Browse": "Bl\u00e4ddra", "Drop image": "Sl\u00e4ppa bild", "or click": "eller klicka", "Manage Images": "Hantera bilder", "Loading": "L\u00e4ser", "Deleting": "Radera", "Tags": "Taggar", "Are you sure? Image will be deleted.": "\u00c4r du s\u00e4ker? Bild kommer att raderas.", "Replace": "Ers\u00e4tt", "Uploading": "Uppladdning", "Loading image": "Laddar bild", "Display": "Visa", "Inline": "I k\u00f6", "Break Text": "Break text", "Alternate Text": "Alternativ text", "Change Size": "\u00c4ndra storlek", "Width": "Bredd", "Height": "H\u00f6jd", "Something went wrong. Please try again.": "N\u00e5got gick snett. Var god f\u00f6rs\u00f6k igen.", // Video "Insert Video": "Infoga video", "Embedded Code": "Inb\u00e4ddad kod", // Tables "Insert Table": "Infoga tabell", "Header": "Header", "Row": "Rad", "Insert row above": "Infoga rad f\u00f6re", "Insert row below": "Infoga rad efter", "Delete row": "Radera rad", "Column": "Kolumn", "Insert column before": "Infoga kollumn f\u00f6re", "Insert column after": "Infoga kolumn efter", "Delete column": "Radera kolumn", "Cell": "Cell", "Merge cells": "Sammanfoga celler", "Horizontal split": "Horisontell split", "Vertical split": "Vertikal split", "Cell Background": "Cellbakgrunden", "Vertical Align": "Vertikala justeringen", "Top": "Topp", "Middle": "Mitten", "Bottom": "Botten", "Align Top": "Justera topp", "Align Middle": "Justera mitten", "Align Bottom": "Justera botten", "Cell Style": "Cellformat", // Files "Upload File": "Ladda upp fil", "Drop file": "Sl\u00e4ppa fil", // Emoticons "Emoticons": "Uttryckssymboler", "Grinning face": "Grina ansikte", "Grinning face with smiling eyes": "Grina ansikte med leende \u00f6gon", "Face with tears of joy": "Face med gl\u00e4djet\u00e5rar", "Smiling face with open mouth": "Leende ansikte med \u00f6ppen mun", "Smiling face with open mouth and smiling eyes": "Leende ansikte med \u00f6ppen mun och leende \u00f6gon", "Smiling face with open mouth and cold sweat": "Leende ansikte med \u00f6ppen mun och kallsvett", "Smiling face with open mouth and tightly-closed eyes": "Leende ansikte med \u00f6ppen mun och t\u00e4tt slutna \u00f6gon", "Smiling face with halo": "Leende ansikte med halo", "Smiling face with horns": "Leende ansikte med horn", "Winking face": "Blinka ansikte", "Smiling face with smiling eyes": "Leende ansikte med leende \u00f6gon", "Face savoring delicious food": "Ansikte smaka uts\u00f6kt mat", "Relieved face": "L\u00e4ttad ansikte", "Smiling face with heart-shaped eyes": "Leende ansikte med hj\u00e4rtformade \u00f6gon", "Smiling face with sunglasses": "Leende ansikte med solglas\u00f6gon", "Smirking face": "Flinande ansikte", "Neutral face": "Neutral ansikte", "Expressionless face": "Uttryckslöst ansikte", "Unamused face": "Inte roade ansikte", "Face with cold sweat": "Ansikte med kallsvett", "Pensive face": "Eftert\u00e4nksamt ansikte", "Confused face": "F\u00f6rvirrad ansikte", "Confounded face": "F\u00f6rbryllade ansikte", "Kissing face": "Kyssande ansikte", "Face throwing a kiss": "Ansikte kasta en kyss", "Kissing face with smiling eyes": "Kyssa ansikte med leende \u00f6gon", "Kissing face with closed eyes": "Kyssa ansikte med slutna \u00f6gon", "Face with stuck out tongue": "Ansikte med stack ut tungan", "Face with stuck out tongue and winking eye": "Ansikte med stack ut tungan och blinkande \u00f6ga", "Face with stuck out tongue and tightly-closed eyes": "Ansikte med stack ut tungan och t\u00e4tt slutna \u00f6gon", "Disappointed face": "Besviken ansikte", "Worried face": "Orolig ansikte", "Angry face": "Argt ansikte", "Pouting face": "Sk\u00e4ggtorsk ansikte", "Crying face": "Gr\u00e5tande ansikte", "Persevering face": "Uth\u00e5llig ansikte", "Face with look of triumph": "Ansikte med utseendet p\u00e5 triumf", "Disappointed but relieved face": "Besviken men l\u00e4ttad ansikte", "Frowning face with open mouth": "Rynkar pannan ansikte med \u00f6ppen mun", "Anguished face": "\u00c5ngest ansikte", "Fearful face": "R\u00e4dda ansikte", "Weary face": "Tr\u00f6tta ansikte", "Sleepy face": "S\u00f6mnig ansikte", "Tired face": "Tr\u00f6tt ansikte", "Grimacing face": "Grimaserande ansikte", "Loudly crying face": "H\u00f6gt gr\u00e5tande ansikte", "Face with open mouth": "Ansikte med \u00f6ppen mun", "Hushed face": "D\u00e4mpade ansikte", "Face with open mouth and cold sweat": "Ansikte med \u00f6ppen mun och kallsvett", "Face screaming in fear": "Face skriker i skr\u00e4ck", "Astonished face": "F\u00f6rv\u00e5nad ansikte", "Flushed face": "Ansiktsrodnad", "Sleeping face": "Sovande anskite", "Dizzy face": "Yr ansikte", "Face without mouth": "Ansikte utan mun", "Face with medical mask": "Ansikte med medicinsk maskera", // Line breaker "Break": "Break", // Math "Subscript": "Neds\u00e4nkt", "Superscript": "Upph\u00f6jd text", // Full screen "Fullscreen": "Helsk\u00e4rm", // Horizontal line "Insert Horizontal Line": "Infoga horisontell linje", // Clear formatting "Clear Formatting": "Ta bort formatering", // Undo, redo "Undo": "\u00c5ngra", "Redo": "G\u00f6r om", // Select all "Select All": "Markera allt", // Code view "Code View": "Kodvyn", // Quote "Quote": "Citerar", "Increase": "\u00d6ka", "Decrease": "Minska" }, direction: "ltr" };
/**! * AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort, * progress, resize, thumbnail, preview, validation and CORS * FileAPI Flash shim for old browsers not supporting FormData * @author Danial <danial.farid@gmail.com> * @version 10.1.9 */ (function () { /** @namespace FileAPI.noContentTimeout */ function patchXHR(fnName, newFn) { window.XMLHttpRequest.prototype[fnName] = newFn(window.XMLHttpRequest.prototype[fnName]); } function redefineProp(xhr, prop, fn) { try { Object.defineProperty(xhr, prop, {get: fn}); } catch (e) {/*ignore*/ } } if (!window.FileAPI) { window.FileAPI = {}; } if (!window.XMLHttpRequest) { throw 'AJAX is not supported. XMLHttpRequest is not defined.'; } FileAPI.shouldLoad = !window.FormData || FileAPI.forceLoad; if (FileAPI.shouldLoad) { var initializeUploadListener = function (xhr) { if (!xhr.__listeners) { if (!xhr.upload) xhr.upload = {}; xhr.__listeners = []; var origAddEventListener = xhr.upload.addEventListener; xhr.upload.addEventListener = function (t, fn) { xhr.__listeners[t] = fn; if (origAddEventListener) origAddEventListener.apply(this, arguments); }; } }; patchXHR('open', function (orig) { return function (m, url, b) { initializeUploadListener(this); this.__url = url; try { orig.apply(this, [m, url, b]); } catch (e) { if (e.message.indexOf('Access is denied') > -1) { this.__origError = e; orig.apply(this, [m, '_fix_for_ie_crossdomain__', b]); } } }; }); patchXHR('getResponseHeader', function (orig) { return function (h) { return this.__fileApiXHR && this.__fileApiXHR.getResponseHeader ? this.__fileApiXHR.getResponseHeader(h) : (orig == null ? null : orig.apply(this, [h])); }; }); patchXHR('getAllResponseHeaders', function (orig) { return function () { return this.__fileApiXHR && this.__fileApiXHR.getAllResponseHeaders ? this.__fileApiXHR.getAllResponseHeaders() : (orig == null ? null : orig.apply(this)); }; }); patchXHR('abort', function (orig) { return function () { return this.__fileApiXHR && this.__fileApiXHR.abort ? this.__fileApiXHR.abort() : (orig == null ? null : orig.apply(this)); }; }); patchXHR('setRequestHeader', function (orig) { return function (header, value) { if (header === '__setXHR_') { initializeUploadListener(this); var val = value(this); // fix for angular < 1.2.0 if (val instanceof Function) { val(this); } } else { this.__requestHeaders = this.__requestHeaders || {}; this.__requestHeaders[header] = value; orig.apply(this, arguments); } }; }); patchXHR('send', function (orig) { return function () { var xhr = this; if (arguments[0] && arguments[0].__isFileAPIShim) { var formData = arguments[0]; var config = { url: xhr.__url, jsonp: false, //removes the callback form param cache: true, //removes the ?fileapiXXX in the url complete: function (err, fileApiXHR) { if (err && angular.isString(err) && err.indexOf('#2174') !== -1) { // this error seems to be fine the file is being uploaded properly. err = null; } xhr.__completed = true; if (!err && xhr.__listeners.load) xhr.__listeners.load({ type: 'load', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true }); if (!err && xhr.__listeners.loadend) xhr.__listeners.loadend({ type: 'loadend', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true }); if (err === 'abort' && xhr.__listeners.abort) xhr.__listeners.abort({ type: 'abort', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true }); if (fileApiXHR.status !== undefined) redefineProp(xhr, 'status', function () { return (fileApiXHR.status === 0 && err && err !== 'abort') ? 500 : fileApiXHR.status; }); if (fileApiXHR.statusText !== undefined) redefineProp(xhr, 'statusText', function () { return fileApiXHR.statusText; }); redefineProp(xhr, 'readyState', function () { return 4; }); if (fileApiXHR.response !== undefined) redefineProp(xhr, 'response', function () { return fileApiXHR.response; }); var resp = fileApiXHR.responseText || (err && fileApiXHR.status === 0 && err !== 'abort' ? err : undefined); redefineProp(xhr, 'responseText', function () { return resp; }); redefineProp(xhr, 'response', function () { return resp; }); if (err) redefineProp(xhr, 'err', function () { return err; }); xhr.__fileApiXHR = fileApiXHR; if (xhr.onreadystatechange) xhr.onreadystatechange(); if (xhr.onload) xhr.onload(); }, progress: function (e) { e.target = xhr; if (xhr.__listeners.progress) xhr.__listeners.progress(e); xhr.__total = e.total; xhr.__loaded = e.loaded; if (e.total === e.loaded) { // fix flash issue that doesn't call complete if there is no response text from the server var _this = this; setTimeout(function () { if (!xhr.__completed) { xhr.getAllResponseHeaders = function () { }; _this.complete(null, {status: 204, statusText: 'No Content'}); } }, FileAPI.noContentTimeout || 10000); } }, headers: xhr.__requestHeaders }; config.data = {}; config.files = {}; for (var i = 0; i < formData.data.length; i++) { var item = formData.data[i]; if (item.val != null && item.val.name != null && item.val.size != null && item.val.type != null) { config.files[item.key] = item.val; } else { config.data[item.key] = item.val; } } setTimeout(function () { if (!FileAPI.hasFlash) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } xhr.__fileApiXHR = FileAPI.upload(config); }, 1); } else { if (this.__origError) { throw this.__origError; } orig.apply(xhr, arguments); } }; }); window.XMLHttpRequest.__isFileAPIShim = true; window.FormData = FormData = function () { return { append: function (key, val, name) { if (val.__isFileAPIBlobShim) { val = val.data[0]; } this.data.push({ key: key, val: val, name: name }); }, data: [], __isFileAPIShim: true }; }; window.Blob = Blob = function (b) { return { data: b, __isFileAPIBlobShim: true }; }; } })(); (function () { /** @namespace FileAPI.forceLoad */ /** @namespace window.FileAPI.jsUrl */ /** @namespace window.FileAPI.jsPath */ function isInputTypeFile(elem) { return elem[0].tagName.toLowerCase() === 'input' && elem.attr('type') && elem.attr('type').toLowerCase() === 'file'; } function hasFlash() { try { var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash'); if (fo) return true; } catch (e) { if (navigator.mimeTypes['application/x-shockwave-flash'] !== undefined) return true; } return false; } function getOffset(obj) { var left = 0, top = 0; if (window.jQuery) { return jQuery(obj).offset(); } if (obj.offsetParent) { do { left += (obj.offsetLeft - obj.scrollLeft); top += (obj.offsetTop - obj.scrollTop); obj = obj.offsetParent; } while (obj); } return { left: left, top: top }; } if (FileAPI.shouldLoad) { FileAPI.hasFlash = hasFlash(); //load FileAPI if (FileAPI.forceLoad) { FileAPI.html5 = false; } if (!FileAPI.upload) { var jsUrl, basePath, script = document.createElement('script'), allScripts = document.getElementsByTagName('script'), i, index, src; if (window.FileAPI.jsUrl) { jsUrl = window.FileAPI.jsUrl; } else if (window.FileAPI.jsPath) { basePath = window.FileAPI.jsPath; } else { for (i = 0; i < allScripts.length; i++) { src = allScripts[i].src; index = src.search(/\/ng\-file\-upload[\-a-zA-z0-9\.]*\.js/); if (index > -1) { basePath = src.substring(0, index + 1); break; } } } if (FileAPI.staticPath == null) FileAPI.staticPath = basePath; script.setAttribute('src', jsUrl || basePath + 'FileAPI.js'); document.getElementsByTagName('head')[0].appendChild(script); } FileAPI.ngfFixIE = function (elem, fileElem, changeFn) { if (!hasFlash()) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } var fixInputStyle = function () { if (elem.attr('disabled')) { if (fileElem) fileElem.removeClass('js-fileapi-wrapper'); } else { if (!fileElem.attr('__ngf_flash_')) { fileElem.unbind('change'); fileElem.unbind('click'); fileElem.bind('change', function (evt) { fileApiChangeFn.apply(this, [evt]); changeFn.apply(this, [evt]); }); fileElem.attr('__ngf_flash_', 'true'); } fileElem.addClass('js-fileapi-wrapper'); if (!isInputTypeFile(elem)) { fileElem.css('position', 'absolute') .css('top', getOffset(elem[0]).top + 'px').css('left', getOffset(elem[0]).left + 'px') .css('width', elem[0].offsetWidth + 'px').css('height', elem[0].offsetHeight + 'px') .css('filter', 'alpha(opacity=0)').css('display', elem.css('display')) .css('overflow', 'hidden').css('z-index', '900000') .css('visibility', 'visible'); } } }; elem.bind('mouseenter', fixInputStyle); var fileApiChangeFn = function (evt) { var files = FileAPI.getFiles(evt); //just a double check for #233 for (var i = 0; i < files.length; i++) { if (files[i].size === undefined) files[i].size = 0; if (files[i].name === undefined) files[i].name = 'file'; if (files[i].type === undefined) files[i].type = 'undefined'; } if (!evt.target) { evt.target = {}; } evt.target.files = files; // if evt.target.files is not writable use helper field if (evt.target.files !== files) { evt.__files_ = files; } (evt.__files_ || evt.target.files).item = function (i) { return (evt.__files_ || evt.target.files)[i] || null; }; }; }; FileAPI.disableFileInput = function (elem, disable) { if (disable) { elem.removeClass('js-fileapi-wrapper'); } else { elem.addClass('js-fileapi-wrapper'); } }; } })(); if (!window.FileReader) { window.FileReader = function () { var _this = this, loadStarted = false; this.listeners = {}; this.addEventListener = function (type, fn) { _this.listeners[type] = _this.listeners[type] || []; _this.listeners[type].push(fn); }; this.removeEventListener = function (type, fn) { if (_this.listeners[type]) _this.listeners[type].splice(_this.listeners[type].indexOf(fn), 1); }; this.dispatchEvent = function (evt) { var list = _this.listeners[evt.type]; if (list) { for (var i = 0; i < list.length; i++) { list[i].call(_this, evt); } } }; this.onabort = this.onerror = this.onload = this.onloadstart = this.onloadend = this.onprogress = null; var constructEvent = function (type, evt) { var e = {type: type, target: _this, loaded: evt.loaded, total: evt.total, error: evt.error}; if (evt.result != null) e.target.result = evt.result; return e; }; var listener = function (evt) { if (!loadStarted) { loadStarted = true; if (_this.onloadstart) _this.onloadstart(constructEvent('loadstart', evt)); } var e; if (evt.type === 'load') { if (_this.onloadend) _this.onloadend(constructEvent('loadend', evt)); e = constructEvent('load', evt); if (_this.onload) _this.onload(e); _this.dispatchEvent(e); } else if (evt.type === 'progress') { e = constructEvent('progress', evt); if (_this.onprogress) _this.onprogress(e); _this.dispatchEvent(e); } else { e = constructEvent('error', evt); if (_this.onerror) _this.onerror(e); _this.dispatchEvent(e); } }; this.readAsDataURL = function (file) { FileAPI.readAsDataURL(file, listener); }; this.readAsText = function (file) { FileAPI.readAsText(file, listener); }; }; } /**! * AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort, * progress, resize, thumbnail, preview, validation and CORS * @author Danial <danial.farid@gmail.com> * @version 10.1.9 */ if (window.XMLHttpRequest && !(window.FileAPI && FileAPI.shouldLoad)) { window.XMLHttpRequest.prototype.setRequestHeader = (function (orig) { return function (header, value) { if (header === '__setXHR_') { var val = value(this); // fix for angular < 1.2.0 if (val instanceof Function) { val(this); } } else { orig.apply(this, arguments); } }; })(window.XMLHttpRequest.prototype.setRequestHeader); } var ngFileUpload = angular.module('ngFileUpload', []); ngFileUpload.version = '10.1.9'; ngFileUpload.service('UploadBase', ['$http', '$q', '$timeout', function ($http, $q, $timeout) { var upload = this; this.isResumeSupported = function () { return window.Blob && (window.Blob instanceof Function) && new window.Blob().slice; }; var resumeSupported = this.isResumeSupported(); function sendHttp(config) { config.method = config.method || 'POST'; config.headers = config.headers || {}; var deferred = config._deferred = config._deferred || $q.defer(); var promise = deferred.promise; function notifyProgress(e) { if (deferred.notify) { deferred.notify(e); } if (promise.progressFunc) { $timeout(function () { promise.progressFunc(e); }); } } function getNotifyEvent(n) { if (config._start != null && resumeSupported) { return { loaded: n.loaded + config._start, total: config._file.size, type: n.type, config: config, lengthComputable: true, target: n.target }; } else { return n; } } if (!config.disableProgress) { config.headers.__setXHR_ = function () { return function (xhr) { if (!xhr || !(xhr instanceof XMLHttpRequest)) return; config.__XHR = xhr; if (config.xhrFn) config.xhrFn(xhr); xhr.upload.addEventListener('progress', function (e) { e.config = config; notifyProgress(getNotifyEvent(e)); }, false); //fix for firefox not firing upload progress end, also IE8-9 xhr.upload.addEventListener('load', function (e) { if (e.lengthComputable) { e.config = config; notifyProgress(getNotifyEvent(e)); } }, false); }; }; } function uploadWithAngular() { $http(config).then(function (r) { if (resumeSupported && config._chunkSize && !config._finished) { notifyProgress({loaded: config._end, total: config._file.size, config: config, type: 'progress'}); upload.upload(config, true); } else { if (config._finished) delete config._finished; deferred.resolve(r); } }, function (e) { deferred.reject(e); }, function (n) { deferred.notify(n); }); } if (!resumeSupported) { uploadWithAngular(); } else if (config._chunkSize && config._end && !config._finished) { config._start = config._end; config._end += config._chunkSize; uploadWithAngular(); } else if (config.resumeSizeUrl) { $http.get(config.resumeSizeUrl).then(function (resp) { if (config.resumeSizeResponseReader) { config._start = config.resumeSizeResponseReader(resp.data); } else { config._start = parseInt((resp.data.size == null ? resp.data : resp.data.size).toString()); } if (config._chunkSize) { config._end = config._start + config._chunkSize; } uploadWithAngular(); }, function (e) { throw e; }); } else if (config.resumeSize) { config.resumeSize().then(function (size) { config._start = size; uploadWithAngular(); }, function (e) { throw e; }); } else { uploadWithAngular(); } promise.success = function (fn) { promise.then(function (response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.error = function (fn) { promise.then(null, function (response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.progress = function (fn) { promise.progressFunc = fn; promise.then(null, null, function (n) { fn(n); }); return promise; }; promise.abort = promise.pause = function () { if (config.__XHR) { $timeout(function () { config.__XHR.abort(); }); } return promise; }; promise.xhr = function (fn) { config.xhrFn = (function (origXhrFn) { return function () { if (origXhrFn) origXhrFn.apply(promise, arguments); fn.apply(promise, arguments); }; })(config.xhrFn); return promise; }; return promise; } this.rename = function (file, name) { file.ngfName = name; return file; }; this.jsonBlob = function (val) { if (val != null && !angular.isString(val)) { val = JSON.stringify(val); } var blob = new window.Blob([val], {type: 'application/json'}); blob._ngfBlob = true; return blob; }; this.json = function (val) { return angular.toJson(val); }; function copy(obj) { var clone = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { clone[key] = obj[key]; } } return clone; } this.upload = function (config, internal) { function isFile(file) { return file != null && (file instanceof window.Blob || (file.flashId && file.name && file.size)); } function toResumeFile(file, formData) { if (file._ngfBlob) return file; config._file = config._file || file; if (config._start != null && resumeSupported) { if (config._end && config._end >= file.size) { config._finished = true; config._end = file.size; } var slice = file.slice(config._start, config._end || file.size); slice.name = file.name; slice.ngfName = file.ngfName; if (config._chunkSize) { formData.append('_chunkSize', config._end - config._start); formData.append('_chunkNumber', Math.floor(config._start / config._chunkSize)); formData.append('_totalSize', config._file.size); } return slice; } return file; } function addFieldToFormData(formData, val, key) { if (val !== undefined) { if (angular.isDate(val)) { val = val.toISOString(); } if (angular.isString(val)) { formData.append(key, val); } else if (isFile(val)) { var file = toResumeFile(val, formData); var split = key.split(','); if (split[1]) { file.ngfName = split[1].replace(/^\s+|\s+$/g, ''); key = split[0]; } config._fileKey = config._fileKey || key; formData.append(key, file, file.ngfName || file.name); } else { if (angular.isObject(val)) { if (val.$$ngfCircularDetection) throw 'ngFileUpload: Circular reference in config.data. Make sure specified data for Upload.upload() has no circular reference: ' + key; val.$$ngfCircularDetection = true; try { for (var k in val) { if (val.hasOwnProperty(k) && k !== '$$ngfCircularDetection') { var objectKey = config.objectKey == null ? '[i]' : config.objectKey; if (val.length && parseInt(k) > -1) { objectKey = config.arrayKey == null ? objectKey : config.arrayKey; } addFieldToFormData(formData, val[k], key + objectKey.replace(/[ik]/g, k)); } } } finally { delete val.$$ngfCircularDetection; } } else { formData.append(key, val); } } } } function digestConfig() { config._chunkSize = upload.translateScalars(config.resumeChunkSize); config._chunkSize = config._chunkSize ? parseInt(config._chunkSize.toString()) : null; config.headers = config.headers || {}; config.headers['Content-Type'] = undefined; config.transformRequest = config.transformRequest ? (angular.isArray(config.transformRequest) ? config.transformRequest : [config.transformRequest]) : []; config.transformRequest.push(function (data) { var formData = new window.FormData(), key; data = data || config.fields || {}; if (config.file) { data.file = config.file; } for (key in data) { if (data.hasOwnProperty(key)) { var val = data[key]; if (config.formDataAppender) { config.formDataAppender(formData, key, val); } else { addFieldToFormData(formData, val, key); } } } return formData; }); } if (!internal) config = copy(config); if (!config._isDigested) { config._isDigested = true; digestConfig(); } return sendHttp(config); }; this.http = function (config) { config = copy(config); config.transformRequest = config.transformRequest || function (data) { if ((window.ArrayBuffer && data instanceof window.ArrayBuffer) || data instanceof window.Blob) { return data; } return $http.defaults.transformRequest[0].apply(this, arguments); }; config._chunkSize = upload.translateScalars(config.resumeChunkSize); config._chunkSize = config._chunkSize ? parseInt(config._chunkSize.toString()) : null; return sendHttp(config); }; this.translateScalars = function (str) { if (angular.isString(str)) { if (str.search(/kb/i) === str.length - 2) { return parseFloat(str.substring(0, str.length - 2) * 1000); } else if (str.search(/mb/i) === str.length - 2) { return parseFloat(str.substring(0, str.length - 2) * 1000000); } else if (str.search(/gb/i) === str.length - 2) { return parseFloat(str.substring(0, str.length - 2) * 1000000000); } else if (str.search(/b/i) === str.length - 1) { return parseFloat(str.substring(0, str.length - 1)); } else if (str.search(/s/i) === str.length - 1) { return parseFloat(str.substring(0, str.length - 1)); } else if (str.search(/m/i) === str.length - 1) { return parseFloat(str.substring(0, str.length - 1) * 60); } else if (str.search(/h/i) === str.length - 1) { return parseFloat(str.substring(0, str.length - 1) * 3600); } } return str; }; this.setDefaults = function (defaults) { this.defaults = defaults || {}; }; this.defaults = {}; this.version = ngFileUpload.version; } ]); ngFileUpload.service('Upload', ['$parse', '$timeout', '$compile', '$q', 'UploadExif', function ($parse, $timeout, $compile, $q, UploadExif) { var upload = UploadExif; upload.getAttrWithDefaults = function (attr, name) { if (attr[name] != null) return attr[name]; var def = upload.defaults[name]; return (def == null ? def : (angular.isString(def) ? def : JSON.stringify(def))); }; upload.attrGetter = function (name, attr, scope, params) { var attrVal = this.getAttrWithDefaults(attr, name); if (scope) { try { if (params) { return $parse(attrVal)(scope, params); } else { return $parse(attrVal)(scope); } } catch (e) { // hangle string value without single qoute if (name.search(/min|max|pattern/i)) { return attrVal; } else { throw e; } } } else { return attrVal; } }; upload.shouldUpdateOn = function (type, attr, scope) { var modelOptions = upload.attrGetter('ngModelOptions', attr, scope); if (modelOptions && modelOptions.updateOn) { return modelOptions.updateOn.split(' ').indexOf(type) > -1; } return true; }; upload.emptyPromise = function () { var d = $q.defer(); var args = arguments; $timeout(function () { d.resolve.apply(d, args); }); return d.promise; }; upload.happyPromise = function (promise, data) { var d = $q.defer(); promise.then(function (result) { d.resolve(result); }, function (error) { $timeout(function () { throw error; }); d.resolve(data); }); return d.promise; }; function applyExifRotations(files, attr, scope) { var promises = [upload.emptyPromise()]; angular.forEach(files, function (f, i) { if (f.type.indexOf('image/jpeg') === 0 && upload.attrGetter('ngfFixOrientation', attr, scope, {$file: f})) { promises.push(upload.happyPromise(upload.applyExifRotation(f), f).then(function (fixedFile) { files.splice(i, 1, fixedFile); })); } }); return $q.all(promises); } function resize(files, attr, scope) { var param = upload.attrGetter('ngfResize', attr, scope); if (!param || !upload.isResizeSupported() || !files.length) return upload.emptyPromise(); var promises = [upload.emptyPromise()]; angular.forEach(files, function (f, i) { if (f.type.indexOf('image') === 0) { if (param.pattern && !upload.validatePattern(f, param.pattern)) return; var promise = upload.resize(f, param.width, param.height, param.quality, param.type, param.ratio, param.centerCrop); promises.push(promise); promise.then(function (resizedFile) { files.splice(i, 1, resizedFile); }, function (e) { f.$error = 'resize'; f.$errorParam = (e ? (e.message ? e.message : e) + ': ' : '') + (f && f.name); }); } }); return $q.all(promises); } function handleKeep(files, prevFiles, attr, scope) { var dupFiles = []; var keep = upload.attrGetter('ngfKeep', attr, scope); if (keep) { var hasNew = false; if (keep === 'distinct' || upload.attrGetter('ngfKeepDistinct', attr, scope) === true) { var len = prevFiles.length; if (files) { for (var i = 0; i < files.length; i++) { for (var j = 0; j < len; j++) { if (files[i].name === prevFiles[j].name) { dupFiles.push(files[i]); break; } } if (j === len) { prevFiles.push(files[i]); hasNew = true; } } } files = prevFiles; } else { files = prevFiles.concat(files || []); } } return {files: files, dupFiles: dupFiles, keep: keep}; } upload.updateModel = function (ngModel, attr, scope, fileChange, files, evt, noDelay) { function update(files, invalidFiles, newFiles, dupFiles, isSingleModel) { var file = files && files.length ? files[0] : null; if (ngModel) { upload.applyModelValidation(ngModel, files); ngModel.$ngfModelChange = true; ngModel.$setViewValue(isSingleModel ? file : files); } if (fileChange) { $parse(fileChange)(scope, { $files: files, $file: file, $newFiles: newFiles, $duplicateFiles: dupFiles, $invalidFiles: invalidFiles, $event: evt }); } var invalidModel = upload.attrGetter('ngfModelInvalid', attr); if (invalidModel) { $timeout(function () { $parse(invalidModel).assign(scope, invalidFiles); }); } $timeout(function () { // scope apply changes }); } var newFiles = files; var prevFiles = ngModel && ngModel.$modelValue && (angular.isArray(ngModel.$modelValue) ? ngModel.$modelValue : [ngModel.$modelValue]); prevFiles = (prevFiles || attr.$$ngfPrevFiles || []).slice(0); var keepResult = handleKeep(files, prevFiles, attr, scope); files = keepResult.files; var dupFiles = keepResult.dupFiles; var isSingleModel = !upload.attrGetter('ngfMultiple', attr, scope) && !upload.attrGetter('multiple', attr) && !keepResult.keep; attr.$$ngfPrevFiles = files; if (keepResult.keep && (!newFiles || !newFiles.length)) return; upload.attrGetter('ngfBeforeModelChange', attr, scope, {$files: files, $file: files && files.length ? files[0] : null, $duplicateFiles: dupFiles, $event: evt}); upload.validate(newFiles, ngModel, attr, scope).then(function () { if (noDelay) { update(files, [], newFiles, dupFiles, isSingleModel); } else { var options = upload.attrGetter('ngModelOptions', attr, scope); if (!options || !options.allowInvalid) { var valids = [], invalids = []; angular.forEach(files, function (file) { if (file.$error) { invalids.push(file); } else { valids.push(file); } }); files = valids; } var fixOrientation = upload.emptyPromise(files); if (upload.attrGetter('ngfFixOrientation', attr, scope) && upload.isExifSupported()) { fixOrientation = applyExifRotations(files, attr, scope); } fixOrientation.then(function () { resize(files, attr, scope).then(function () { $timeout(function () { update(files, invalids, newFiles, dupFiles, isSingleModel); }, options && options.debounce ? options.debounce.change || options.debounce : 0); }, function (e) { throw 'Could not resize files ' + e; }); }); } }); // cleaning object url memories var l = prevFiles.length; while (l--) { var prevFile = prevFiles[l]; if (window.URL && prevFile.blobUrl) { URL.revokeObjectURL(prevFile.blobUrl); delete prevFile.blobUrl; } } }; return upload; }]); ngFileUpload.directive('ngfSelect', ['$parse', '$timeout', '$compile', 'Upload', function ($parse, $timeout, $compile, Upload) { var generatedElems = []; function isDelayedClickSupported(ua) { // fix for android native browser < 4.4 and safari windows var m = ua.match(/Android[^\d]*(\d+)\.(\d+)/); if (m && m.length > 2) { var v = Upload.defaults.androidFixMinorVersion || 4; return parseInt(m[1]) < 4 || (parseInt(m[1]) === v && parseInt(m[2]) < v); } // safari on windows return ua.indexOf('Chrome') === -1 && /.*Windows.*Safari.*/.test(ua); } function linkFileSelect(scope, elem, attr, ngModel, $parse, $timeout, $compile, upload) { /** @namespace attr.ngfSelect */ /** @namespace attr.ngfChange */ /** @namespace attr.ngModel */ /** @namespace attr.ngModelOptions */ /** @namespace attr.ngfMultiple */ /** @namespace attr.ngfCapture */ /** @namespace attr.ngfValidate */ /** @namespace attr.ngfKeep */ var attrGetter = function (name, scope) { return upload.attrGetter(name, attr, scope); }; function isInputTypeFile() { return elem[0].tagName.toLowerCase() === 'input' && attr.type && attr.type.toLowerCase() === 'file'; } function fileChangeAttr() { return attrGetter('ngfChange') || attrGetter('ngfSelect'); } function changeFn(evt) { if (upload.shouldUpdateOn('change', attr, scope)) { var fileList = evt.__files_ || (evt.target && evt.target.files), files = []; for (var i = 0; i < fileList.length; i++) { files.push(fileList[i]); } upload.updateModel(ngModel, attr, scope, fileChangeAttr(), files.length ? files : null, evt); } } upload.registerModelChangeValidator(ngModel, attr, scope); var unwatches = []; unwatches.push(scope.$watch(attrGetter('ngfMultiple'), function () { fileElem.attr('multiple', attrGetter('ngfMultiple', scope)); })); unwatches.push(scope.$watch(attrGetter('ngfCapture'), function () { fileElem.attr('capture', attrGetter('ngfCapture', scope)); })); unwatches.push(scope.$watch(attrGetter('ngfAccept'), function () { fileElem.attr('accept', attrGetter('ngfAccept', scope)); })); attr.$observe('accept', function () { fileElem.attr('accept', attrGetter('accept')); }); unwatches.push(function () { if (attr.$$observers) delete attr.$$observers.accept; }); function bindAttrToFileInput(fileElem) { if (elem !== fileElem) { for (var i = 0; i < elem[0].attributes.length; i++) { var attribute = elem[0].attributes[i]; if (attribute.name !== 'type' && attribute.name !== 'class' && attribute.name !== 'style') { if (attribute.value == null || attribute.value === '') { if (attribute.name === 'required') attribute.value = 'required'; if (attribute.name === 'multiple') attribute.value = 'multiple'; } fileElem.attr(attribute.name, attribute.name === 'id' ? 'ngf-' + attribute.value : attribute.value); } } } } function createFileInput() { if (isInputTypeFile()) { return elem; } var fileElem = angular.element('<input type="file">'); bindAttrToFileInput(fileElem); var label = angular.element('<label>upload</label>'); label.css('visibility', 'hidden').css('position', 'absolute').css('overflow', 'hidden') .css('width', '0px').css('height', '0px').css('border', 'none') .css('margin', '0px').css('padding', '0px').attr('tabindex', '-1'); generatedElems.push({el: elem, ref: label}); document.body.appendChild(label.append(fileElem)[0]); return fileElem; } var initialTouchStartY = 0; function clickHandler(evt) { if (elem.attr('disabled') || attrGetter('ngfSelectDisabled', scope)) return false; var r = handleTouch(evt); if (r != null) return r; resetModel(evt); // fix for md when the element is removed from the DOM and added back #460 try { if (!isInputTypeFile() && !document.body.contains(fileElem[0])) { generatedElems.push({el: elem, ref: fileElem.parent()}); document.body.appendChild(fileElem[0].parent()); fileElem.bind('change', changeFn); } } catch(e){/*ignore*/} if (isDelayedClickSupported(navigator.userAgent)) { setTimeout(function () { fileElem[0].click(); }, 0); } else { fileElem[0].click(); } return false; } function handleTouch(evt) { var touches = evt.changedTouches || (evt.originalEvent && evt.originalEvent.changedTouches); if (evt.type === 'touchstart') { initialTouchStartY = touches ? touches[0].clientY : 0; return true; // don't block event default } else { evt.stopPropagation(); evt.preventDefault(); // prevent scroll from triggering event if (evt.type === 'touchend') { var currentLocation = touches ? touches[0].clientY : 0; if (Math.abs(currentLocation - initialTouchStartY) > 20) return false; } } } var fileElem = elem; function resetModel(evt) { if (upload.shouldUpdateOn('click', attr, scope) && fileElem.val()) { fileElem.val(null); upload.updateModel(ngModel, attr, scope, fileChangeAttr(), null, evt, true); } } if (!isInputTypeFile()) { fileElem = createFileInput(); } fileElem.bind('change', changeFn); if (!isInputTypeFile()) { elem.bind('click touchstart touchend', clickHandler); } else { elem.bind('click', resetModel); } function ie10SameFileSelectFix(evt) { if (fileElem && !fileElem.attr('__ngf_ie10_Fix_')) { if (!fileElem[0].parentNode) { fileElem = null; return; } evt.preventDefault(); evt.stopPropagation(); fileElem.unbind('click'); var clone = fileElem.clone(); fileElem.replaceWith(clone); fileElem = clone; fileElem.attr('__ngf_ie10_Fix_', 'true'); fileElem.bind('change', changeFn); fileElem.bind('click', ie10SameFileSelectFix); fileElem[0].click(); return false; } else { fileElem.removeAttr('__ngf_ie10_Fix_'); } } if (navigator.appVersion.indexOf('MSIE 10') !== -1) { fileElem.bind('click', ie10SameFileSelectFix); } if (ngModel) ngModel.$formatters.push(function (val) { if (val == null || val.length === 0) { if (fileElem.val()) { fileElem.val(null); } } return val; }); scope.$on('$destroy', function () { if (!isInputTypeFile()) fileElem.parent().remove(); angular.forEach(unwatches, function (unwatch) { unwatch(); }); }); $timeout(function () { for (var i = 0; i < generatedElems.length; i++) { var g = generatedElems[i]; if (!document.body.contains(g.el[0])) { generatedElems.splice(i, 1); g.ref.remove(); } } }); if (window.FileAPI && window.FileAPI.ngfFixIE) { window.FileAPI.ngfFixIE(elem, fileElem, changeFn); } } return { restrict: 'AEC', require: '?ngModel', link: function (scope, elem, attr, ngModel) { linkFileSelect(scope, elem, attr, ngModel, $parse, $timeout, $compile, Upload); } }; }]); (function () { ngFileUpload.service('UploadDataUrl', ['UploadBase', '$timeout', '$q', function (UploadBase, $timeout, $q) { var upload = UploadBase; upload.base64DataUrl = function (file) { if (angular.isArray(file)) { var d = $q.defer(), count = 0; angular.forEach(file, function (f) { upload.dataUrl(f, true)['finally'](function () { count++; if (count === file.length) { var urls = []; angular.forEach(file, function (ff) { urls.push(ff.$ngfDataUrl); }); d.resolve(urls, file); } }); }); return d.promise; } else { return upload.dataUrl(file, true); } }; upload.dataUrl = function (file, disallowObjectUrl) { if (!file) return upload.emptyPromise(file, file); if ((disallowObjectUrl && file.$ngfDataUrl != null) || (!disallowObjectUrl && file.$ngfBlobUrl != null)) { return upload.emptyPromise(disallowObjectUrl ? file.$ngfDataUrl : file.$ngfBlobUrl, file); } var p = disallowObjectUrl ? file.$$ngfDataUrlPromise : file.$$ngfBlobUrlPromise; if (p) return p; var deferred = $q.defer(); $timeout(function () { if (window.FileReader && file && (!window.FileAPI || navigator.userAgent.indexOf('MSIE 8') === -1 || file.size < 20000) && (!window.FileAPI || navigator.userAgent.indexOf('MSIE 9') === -1 || file.size < 4000000)) { //prefer URL.createObjectURL for handling refrences to files of all sizes //since it doesn´t build a large string in memory var URL = window.URL || window.webkitURL; if (URL && URL.createObjectURL && !disallowObjectUrl) { var url; try { url = URL.createObjectURL(file); } catch (e) { $timeout(function () { file.$ngfBlobUrl = ''; deferred.reject(); }); return; } $timeout(function () { file.$ngfBlobUrl = url; if (url) deferred.resolve(url, file); }); } else { var fileReader = new FileReader(); fileReader.onload = function (e) { $timeout(function () { file.$ngfDataUrl = e.target.result; deferred.resolve(e.target.result, file); }); }; fileReader.onerror = function () { $timeout(function () { file.$ngfDataUrl = ''; deferred.reject(); }); }; fileReader.readAsDataURL(file); } } else { $timeout(function () { file[disallowObjectUrl ? 'dataUrl' : 'blobUrl'] = ''; deferred.reject(); }); } }); if (disallowObjectUrl) { p = file.$$ngfDataUrlPromise = deferred.promise; } else { p = file.$$ngfBlobUrlPromise = deferred.promise; } p['finally'](function () { delete file[disallowObjectUrl ? '$$ngfDataUrlPromise' : '$$ngfBlobUrlPromise']; }); return p; }; return upload; }]); function getTagType(el) { if (el.tagName.toLowerCase() === 'img') return 'image'; if (el.tagName.toLowerCase() === 'audio') return 'audio'; if (el.tagName.toLowerCase() === 'video') return 'video'; return /./; } function linkFileDirective(Upload, $timeout, scope, elem, attr, directiveName, resizeParams, isBackground) { function constructDataUrl(file) { var disallowObjectUrl = Upload.attrGetter('ngfNoObjectUrl', attr, scope); Upload.dataUrl(file, disallowObjectUrl)['finally'](function () { $timeout(function () { var src = (disallowObjectUrl ? file.$ngfDataUrl : file.$ngfBlobUrl) || file.$ngfDataUrl; if (isBackground) { elem.css('background-image', 'url(\'' + (src || '') + '\')'); } else { elem.attr('src', src); } if (src) { elem.removeClass('ng-hide'); } else { elem.addClass('ng-hide'); } }); }); } $timeout(function () { var unwatch = scope.$watch(attr[directiveName], function (file) { var size = resizeParams; if (directiveName === 'ngfThumbnail') { if (!size) { size = {width: elem[0].clientWidth, height: elem[0].clientHeight}; } if (size.width === 0 && window.getComputedStyle) { var style = getComputedStyle(elem[0]); size = { width: parseInt(style.width.slice(0, -2)), height: parseInt(style.height.slice(0, -2)) }; } } if (angular.isString(file)) { elem.removeClass('ng-hide'); if (isBackground) { return elem.css('background-image', 'url(\'' + file + '\')'); } else { return elem.attr('src', file); } } if (file && file.type && file.type.search(getTagType(elem[0])) === 0 && (!isBackground || file.type.indexOf('image') === 0)) { if (size && Upload.isResizeSupported()) { Upload.resize(file, size.width, size.height, size.quality).then( function (f) { constructDataUrl(f); }, function (e) { throw e; } ); } else { constructDataUrl(file); } } else { elem.addClass('ng-hide'); } }); scope.$on('$destroy', function () { unwatch(); }); }); } /** @namespace attr.ngfSrc */ /** @namespace attr.ngfNoObjectUrl */ ngFileUpload.directive('ngfSrc', ['Upload', '$timeout', function (Upload, $timeout) { return { restrict: 'AE', link: function (scope, elem, attr) { linkFileDirective(Upload, $timeout, scope, elem, attr, 'ngfSrc', Upload.attrGetter('ngfResize', attr, scope), false); } }; }]); /** @namespace attr.ngfBackground */ /** @namespace attr.ngfNoObjectUrl */ ngFileUpload.directive('ngfBackground', ['Upload', '$timeout', function (Upload, $timeout) { return { restrict: 'AE', link: function (scope, elem, attr) { linkFileDirective(Upload, $timeout, scope, elem, attr, 'ngfBackground', Upload.attrGetter('ngfResize', attr, scope), true); } }; }]); /** @namespace attr.ngfThumbnail */ /** @namespace attr.ngfAsBackground */ /** @namespace attr.ngfSize */ /** @namespace attr.ngfNoObjectUrl */ ngFileUpload.directive('ngfThumbnail', ['Upload', '$timeout', function (Upload, $timeout) { return { restrict: 'AE', link: function (scope, elem, attr) { var size = Upload.attrGetter('ngfSize', attr, scope); linkFileDirective(Upload, $timeout, scope, elem, attr, 'ngfThumbnail', size, Upload.attrGetter('ngfAsBackground', attr, scope)); } }; }]); ngFileUpload.config(['$compileProvider', function ($compileProvider) { if ($compileProvider.imgSrcSanitizationWhitelist) $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|local|file|data|blob):/); if ($compileProvider.aHrefSanitizationWhitelist) $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|local|file|data|blob):/); }]); ngFileUpload.filter('ngfDataUrl', ['UploadDataUrl', '$sce', function (UploadDataUrl, $sce) { return function (file, disallowObjectUrl, trustedUrl) { if (angular.isString(file)) { return $sce.trustAsResourceUrl(file); } var src = file && ((disallowObjectUrl ? file.$ngfDataUrl : file.$ngfBlobUrl) || file.$ngfDataUrl); if (file && !src) { if (!file.$ngfDataUrlFilterInProgress && angular.isObject(file)) { file.$ngfDataUrlFilterInProgress = true; UploadDataUrl.dataUrl(file, disallowObjectUrl); } return ''; } if (file) delete file.$ngfDataUrlFilterInProgress; return (file && src ? (trustedUrl ? $sce.trustAsResourceUrl(src) : src) : file) || ''; }; }]); })(); ngFileUpload.service('UploadValidate', ['UploadDataUrl', '$q', '$timeout', function (UploadDataUrl, $q, $timeout) { var upload = UploadDataUrl; function globStringToRegex(str) { var regexp = '', excludes = []; if (str.length > 2 && str[0] === '/' && str[str.length - 1] === '/') { regexp = str.substring(1, str.length - 1); } else { var split = str.split(','); if (split.length > 1) { for (var i = 0; i < split.length; i++) { var r = globStringToRegex(split[i]); if (r.regexp) { regexp += '(' + r.regexp + ')'; if (i < split.length - 1) { regexp += '|'; } } else { excludes = excludes.concat(r.excludes); } } } else { if (str.indexOf('!') === 0) { excludes.push('^((?!' + globStringToRegex(str.substring(1)).regexp + ').)*$'); } else { if (str.indexOf('.') === 0) { str = '*' + str; } regexp = '^' + str.replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\-]', 'g'), '\\$&') + '$'; regexp = regexp.replace(/\\\*/g, '.*').replace(/\\\?/g, '.'); } } } return {regexp: regexp, excludes: excludes}; } upload.validatePattern = function (file, val) { if (!val) { return true; } var pattern = globStringToRegex(val), valid = true; if (pattern.regexp && pattern.regexp.length) { var regexp = new RegExp(pattern.regexp, 'i'); valid = (file.type != null && regexp.test(file.type)) || (file.name != null && regexp.test(file.name)); } var len = pattern.excludes.length; while (len--) { var exclude = new RegExp(pattern.excludes[len], 'i'); valid = valid && (file.type == null || exclude.test(file.type)) && (file.name == null || exclude.test(file.name)); } return valid; }; upload.ratioToFloat = function(val) { var r = val.toString(), xIndex = r.search(/[x:]/i); if (xIndex > -1) { r = parseFloat(r.substring(0, xIndex)) / parseFloat(r.substring(xIndex + 1)); } else { r = parseFloat(r); } return r; }; upload.registerModelChangeValidator = function (ngModel, attr, scope) { if (ngModel) { ngModel.$formatters.push(function (files) { if (!ngModel.$ngfModelChange) { upload.validate(files, ngModel, attr, scope, function () { upload.applyModelValidation(ngModel, files); }); } else { ngModel.$ngfModelChange = false; } }); } }; function markModelAsDirty(ngModel, files) { if (files != null && !ngModel.$dirty) { if (ngModel.$setDirty) { ngModel.$setDirty(); } else { ngModel.$dirty = true; } } } upload.applyModelValidation = function (ngModel, files) { markModelAsDirty(ngModel, files); angular.forEach(ngModel.$ngfValidations, function (validation) { ngModel.$setValidity(validation.name, validation.valid); }); }; upload.validate = function (files, ngModel, attr, scope) { ngModel = ngModel || {}; ngModel.$ngfValidations = ngModel.$ngfValidations || []; angular.forEach(ngModel.$ngfValidations, function (v) { v.valid = true; }); var attrGetter = function (name, params) { return upload.attrGetter(name, attr, scope, params); }; if (files == null || files.length === 0) { return upload.emptyPromise(ngModel); } files = files.length === undefined ? [files] : files.slice(0); function validateSync(name, validatorVal, fn) { if (files) { var dName = 'ngf' + name[0].toUpperCase() + name.substr(1); var i = files.length, valid = null; while (i--) { var file = files[i]; if (file) { var val = attrGetter(dName, {'$file': file}); if (val == null) { val = validatorVal(attrGetter('ngfValidate') || {}); valid = valid == null ? true : valid; } if (val != null) { if (!fn(file, val)) { file.$error = name; file.$errorParam = val; files.splice(i, 1); valid = false; } } } } if (valid !== null) { ngModel.$ngfValidations.push({name: name, valid: valid}); } } } validateSync('pattern', function (cons) { return cons.pattern; }, upload.validatePattern); validateSync('minSize', function (cons) { return cons.size && cons.size.min; }, function (file, val) { return file.size >= upload.translateScalars(val); }); validateSync('maxSize', function (cons) { return cons.size && cons.size.max; }, function (file, val) { return file.size <= upload.translateScalars(val); }); var totalSize = 0; validateSync('maxTotalSize', function (cons) { return cons.maxTotalSize && cons.maxTotalSize; }, function (file, val) { totalSize += file.size; if (totalSize > upload.translateScalars(val)) { files.splice(0, files.length); return false; } return true; }); validateSync('validateFn', function () { return null; }, function (file, r) { return r === true || r === null || r === ''; }); if (!files.length) { return upload.emptyPromise(ngModel, ngModel.$ngfValidations); } function validateAsync(name, validatorVal, type, asyncFn, fn) { var promises = [upload.emptyPromise()]; if (files) { var dName = 'ngf' + name[0].toUpperCase() + name.substr(1); files = files.length === undefined ? [files] : files; angular.forEach(files, function (file) { var defer = $q.defer(); promises.push(defer.promise); if (type && (file.type == null || file.type.search(type) !== 0)) { defer.resolve(); return; } var val = attrGetter(dName, {'$file': file}) || validatorVal(attrGetter('ngfValidate', {'$file': file}) || {}); if (val) { asyncFn(file, val).then(function (d) { if (!fn(d, val)) { file.$error = name; file.$errorParam = val; defer.reject(); } else { defer.resolve(); } }, function () { if (attrGetter('ngfValidateForce', {'$file': file})) { file.$error = name; file.$errorParam = val; defer.reject(); } else { defer.resolve(); } }); } else { defer.resolve(); } }); return $q.all(promises).then(function () { ngModel.$ngfValidations.push({name: name, valid: true}); }, function () { ngModel.$ngfValidations.push({name: name, valid: false}); }); } } var deffer = $q.defer(); var promises = []; promises.push(upload.happyPromise(validateAsync('maxHeight', function (cons) { return cons.height && cons.height.max; }, /image/, this.imageDimensions, function (d, val) { return d.height <= val; }))); promises.push(upload.happyPromise(validateAsync('minHeight', function (cons) { return cons.height && cons.height.min; }, /image/, this.imageDimensions, function (d, val) { return d.height >= val; }))); promises.push(upload.happyPromise(validateAsync('maxWidth', function (cons) { return cons.width && cons.width.max; }, /image/, this.imageDimensions, function (d, val) { return d.width <= val; }))); promises.push(upload.happyPromise(validateAsync('minWidth', function (cons) { return cons.width && cons.width.min; }, /image/, this.imageDimensions, function (d, val) { return d.width >= val; }))); promises.push(upload.happyPromise(validateAsync('ratio', function (cons) { return cons.ratio; }, /image/, this.imageDimensions, function (d, val) { var split = val.toString().split(','), valid = false; for (var i = 0; i < split.length; i++) { if (Math.abs((d.width / d.height) - upload.ratioToFloat(split[i])) < 0.0001) { valid = true; } } return valid; }))); promises.push(upload.happyPromise(validateAsync('maxRatio', function (cons) { return cons.ratio; }, /image/, this.imageDimensions, function (d, val) { return (d.width / d.height) - upload.ratioToFloat(val) < 0.0001; }))); promises.push(upload.happyPromise(validateAsync('minRatio', function (cons) { return cons.ratio; }, /image/, this.imageDimensions, function (d, val) { return (d.width / d.height) - upload.ratioToFloat(val) > -0.0001; }))); promises.push(upload.happyPromise(validateAsync('maxDuration', function (cons) { return cons.duration && cons.duration.max; }, /audio|video/, this.mediaDuration, function (d, val) { return d <= upload.translateScalars(val); }))); promises.push(upload.happyPromise(validateAsync('minDuration', function (cons) { return cons.duration && cons.duration.min; }, /audio|video/, this.mediaDuration, function (d, val) { return d >= upload.translateScalars(val); }))); promises.push(upload.happyPromise(validateAsync('validateAsyncFn', function () { return null; }, null, function (file, val) { return val; }, function (r) { return r === true || r === null || r === ''; }))); return $q.all(promises).then(function () { deffer.resolve(ngModel, ngModel.$ngfValidations); }); }; upload.imageDimensions = function (file) { if (file.$ngfWidth && file.$ngfHeight) { var d = $q.defer(); $timeout(function () { d.resolve({width: file.$ngfWidth, height: file.$ngfHeight}); }); return d.promise; } if (file.$ngfDimensionPromise) return file.$ngfDimensionPromise; var deferred = $q.defer(); $timeout(function () { if (file.type.indexOf('image') !== 0) { deferred.reject('not image'); return; } upload.dataUrl(file).then(function (dataUrl) { var img = angular.element('<img>').attr('src', dataUrl).css('visibility', 'hidden').css('position', 'fixed'); function success() { var width = img[0].clientWidth; var height = img[0].clientHeight; img.remove(); file.$ngfWidth = width; file.$ngfHeight = height; deferred.resolve({width: width, height: height}); } function error() { img.remove(); deferred.reject('load error'); } img.on('load', success); img.on('error', error); var count = 0; function checkLoadError() { $timeout(function () { if (img[0].parentNode) { if (img[0].clientWidth) { success(); } else if (count > 10) { error(); } else { checkLoadError(); } } }, 1000); } checkLoadError(); angular.element(document.getElementsByTagName('body')[0]).append(img); }, function () { deferred.reject('load error'); }); }); file.$ngfDimensionPromise = deferred.promise; file.$ngfDimensionPromise['finally'](function () { delete file.$ngfDimensionPromise; }); return file.$ngfDimensionPromise; }; upload.mediaDuration = function (file) { if (file.$ngfDuration) { var d = $q.defer(); $timeout(function () { d.resolve(file.$ngfDuration); }); return d.promise; } if (file.$ngfDurationPromise) return file.$ngfDurationPromise; var deferred = $q.defer(); $timeout(function () { if (file.type.indexOf('audio') !== 0 && file.type.indexOf('video') !== 0) { deferred.reject('not media'); return; } upload.dataUrl(file).then(function (dataUrl) { var el = angular.element(file.type.indexOf('audio') === 0 ? '<audio>' : '<video>') .attr('src', dataUrl).css('visibility', 'none').css('position', 'fixed'); function success() { var duration = el[0].duration; file.$ngfDuration = duration; el.remove(); deferred.resolve(duration); } function error() { el.remove(); deferred.reject('load error'); } el.on('loadedmetadata', success); el.on('error', error); var count = 0; function checkLoadError() { $timeout(function () { if (el[0].parentNode) { if (el[0].duration) { success(); } else if (count > 10) { error(); } else { checkLoadError(); } } }, 1000); } checkLoadError(); angular.element(document.body).append(el); }, function () { deferred.reject('load error'); }); }); file.$ngfDurationPromise = deferred.promise; file.$ngfDurationPromise['finally'](function () { delete file.$ngfDurationPromise; }); return file.$ngfDurationPromise; }; return upload; } ]); ngFileUpload.service('UploadResize', ['UploadValidate', '$q', function (UploadValidate, $q) { var upload = UploadValidate; /** * Conserve aspect ratio of the original region. Useful when shrinking/enlarging * images to fit into a certain area. * Source: http://stackoverflow.com/a/14731922 * * @param {Number} srcWidth Source area width * @param {Number} srcHeight Source area height * @param {Number} maxWidth Nestable area maximum available width * @param {Number} maxHeight Nestable area maximum available height * @return {Object} { width, height } */ var calculateAspectRatioFit = function (srcWidth, srcHeight, maxWidth, maxHeight, centerCrop) { var ratio = centerCrop ? Math.max(maxWidth / srcWidth, maxHeight / srcHeight) : Math.min(maxWidth / srcWidth, maxHeight / srcHeight); return {width: srcWidth * ratio, height: srcHeight * ratio, marginX: srcWidth * ratio - maxWidth, marginY: srcHeight * ratio - maxHeight}; }; // Extracted from https://github.com/romelgomez/angular-firebase-image-upload/blob/master/app/scripts/fileUpload.js#L89 var resize = function (imagen, width, height, quality, type, ratio, centerCrop) { var deferred = $q.defer(); var canvasElement = document.createElement('canvas'); var imageElement = document.createElement('img'); imageElement.onload = function () { try { if (ratio) { var ratioFloat = upload.ratioToFloat(ratio); var imgRatio = imageElement.width / imageElement.height; if (imgRatio < ratioFloat) { width = imageElement.width; height = width / ratioFloat; } else { height = imageElement.height; width = height * ratioFloat; } } if (!width) { width = imageElement.width; } if (!height) { height = imageElement.height; } var dimensions = calculateAspectRatioFit(imageElement.width, imageElement.height, width, height, centerCrop); canvasElement.width = Math.min(dimensions.width, width); canvasElement.height = Math.min(dimensions.height, height); var context = canvasElement.getContext('2d'); context.drawImage(imageElement, Math.min(0, -dimensions.marginX / 2), Math.min(0, -dimensions.marginY / 2), dimensions.width, dimensions.height); deferred.resolve(canvasElement.toDataURL(type || 'image/WebP', quality || 1.0)); } catch (e) { deferred.reject(e); } }; imageElement.onerror = function () { deferred.reject(); }; imageElement.src = imagen; return deferred.promise; }; upload.dataUrltoBlob = function (dataurl, name) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } var blob = new window.Blob([u8arr], {type: mime}); blob.name = name; return blob; }; upload.isResizeSupported = function () { var elem = document.createElement('canvas'); return window.atob && elem.getContext && elem.getContext('2d'); }; if (upload.isResizeSupported()) { // add name getter to the blob constructor prototype Object.defineProperty(window.Blob.prototype, 'name', { get: function () { return this.$ngfName; }, set: function (v) { this.$ngfName = v; }, configurable: true }); } upload.resize = function (file, width, height, quality, type, ratio, centerCrop) { if (file.type.indexOf('image') !== 0) return upload.emptyPromise(file); var deferred = $q.defer(); upload.dataUrl(file, true).then(function (url) { resize(url, width, height, quality, type || file.type, ratio, centerCrop).then(function (dataUrl) { deferred.resolve(upload.dataUrltoBlob(dataUrl, file.name)); }, function () { deferred.reject(); }); }, function () { deferred.reject(); }); return deferred.promise; }; return upload; }]); (function () { ngFileUpload.directive('ngfDrop', ['$parse', '$timeout', '$location', 'Upload', '$http', '$q', function ($parse, $timeout, $location, Upload, $http, $q) { return { restrict: 'AEC', require: '?ngModel', link: function (scope, elem, attr, ngModel) { linkDrop(scope, elem, attr, ngModel, $parse, $timeout, $location, Upload, $http, $q); } }; }]); ngFileUpload.directive('ngfNoFileDrop', function () { return function (scope, elem) { if (dropAvailable()) elem.css('display', 'none'); }; }); ngFileUpload.directive('ngfDropAvailable', ['$parse', '$timeout', 'Upload', function ($parse, $timeout, Upload) { return function (scope, elem, attr) { if (dropAvailable()) { var model = $parse(Upload.attrGetter('ngfDropAvailable', attr)); $timeout(function () { model(scope); if (model.assign) { model.assign(scope, true); } }); } }; }]); function linkDrop(scope, elem, attr, ngModel, $parse, $timeout, $location, upload, $http, $q) { var available = dropAvailable(); var attrGetter = function (name, scope, params) { return upload.attrGetter(name, attr, scope, params); }; if (attrGetter('dropAvailable')) { $timeout(function () { if (scope[attrGetter('dropAvailable')]) { scope[attrGetter('dropAvailable')].value = available; } else { scope[attrGetter('dropAvailable')] = available; } }); } if (!available) { if (attrGetter('ngfHideOnDropNotAvailable', scope) === true) { elem.css('display', 'none'); } return; } function isDisabled() { return elem.attr('disabled') || attrGetter('ngfDropDisabled', scope); } if (attrGetter('ngfSelect') == null) { upload.registerModelChangeValidator(ngModel, attr, scope); } var leaveTimeout = null; var stopPropagation = $parse(attrGetter('ngfStopPropagation')); var dragOverDelay = 1; var actualDragOverClass; elem[0].addEventListener('dragover', function (evt) { if (isDisabled()) return; evt.preventDefault(); if (stopPropagation(scope)) evt.stopPropagation(); // handling dragover events from the Chrome download bar if (navigator.userAgent.indexOf('Chrome') > -1) { var b = evt.dataTransfer.effectAllowed; evt.dataTransfer.dropEffect = ('move' === b || 'linkMove' === b) ? 'move' : 'copy'; } $timeout.cancel(leaveTimeout); if (!actualDragOverClass) { actualDragOverClass = 'C'; calculateDragOverClass(scope, attr, evt, function (clazz) { actualDragOverClass = clazz; elem.addClass(actualDragOverClass); attrGetter('ngfDrag', scope, {$isDragging: true, $class: actualDragOverClass, $event: evt}); }); } }, false); elem[0].addEventListener('dragenter', function (evt) { if (isDisabled()) return; evt.preventDefault(); if (stopPropagation(scope)) evt.stopPropagation(); }, false); elem[0].addEventListener('dragleave', function (evt) { if (isDisabled()) return; evt.preventDefault(); if (stopPropagation(scope)) evt.stopPropagation(); leaveTimeout = $timeout(function () { if (actualDragOverClass) elem.removeClass(actualDragOverClass); actualDragOverClass = null; attrGetter('ngfDrag', scope, {$isDragging: false, $event: evt}); }, dragOverDelay || 100); }, false); elem[0].addEventListener('drop', function (evt) { if (isDisabled() || !upload.shouldUpdateOn('drop', attr, scope)) return; evt.preventDefault(); if (stopPropagation(scope)) evt.stopPropagation(); if (actualDragOverClass) elem.removeClass(actualDragOverClass); actualDragOverClass = null; var html; try { html = (evt.dataTransfer && evt.dataTransfer.getData && evt.dataTransfer.getData('text/html')); } catch (e) {/* Fix IE11 that throw error calling getData */ } if (upload.shouldUpdateOn('dropUrl', attr, scope) && html) { extractUrlAndUpdateModel(html, evt); } else { extractFiles(evt, function (files) { upload.updateModel(ngModel, attr, scope, attrGetter('ngfChange') || attrGetter('ngfDrop'), files, evt); }, attrGetter('ngfAllowDir', scope) !== false, attrGetter('multiple') || attrGetter('ngfMultiple', scope)); } }, false); elem[0].addEventListener('paste', function (evt) { if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) { evt.preventDefault(); } if (isDisabled() || !upload.shouldUpdateOn('paste', attr, scope)) return; var files = []; var clipboard = evt.clipboardData || evt.originalEvent.clipboardData; if (clipboard && clipboard.items) { for (var k = 0; k < clipboard.items.length; k++) { if (clipboard.items[k].type.indexOf('image') !== -1) { files.push(clipboard.items[k].getAsFile()); } } } if (files.length) { upload.updateModel(ngModel, attr, scope, attrGetter('ngfChange') || attrGetter('ngfDrop'), files, evt); } else { var html; try { html = (clipboard && clipboard.getData && clipboard.getData('text/html')); } catch (e) {/* Fix IE11 that throw error calling getData */ } if (upload.shouldUpdateOn('pasteUrl', attr, scope) && html) { extractUrlAndUpdateModel(html, evt); } } }, false); if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1 && attrGetter('ngfEnableFirefoxPaste', scope)) { elem.attr('contenteditable', true); elem.on('keypress', function (e) { if (!e.metaKey && !e.ctrlKey) { e.preventDefault(); } }); } function extractUrlAndUpdateModel(html, evt) { var urls = []; html.replace(/<(img src|img [^>]* src) *=\"([^\"]*)\"/gi, function (m, n, src) { urls.push(src); }); var promises = [], files = []; if (urls.length) { angular.forEach(urls, function (url) { promises.push($http({url: url, method: 'get', responseType: 'arraybuffer'}).then(function (resp) { var arrayBufferView = new Uint8Array(resp.data); var type = resp.headers('content-type') || 'image/WebP'; var blob = new window.Blob([arrayBufferView], {type: type}); files.push(blob); //var split = type.split('[/;]'); //blob.name = url.substring(0, 150).replace(/\W+/g, '') + '.' + (split.length > 1 ? split[1] : 'jpg'); })); }); $q.all(promises).then(function () { upload.updateModel(ngModel, attr, scope, attrGetter('ngfChange') || attrGetter('ngfDrop'), files, evt); }); } } function calculateDragOverClass(scope, attr, evt, callback) { var obj = attrGetter('ngfDragOverClass', scope, {$event: evt}), dClass = 'dragover'; if (angular.isString(obj)) { dClass = obj; } else if (obj) { if (obj.delay) dragOverDelay = obj.delay; if (obj.accept || obj.reject) { var items = evt.dataTransfer.items; if (items == null || !items.length) { dClass = obj.accept; } else { var pattern = obj.pattern || attrGetter('ngfPattern', scope, {$event: evt}); var len = items.length; while (len--) { if (!upload.validatePattern(items[len], pattern)) { dClass = obj.reject; break; } else { dClass = obj.accept; } } } } } callback(dClass); } function extractFiles(evt, callback, allowDir, multiple) { var files = [], processing = 0; function traverseFileTree(files, entry, path) { if (entry != null) { if (entry.isDirectory) { var filePath = (path || '') + entry.name; files.push({name: entry.name, type: 'directory', path: filePath}); var dirReader = entry.createReader(); var entries = []; processing++; var readEntries = function () { dirReader.readEntries(function (results) { try { if (!results.length) { for (var i = 0; i < entries.length; i++) { traverseFileTree(files, entries[i], (path ? path : '') + entry.name + '/'); } processing--; } else { entries = entries.concat(Array.prototype.slice.call(results || [], 0)); readEntries(); } } catch (e) { processing--; console.error(e); } }, function () { processing--; }); }; readEntries(); } else { processing++; entry.file(function (file) { try { processing--; file.path = (path ? path : '') + file.name; files.push(file); } catch (e) { processing--; console.error(e); } }, function () { processing--; }); } } } var items = evt.dataTransfer.items; if (items && items.length > 0 && $location.protocol() !== 'file') { for (var i = 0; i < items.length; i++) { if (items[i].webkitGetAsEntry && items[i].webkitGetAsEntry() && items[i].webkitGetAsEntry().isDirectory) { var entry = items[i].webkitGetAsEntry(); if (entry.isDirectory && !allowDir) { continue; } if (entry != null) { traverseFileTree(files, entry); } } else { var f = items[i].getAsFile(); if (f != null) files.push(f); } if (!multiple && files.length > 0) break; } } else { var fileList = evt.dataTransfer.files; if (fileList != null) { for (var j = 0; j < fileList.length; j++) { var file = fileList.item(j); if (file.type || file.size > 0) { files.push(file); } if (!multiple && files.length > 0) { break; } } } } var delays = 0; (function waitForProcess(delay) { $timeout(function () { if (!processing) { if (!multiple && files.length > 1) { i = 0; while (files[i].type === 'directory') i++; files = [files[i]]; } callback(files); } else { if (delays++ * 10 < 20 * 1000) { waitForProcess(10); } } }, delay || 0); })(); } } function dropAvailable() { var div = document.createElement('div'); return ('draggable' in div) && ('ondrop' in div) && !/Edge\/12./i.test(navigator.userAgent); } })(); // customized version of https://github.com/exif-js/exif-js ngFileUpload.service('UploadExif', ['UploadResize', '$q', function (UploadResize, $q) { var upload = UploadResize; function findEXIFinJPEG(file) { var dataView = new DataView(file); if ((dataView.getUint8(0) !== 0xFF) || (dataView.getUint8(1) !== 0xD8)) { return 'Not a valid JPEG'; } var offset = 2, length = file.byteLength, marker; while (offset < length) { if (dataView.getUint8(offset) !== 0xFF) { return 'Not a valid marker at offset ' + offset + ', found: ' + dataView.getUint8(offset); } marker = dataView.getUint8(offset + 1); if (marker === 225) { return readEXIFData(dataView, offset + 4, dataView.getUint16(offset + 2) - 2); } else { offset += 2 + dataView.getUint16(offset + 2); } } } function readOrientation(file, tiffStart, dirStart, bigEnd) { var entries = file.getUint16(dirStart, !bigEnd), entryOffset, i; for (i = 0; i < entries; i++) { entryOffset = dirStart + i * 12 + 2; var val = file.getUint16(entryOffset, !bigEnd); if (0x0112 === val) { return readTagValue(file, entryOffset, tiffStart, bigEnd); } } return null; } function readTagValue(file, entryOffset, tiffStart, bigEnd) { var numValues = file.getUint32(entryOffset + 4, !bigEnd), valueOffset = file.getUint32(entryOffset + 8, !bigEnd) + tiffStart, offset, vals, n; if (numValues === 1) { return file.getUint16(entryOffset + 8, !bigEnd); } else { offset = numValues > 2 ? valueOffset : (entryOffset + 8); vals = []; for (n = 0; n < numValues; n++) { vals[n] = file.getUint16(offset + 2 * n, !bigEnd); } return vals; } } function getStringFromDB(buffer, start, length) { var outstr = ''; for (var n = start; n < start + length; n++) { outstr += String.fromCharCode(buffer.getUint8(n)); } return outstr; } function readEXIFData(file, start) { if (getStringFromDB(file, start, 4) !== 'Exif') { return 'Not valid EXIF data! ' + getStringFromDB(file, start, 4); } var bigEnd, tiffOffset = start + 6; // test for TIFF validity and endianness if (file.getUint16(tiffOffset) === 0x4949) { bigEnd = false; } else if (file.getUint16(tiffOffset) === 0x4D4D) { bigEnd = true; } else { return 'Not valid TIFF data! (no 0x4949 or 0x4D4D)'; } if (file.getUint16(tiffOffset + 2, !bigEnd) !== 0x002A) { return 'Not valid TIFF data! (no 0x002A)'; } var firstIFDOffset = file.getUint32(tiffOffset + 4, !bigEnd); if (firstIFDOffset < 0x00000008) { return 'Not valid TIFF data! (First offset less than 8)', file.getUint32(tiffOffset + 4, !bigEnd); } return readOrientation(file, tiffOffset, tiffOffset + firstIFDOffset, bigEnd); } upload.isExifSupported = function() { return window.FileReader && new FileReader().readAsArrayBuffer && upload.isResizeSupported(); }; upload.orientation = function (file) { if (file.$ngfOrientation != null) { return upload.emptyPromise(file.$ngfOrientation); } var defer = $q.defer(); var fileReader = new FileReader(); fileReader.onload = function (e) { var orientation; try { orientation = findEXIFinJPEG(e.target.result); } catch (e) { defer.reject(e); return; } if (angular.isString(orientation)) { defer.resolve(1); } else { file.$ngfOrientation = orientation; defer.resolve(orientation); } }; fileReader.onerror = function (e) { defer.reject(e); }; fileReader.readAsArrayBuffer(file); return defer.promise; }; function applyTransform(ctx, orientation, width, height) { switch (orientation) { case 2: return ctx.transform(-1, 0, 0, 1, width, 0); case 3: return ctx.transform(-1, 0, 0, -1, width, height); case 4: return ctx.transform(1, 0, 0, -1, 0, height); case 5: return ctx.transform(0, 1, 1, 0, 0, 0); case 6: return ctx.transform(0, 1, -1, 0, height, 0); case 7: return ctx.transform(0, -1, -1, 0, height, width); case 8: return ctx.transform(0, -1, 1, 0, 0, width); } } upload.applyExifRotation = function (file) { if (file.type.indexOf('image/jpeg') !== 0) { return upload.emptyPromise(file); } var deferred = $q.defer(); upload.orientation(file).then(function (orientation) { if (!orientation || orientation < 2 || orientation > 8) { deferred.resolve(file); } upload.dataUrl(file, true).then(function (url) { var canvas = document.createElement('canvas'); var img = document.createElement('img'); img.onload = function () { try { canvas.width = orientation > 4 ? img.height : img.width; canvas.height = orientation > 4 ? img.width : img.height; var ctx = canvas.getContext('2d'); applyTransform(ctx, orientation, img.width, img.height); ctx.drawImage(img, 0, 0); var dataUrl = canvas.toDataURL(file.type || 'image/WebP', 1.0); var blob = upload.dataUrltoBlob(dataUrl, file.name); deferred.resolve(blob); } catch (e) { deferred.reject(e); } }; img.onerror = function () { deferred.reject(); }; img.src = url; }, function (e) { deferred.reject(e); }); }, function (e) { deferred.reject(e); }); return deferred.promise; }; return upload; }]);
angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": { "0": "vorm.", "1": "nachm." }, "DAY": { "0": "Sonntag", "1": "Montag", "2": "Dienstag", "3": "Mittwoch", "4": "Donnerstag", "5": "Freitag", "6": "Samstag" }, "MONTH": { "0": "Januar", "1": "Februar", "2": "M\u00e4rz", "3": "April", "4": "Mai", "5": "Juni", "6": "Juli", "7": "August", "8": "September", "9": "Oktober", "10": "November", "11": "Dezember" }, "SHORTDAY": { "0": "So.", "1": "Mo.", "2": "Di.", "3": "Mi.", "4": "Do.", "5": "Fr.", "6": "Sa." }, "SHORTMONTH": { "0": "Jan", "1": "Feb", "2": "M\u00e4r", "3": "Apr", "4": "Mai", "5": "Jun", "6": "Jul", "7": "Aug", "8": "Sep", "9": "Okt", "10": "Nov", "11": "Dez" }, "fullDate": "EEEE, d. MMMM y", "longDate": "d. MMMM y", "medium": "dd.MM.yyyy HH:mm:ss", "mediumDate": "dd.MM.yyyy", "mediumTime": "HH:mm:ss", "short": "dd.MM.yy HH:mm", "shortDate": "dd.MM.yy", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u20ac", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": { "0": { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, "1": { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a0\u00a4", "posPre": "", "posSuf": "\u00a0\u00a4" } } }, "id": "de-li", "pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
/** * @fileoverview Rule to flag use of continue statement * @author Borislav Zhivkov */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: "disallow `continue` statements", category: "Stylistic Issues", recommended: false }, schema: [] }, create(context) { return { ContinueStatement(node) { context.report(node, "Unexpected use of continue statement."); } }; } };
CKEDITOR.plugins.setLang("pagebreak","mn",{alt:"Page Break",toolbar:"Хуудас тусгаарлагч оруулах"});
/** * copyright: 2011 Intel * description: This script will replace all drop downs with friendly select controls. Users can still interact * with the old drop down box as normal with javascript, and this will be reflected */ /* global af*/ /* global numOnly*/ (function($) { /*jshint camelcase: false, validthis:true */ "use strict"; function updateOption(prop, oldValue, newValue) { if (newValue === true) { if (!this.getAttribute("multiple")) $.selectBox.updateMaskValue(this.parentNode.id, this.text, this.value); this.parentNode.value = this.value; } return newValue; } function updateIndex(prop, oldValue, newValue) { if (this.options[newValue]) { if (!this.getAttribute("multiple")) $.selectBox.updateMaskValue(this.linker, this.options[newValue].value, this.options[newValue].text); this.value = this.options[newValue].value; } return newValue; } function destroy(e) { var el = e.target; $(el.linker).remove(); delete el.linker; e.stopPropagation(); } $.selectBox = { scroller: null, currLinker: null, getOldSelects: function(elID) { if (!$.os.android || $.os.androidICS) return; if (!$.fn.scroller) { window.alert("This library requires af.scroller"); return; } var container = elID && document.getElementById(elID) ? document.getElementById(elID) : document; if (!container) { window.alert("Could not find container element for af.selectBox " + elID); return; } var sels = container.getElementsByTagName("select"); var that = this; for (var i = 0; i < sels.length; i++) { var el = sels[i]; el.style.display = "none"; var fixer = $.create("div", { className: "afFakeSelect" }); fixer.get(0).linker = sels[i]; el.linker = fixer.get(0); fixer.insertAfter(sels[i]); el.watch("selectedIndex", updateIndex); for (var j = 0; j < el.options.length; j++) { el.options[j].watch("selected", updateOption); if (el.options[j].selected) fixer.html(el.options[j].text); } $(el).one("destroy", destroy); } that.createHtml(); }, updateDropdown: function(el) { if (!el) return; for (var j = 0; j < el.options.length; j++) { if (el.options[j].selected) el.linker.innerHTML = el.options[j].text; } el = null; }, initDropDown: function(el) { if (el.disabled) return; if (!el || !el.options || el.options.length === 0) return; var foundInd = 0; var $scr = $("#afSelectBoxfix"); $scr.html("<ul></ul>"); var $list = $scr.find("ul"); for (var j = 0; j < el.options.length; j++) { el.options[j].watch("selected", updateOption); var checked = (el.options[j].selected) ? "selected" : ""; if (checked) foundInd = j + 1; var row = $.create("li", { html: el.options[j].text, className: checked }); row.data("ind", j); $list.append(row); } $("#afModalMask").show(); try { if (foundInd > 0 && el.getAttribute("multiple") !== "multiple") { var scrollToPos = 0; var scrollThreshold = numOnly($list.find("li").computedStyle("height")); var theHeight = numOnly($("#afSelectBoxContainer").computedStyle("height")); if (foundInd * scrollThreshold >= theHeight) scrollToPos = (foundInd - 1) * -scrollThreshold; this.scroller.scrollTo({ x: 0, y: scrollToPos }); } } catch (e) { console.log("error init dropdown" + e); } var selClose = $("#afSelectClose").css("display") === "block" ? numOnly($("#afSelectClose").height()) : 0; $("#afSelectWrapper").height((numOnly($("#afSelectBoxContainer").height()) - selClose) + "px"); }, updateMaskValue: function(linker, value, val2) { $(linker).html(val2); }, setDropDownValue: function(el, value) { if (!el) return; var $el = $(el); value = parseInt(value, 10); if(isNaN(value)) return; if (!el.getAttribute("multiple")) { el.selectedIndex = value; $el.find("option").prop("selected", false); $el.find("option:nth-child(" + (value + 1) + ")").prop("selected", true); this.scroller.scrollTo({ x: 0, y: 0 }); this.hideDropDown(); } else { //multi select // var myEl = $el.find("option:nth-child(" + (value + 1) + ")").get(0); var myList = $("#afSelectBoxfix li:nth-child(" + (value + 1) + ")"); if (myList.hasClass("selected")) { myList.removeClass("selected"); // myEl.selected = false; } else { myList.addClass("selected"); // myEl.selected = true; } } $(el).trigger("change"); el = null; }, hideDropDown: function() { $("#afModalMask").hide(); $("#afSelectBoxfix").html(""); }, createHtml: function() { var that = this; if (document.getElementById("afSelectBoxfix")) { return; } $(document).ready(function() { $(document).on("click", ".afFakeSelect", function() { if (this.linker.disabled) return; that.currLinker = this; if (this.linker.getAttribute("multiple") === "multiple") $("#afSelectClose").show(); else $("#afSelectClose").hide(); that.initDropDown(this.linker); }); var container = $.create("div", { id: "afSelectBoxContainer" }); var modalDiv = $.create("div", { id: "afSelectBoxfix" }); var modalWrapper = $.create("div", { id: "afSelectWrapper" }); modalWrapper.css("position", "relative"); modalWrapper.append(modalDiv); var closeDiv = $.create("div", { id: "afSelectClose", html: "<a id='afSelectDone'>Done</a> <a id='afSelectCancel'>Cancel</a>" }); var modalMask = $.create("div", { id:"afModalMask" }); var $afui = $("#afui"); container.prepend(closeDiv).append(modalWrapper); modalMask.append(container); if ($afui.length > 0) $afui.append(modalMask); else document.body.appendChild(modalMask.get(0)); that.scroller = $.query("#afSelectBoxfix").scroller({ scroller: false, verticalScroll: true, vScrollCSS: "afselectscrollBarV", hasParent:true }); $("#afModalMask").on("click",function(e){ var $e=$(e.target); if($e.closest("#afSelectBoxContainer").length === 0) that.hideDropDown(); }); $("#afSelectBoxfix").on("click", "li", function(e) { var $el = $(e.target); that.setDropDownValue(that.currLinker.linker, $el.data("ind")); }); $("#afSelectBoxContainer").on("click", "a", function(e) { if (e.target.id === "afSelectCancel") return that.hideDropDown(); var $sel = $(that.currLinker.linker); $sel.find("option").prop("selected", false); $("#afSelectBoxfix li").each(function() { var $el = $(this); if ($el.hasClass("selected")) { var ind = parseInt($el.data("ind"), 10); $sel.find("option:nth-child(" + (ind + 1) + ")").prop("selected", true); that.currLinker.innerHTML = $el.html(); } }); that.hideDropDown(); e.stopPropagation(); e.preventDefault(); return false; }); }); } }; //The following is based off Eli Grey's shim //https://gist.github.com/384583 //We use HTMLElement to not cause problems with other objects if (!HTMLElement.prototype.watch) { HTMLElement.prototype.watch = function(prop, handler) { var oldval = this[prop], newval = oldval, getter = function() { return newval; }, setter = function(val) { oldval = newval; newval = handler.call(this, prop, oldval, val); return newval; }; if (delete this[prop]) { // can't watch constants if (HTMLElement.defineProperty) { // ECMAScript 5 HTMLElement.defineProperty(this, prop, { get: getter, set: setter, enumerable: false, configurable: true }); } else if (HTMLElement.prototype.__defineGetter__ && HTMLElement.prototype.__defineSetter__) { // legacy HTMLElement.prototype.__defineGetter__.call(this, prop, getter); HTMLElement.prototype.__defineSetter__.call(this, prop, setter); } } }; } if (!HTMLElement.prototype.unwatch) { HTMLElement.prototype.unwatch = function(prop) { var val = this[prop]; delete this[prop]; // remove accessors this[prop] = val; }; } })(af);
/* * log-rewriter-test.js: Tests for rewriting metadata in winston. * * (C) 2010 Charlie Robbins * MIT LICENSE * */ var assert = require('assert'), vows = require('vows'), winston = require('../lib/winston'), util = require('util'), helpers = require('./helpers'); vows.describe('winston/logger/levels').addBatch({ "The winston logger": { topic: new (winston.Logger)({ transports: [ new (winston.transports.Console)() ] }), "the info() method": { "when passed metadata": { topic: function (logger) { logger.once('logging', this.callback); logger.info('test message', {foo: 'bar'}); }, "should have metadata object": function (transport, level, msg, meta) { assert.strictEqual(msg, 'test message'); assert.deepEqual(meta, {foo: 'bar'}); } } }, "when passed a string placeholder": { topic: function (logger) { logger.once('logging', this.callback); logger.info('test message %s', 'my string'); }, "should interpolate": function (transport, level, msg, meta) { assert.strictEqual(msg, 'test message my string'); }, }, "when passed a number placeholder": { topic: function (logger) { logger.once('logging', this.callback); logger.info('test message %d', 123); }, "should interpolate": function (transport, level, msg, meta) { assert.strictEqual(msg, 'test message 123'); }, }, "when passed a json placholder and an empty object": { topic: function (logger) { logger.once('logging', this.callback); logger.info('test message %j', {number: 123}, {}); }, "should interpolate": function (transport, level, msg, meta) { assert.strictEqual(msg, 'test message {"number":123}'); }, }, "when passed a escaped percent sign": { topic: function (logger) { logger.once('logging', this.callback); logger.info('test message %%', {number: 123}); }, "should not interpolate": function (transport, level, msg, meta) { assert.strictEqual(msg, util.format('test message %%')); assert.deepEqual(meta, {number: 123}); }, }, "when passed interpolation strings and a meta object": { topic: function (logger) { logger.once('logging', this.callback); logger.info('test message %s, %s', 'first', 'second' ,{number: 123}); }, "should interpolate and have a meta object": function (transport, level, msg, meta) { assert.strictEqual(msg, 'test message first, second'); assert.deepEqual(meta, {number: 123}); }, }, "when passed multiple strings and a meta object": { topic: function (logger) { logger.once('logging', this.callback); logger.info('test message', 'first', 'second' , {number: 123}); }, "should join and have a meta object": function (transport, level, msg, meta) { assert.strictEqual(msg, 'test message first second'); assert.deepEqual(meta, {number: 123}); }, }, "when passed interpolations strings, meta object and a callback": { topic: function (logger) { var that = this; logger.info('test message %s, %s', 'first', 'second' , {number: 123}, function(transport, level, msg, meta){ that.callback(transport, level, msg, meta) }); }, "should interpolate and have a meta object": function (transport, level, msg, meta) { assert.strictEqual(msg, 'test message first, second'); assert.deepEqual(meta, {number: 123}); }, }, "when passed multiple strings, a meta object and a callback": { topic: function (logger) { var that = this; logger.info('test message', 'first', 'second' , {number: 123}, function(transport, level, msg, meta){ that.callback(transport, level, msg, meta) }); }, "should join and have a meta object": function (transport, level, msg, meta) { assert.strictEqual(msg, 'test message first second'); assert.deepEqual(meta, {number: 123}); } }, "when custom levels are set": { "should not fail with 'RangeError: Maximum call stack size exceeded": function (logger) { var that = this; // Logging levels var customLevels = { levels: { none: 0, log: 1, } }; var logger = winston.loggers.add('hello243', { }); try { logger.setLevels(customLevels.levels); } catch (e) { assert.equal('Error', e.name); } try { logger.log('none', 'hi', function (err) { assert.ifError(err); }); } catch (e) { assert.ifError(e); } } } } }).export(module);
/*! * Waves v0.5.0 * https://publicis-indonesia.github.io/Waves * * Copyright 2014 Publicis Metro Indonesia, PT. and other contributors * Released under the BSD license * https://github.com/publicis-indonesia/Waves/blob/master/LICENSE */ ;(function(window) { 'use strict'; var Waves = Waves || {}; var $$ = document.querySelectorAll.bind(document); // Find exact position of element function position(obj) { var left = 0; var top = 0; if (obj.offsetParent) { do { left += obj.offsetLeft; top += obj.offsetTop; } while (obj === obj.offsetParent); } return { top: top, left: left }; } function convertStyle(obj) { var style = ''; for (var a in obj) { if (obj.hasOwnProperty(a)) { style += (a + ':' + obj[a] + ';'); } } return style; } var Effect = { // Effect delay duration: 500, show: function(e) { var el = this; // Create ripple var ripple = document.createElement('div'); ripple.className = 'waves-ripple'; el.appendChild(ripple); // Get click coordinate and element witdh var pos = position(el); var relativeY = (e.pageY - pos.top) - 45; var relativeX = (e.pageX - pos.left) - 45; var scale = 'scale('+((el.clientWidth / 100) * 2.5)+')'; // Attach data to element ripple.setAttribute('data-hold', Date.now()); ripple.setAttribute('data-scale', scale); ripple.setAttribute('data-x', relativeX); ripple.setAttribute('data-y', relativeY); // Set ripple position var rippleStyle = { 'top': relativeY+'px', 'left': relativeX+'px' }; ripple.className = ripple.className + ' waves-notransition'; ripple.setAttribute('style', convertStyle(rippleStyle)); ripple.className = ripple.className.replace('waves-notransition', ''); // Scale the ripple rippleStyle['-webkit-transform'] = scale; rippleStyle['-moz-transform'] = scale; rippleStyle['-ms-transform'] = scale; rippleStyle['-o-transform'] = scale; rippleStyle.transform = scale; rippleStyle.opacity = '1'; rippleStyle['-webkit-transition-duration'] = Effect.duration + 'ms'; rippleStyle['-moz-transition-duration'] = Effect.duration + 'ms'; rippleStyle['-o-transition-duration'] = Effect.duration + 'ms'; rippleStyle['transition-duration'] = Effect.duration + 'ms'; ripple.setAttribute('style', convertStyle(rippleStyle)); }, hide: function() { var el = this; var width = el.clientWidth * 1.4; // Get first ripple var ripple = null; var childrenLength = el.children.length; for (var a = 0; a < childrenLength; a++) { if (el.children[a].className.indexOf('waves-ripple') !== -1) { ripple = el.children[a]; continue; } } if (!ripple) { return false; } var relativeX = ripple.getAttribute('data-x'); var relativeY = ripple.getAttribute('data-y'); var scale = ripple.getAttribute('data-scale'); // Get delay beetween mousedown and mouse leave var diff = Date.now() - Number(ripple.getAttribute('data-hold')); var delay = 500 - diff; if (delay < 0) { delay = 0; } // Fade out ripple after delay setTimeout(function() { var style = { 'top': relativeY+'px', 'left': relativeX+'px', 'opacity': '0', // Duration '-webkit-transition-duration': Effect.duration + 'ms', '-moz-transition-duration': Effect.duration + 'ms', '-o-transition-duration': Effect.duration + 'ms', 'transition-duration': Effect.duration + 'ms', '-webkit-transform': scale, '-moz-transform': scale, '-ms-transform': scale, '-o-transform': scale, 'transform': scale, }; ripple.setAttribute('style', convertStyle(style)); setTimeout(function() { try { el.removeChild(ripple); } catch(e) { return false; } }, Effect.duration); }, delay); }, // Little hack to make <input> can perform waves effect wrapInput: function(elements) { for (var a = 0; a < elements.length; a++) { var el = elements[a]; if (el.tagName.toLowerCase() === 'input') { var parent = el.parentNode; // If input already have parent just pass through if (parent.tagName.toLowerCase() === 'i' && parent.className.indexOf('waves-effect') !== -1) { return false; } // Put element class and style to the specified parent var wrapper = document.createElement('i'); wrapper.className = el.className + ' waves-input-wrapper'; var elementStyle = el.getAttribute('style'); var dimensionStyle = 'width:'+el.offsetWidth+'px;height:'+el.clientHeight+'px;'; if (!elementStyle) { elementStyle = ''; } wrapper.setAttribute('style', dimensionStyle+elementStyle); el.className = 'waves-button-input'; el.removeAttribute('style'); // Put element as child parent.replaceChild(wrapper, el); wrapper.appendChild(el); } } } }; Waves.displayEffect = function(options) { options = options || {}; if ('duration' in options) { Effect.duration = options.duration; } //Wrap input inside <i> tag Effect.wrapInput($$('.waves-effect')); Array.prototype.forEach.call($$('.waves-effect'), function(i) { if (window.Touch) { i.addEventListener('touchstart', Effect.show, false); i.addEventListener('touchend', Effect.hide, false); } i.addEventListener('mousedown', Effect.show, false); i.addEventListener('mouseup', Effect.hide, false); i.addEventListener('mouseleave', Effect.hide, false); }); }; window.Waves = Waves; })(window);
/*global window, document, setTimeout, Ghost, $, _, Backbone, JST, shortcut */ (function () { "use strict"; Ghost.TemplateView = Backbone.View.extend({ templateName: "widget", template: function (data) { return JST[this.templateName](data); }, templateData: function () { if (this.model) { return this.model.toJSON(); } if (this.collection) { return this.collection.toJSON(); } return {}; }, render: function () { if (_.isFunction(this.beforeRender)) { this.beforeRender(); } this.$el.html(this.template(this.templateData())); if (_.isFunction(this.afterRender)) { this.afterRender(); } return this; } }); Ghost.View = Ghost.TemplateView.extend({ // Adds a subview to the current view, which will // ensure its removal when this view is removed, // or when view.removeSubviews is called addSubview: function (view) { if (!(view instanceof Backbone.View)) { throw new Error("Subview must be a Backbone.View"); } this.subviews = this.subviews || []; this.subviews.push(view); return view; }, // Removes any subviews associated with this view // by `addSubview`, which will in-turn remove any // children of those views, and so on. removeSubviews: function () { var children = this.subviews; if (!children) { return this; } _(children).invoke("remove"); this.subviews = []; return this; }, // Extends the view's remove, by calling `removeSubviews` // if any subviews exist. remove: function () { if (this.subviews) { this.removeSubviews(); } return Backbone.View.prototype.remove.apply(this, arguments); } }); Ghost.Views.Utils = { // Used in API request fail handlers to parse a standard api error // response json for the message to display getRequestErrorMessage: function (request) { var message, msgDetail; // Can't really continue without a request if (!request) { return null; } // Seems like a sensible default message = request.statusText; // If a non 200 response if (request.status !== 200) { try { // Try to parse out the error, or default to "Unknown" message = request.responseJSON.error || "Unknown Error"; } catch (e) { msgDetail = request.status ? request.status + " - " + request.statusText : "Server was not available"; message = "The server returned an error (" + msgDetail + ")."; } } return message; }, // Getting URL vars getUrlVariables: function () { var vars = [], hash, hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'), i; for (i = 0; i < hashes.length; i += 1) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; } }; /** * This is the view to generate the markup for the individual * notification. Will be included into #notifications. * * States can be * - persistent * - passive * * Types can be * - error * - success * - alert * - (empty) * */ Ghost.Views.Notification = Ghost.View.extend({ templateName: 'notification', className: 'js-bb-notification', template: function (data) { return JST[this.templateName](data); }, render: function () { var html = this.template(this.model); this.$el.html(html); return this; } }); /** * This handles Notification groups */ Ghost.Views.NotificationCollection = Ghost.View.extend({ el: '#notifications', initialize: function () { var self = this; this.render(); Ghost.on('urlchange', function () { self.clearEverything(); }); shortcut.add("ESC", function () { // Make sure there isn't currently an open modal, as the escape key should close that first. // This is a temporary solution to enable closing extra-long notifications, and should be refactored // into something more robust in future if ($('.js-modal').length < 1) { self.clearEverything(); } }); }, events: { 'animationend .js-notification': 'removeItem', 'webkitAnimationEnd .js-notification': 'removeItem', 'oanimationend .js-notification': 'removeItem', 'MSAnimationEnd .js-notification': 'removeItem', 'click .js-notification.notification-passive .close': 'closePassive', 'click .js-notification.notification-persistent .close': 'closePersistent' }, render: function () { _.each(this.model, function (item) { this.renderItem(item); }, this); }, renderItem: function (item) { var itemView = new Ghost.Views.Notification({ model: item }), height, $notification = $(itemView.render().el); this.$el.append($notification); height = $notification.hide().outerHeight(true); $notification.animate({height: height}, 250, function () { $(this) .css({height: "auto"}) .fadeIn(250); }); }, addItem: function (item) { this.model.push(item); this.renderItem(item); }, clearEverything: function () { this.$el.find('.js-notification.notification-passive').parent().remove(); }, removeItem: function (e) { e.preventDefault(); var self = e.currentTarget, bbSelf = this; if (self.className.indexOf('notification-persistent') !== -1) { $.ajax({ type: "DELETE", headers: { 'X-CSRF-Token': $("meta[name='csrf-param']").attr('content') }, url: Ghost.paths.apiRoot + '/notifications/' + $(self).find('.close').data('id') }).done(function (result) { /*jshint unused:false*/ bbSelf.$el.slideUp(250, function () { $(this).show().css({height: "auto"}); $(self).remove(); }); }); } else { $(self).slideUp(250, function () { $(this) .show() .css({height: "auto"}) .parent() .remove(); }); } }, closePassive: function (e) { $(e.currentTarget) .parent() .fadeOut(250) .slideUp(250, function () { $(this).remove(); }); }, closePersistent: function (e) { var self = e.currentTarget, bbSelf = this; $.ajax({ type: "DELETE", headers: { 'X-CSRF-Token': $("meta[name='csrf-param']").attr('content') }, url: Ghost.paths.apiRoot + '/notifications/' + $(self).data('id') }).done(function (result) { /*jshint unused:false*/ var height = bbSelf.$('.js-notification').outerHeight(true), $parent = $(self).parent(); bbSelf.$el.css({height: height}); if ($parent.parent().hasClass('js-bb-notification')) { $parent.parent().fadeOut(200, function () { $(this).remove(); bbSelf.$el.slideUp(250, function () { $(this).show().css({height: "auto"}); }); }); } else { $parent.fadeOut(200, function () { $(this).remove(); bbSelf.$el.slideUp(250, function () { $(this).show().css({height: "auto"}); }); }); } }); } }); // ## Modals Ghost.Views.Modal = Ghost.View.extend({ el: '#modal-container', templateName: 'modal', className: 'js-bb-modal', // Render and manages modal dismissal initialize: function () { this.render(); var self = this; if (this.model.options.close) { shortcut.add("ESC", function () { self.removeElement(); }); $(document).on('click', '.modal-background', function () { self.removeElement(); }); } else { shortcut.remove("ESC"); $(document).off('click', '.modal-background'); } if (this.model.options.confirm) { // Initiate functions for buttons here so models don't get tied up. this.acceptModal = function () { this.model.options.confirm.accept.func.call(this); self.removeElement(); }; this.rejectModal = function () { this.model.options.confirm.reject.func.call(this); self.removeElement(); }; } }, templateData: function () { return this.model; }, events: { 'click .close': 'removeElement', 'click .js-button-accept': 'acceptModal', 'click .js-button-reject': 'rejectModal' }, afterRender: function () { this.$el.fadeIn(50); $(".modal-background").show(10, function () { $(this).addClass("in"); }); if (this.model.options.confirm) { this.$('.close').remove(); } this.$(".modal-body").html(this.addSubview(new Ghost.Views.Modal.ContentView({model: this.model})).render().el); // if (document.body.style.webkitFilter !== undefined) { // Detect webkit filters // $("body").addClass("blur"); // Removed due to poor performance in Chrome // } if (_.isFunction(this.model.options.afterRender)) { this.model.options.afterRender.call(this); } if (this.model.options.animation) { this.animate(this.$el.children(".js-modal")); } }, // #### remove // Removes Backbone attachments from modals remove: function () { this.undelegateEvents(); this.$el.empty(); this.stopListening(); return this; }, // #### removeElement // Visually removes the modal from the user interface removeElement: function (e) { if (e) { e.preventDefault(); e.stopPropagation(); } var self = this, $jsModal = $('.js-modal'), removeModalDelay = $jsModal.transitionDuration(), removeBackgroundDelay = self.$el.transitionDuration(); $jsModal.removeClass('in'); if (!this.model.options.animation) { removeModalDelay = removeBackgroundDelay = 0; } setTimeout(function () { if (document.body.style.filter !== undefined) { $("body").removeClass("blur"); } $(".modal-background").removeClass('in'); setTimeout(function () { self.remove(); self.$el.hide(); $(".modal-background").hide(); }, removeBackgroundDelay); }, removeModalDelay); }, // #### animate // Animates the animation animate: function (target) { setTimeout(function () { target.addClass('in'); }, target.transitionDuration()); } }); // ## Modal Content Ghost.Views.Modal.ContentView = Ghost.View.extend({ template: function (data) { return JST['modals/' + this.model.content.template](data); }, templateData: function () { return this.model; } }); }());
/*! * @overview Ember - JavaScript Application Framework * @copyright Copyright 2011-2015 Tilde Inc. and contributors * Portions Copyright 2006-2011 Strobe Inc. * Portions Copyright 2008-2011 Apple Inc. All rights reserved. * @license Licensed under MIT license * See https://raw.github.com/emberjs/ember.js/master/LICENSE * @version 1.13.7 */ (function() { var enifed, requireModule, eriuqer, requirejs, Ember; var mainContext = this; (function() { var isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; if (!isNode) { Ember = this.Ember = this.Ember || {}; } if (typeof Ember === 'undefined') { Ember = {}; }; if (typeof Ember.__loader === 'undefined') { var registry = {}; var seen = {}; enifed = function(name, deps, callback) { var value = { }; if (!callback) { value.deps = []; value.callback = deps; } else { value.deps = deps; value.callback = callback; } registry[name] = value; }; requirejs = eriuqer = requireModule = function(name) { return internalRequire(name, null); } function internalRequire(name, referrerName) { var exports = seen[name]; if (exports !== undefined) { return exports; } exports = seen[name] = {}; if (!registry[name]) { if (referrerName) { throw new Error('Could not find module ' + name + ' required by: ' + referrerName); } else { throw new Error('Could not find module ' + name); } } var mod = registry[name]; var deps = mod.deps; var callback = mod.callback; var reified = []; var length = deps.length; for (var i=0; i<length; i++) { if (deps[i] === 'exports') { reified.push(exports); } else { reified.push(internalRequire(resolve(deps[i], name), name)); } } callback.apply(this, reified); return exports; }; function resolve(child, name) { 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('/'); } requirejs._eak_seen = registry; Ember.__loader = { define: enifed, require: eriuqer, registry: registry }; } else { enifed = Ember.__loader.define; requirejs = eriuqer = requireModule = Ember.__loader.require; } })(); enifed("ember-debug", ["exports", "ember-metal/core", "ember-metal/error", "ember-metal/logger", "ember-debug/deprecation-manager", "ember-metal/environment"], function (exports, _emberMetalCore, _emberMetalError, _emberMetalLogger, _emberDebugDeprecationManager, _emberMetalEnvironment) { /*global __fail__*/ "use strict"; exports._warnIfUsingStrippedFeatureFlags = _warnIfUsingStrippedFeatureFlags; /** @module ember @submodule ember-debug */ /** @class Ember @public */ function isPlainFunction(test) { return typeof test === 'function' && test.PrototypeMixin === undefined; } /** Define an assertion that will throw an exception if the condition is not met. Ember build tools will remove any calls to `Ember.assert()` when doing a production build. Example: ```javascript // Test for truthiness Ember.assert('Must pass a valid object', obj); // Fail unconditionally Ember.assert('This code path should never be run'); ``` @method assert @param {String} desc A description of the assertion. This will become the text of the Error thrown if the assertion fails. @param {Boolean|Function} test Must be truthy for the assertion to pass. If falsy, an exception will be thrown. If this is a function, it will be executed and its return value will be used as condition. @public */ _emberMetalCore["default"].assert = function (desc, test) { var throwAssertion; if (isPlainFunction(test)) { throwAssertion = !test(); } else { throwAssertion = !test; } if (throwAssertion) { throw new _emberMetalError["default"]("Assertion Failed: " + desc); } }; /** Display a warning with the provided message. Ember build tools will remove any calls to `Ember.warn()` when doing a production build. @method warn @param {String} message A warning to display. @param {Boolean} test An optional boolean. If falsy, the warning will be displayed. @public */ _emberMetalCore["default"].warn = function (message, test) { if (!test) { _emberMetalLogger["default"].warn("WARNING: " + message); if ('trace' in _emberMetalLogger["default"]) { _emberMetalLogger["default"].trace(); } } }; /** Display a debug notice. Ember build tools will remove any calls to `Ember.debug()` when doing a production build. ```javascript Ember.debug('I\'m a debug notice!'); ``` @method debug @param {String} message A debug message to display. @public */ _emberMetalCore["default"].debug = function (message) { _emberMetalLogger["default"].debug("DEBUG: " + message); }; /** Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only). Ember build tools will remove any calls to `Ember.deprecate()` when doing a production build. @method deprecate @param {String} message A description of the deprecation. @param {Boolean|Function} test An optional boolean. If falsy, the deprecation will be displayed. If this is a function, it will be executed and its return value will be used as condition. @param {Object} options An optional object that can be used to pass in a `url` to the transition guide on the emberjs.com website, and a unique `id` for this deprecation. The `id` can be used by Ember debugging tools to change the behavior (raise, log or silence) for that specific deprecation. The `id` should be namespaced by dots, e.g. "view.helper.select". @public */ _emberMetalCore["default"].deprecate = function (message, test, options) { if (_emberMetalCore["default"].ENV.RAISE_ON_DEPRECATION) { _emberDebugDeprecationManager["default"].setDefaultLevel(_emberDebugDeprecationManager.deprecationLevels.RAISE); } if (_emberDebugDeprecationManager["default"].getLevel(options && options.id) === _emberDebugDeprecationManager.deprecationLevels.SILENCE) { return; } var noDeprecation; if (isPlainFunction(test)) { noDeprecation = test(); } else { noDeprecation = test; } if (noDeprecation) { return; } if (options && options.id) { message = message + (" [deprecation id: " + options.id + "]"); } if (_emberDebugDeprecationManager["default"].getLevel(options && options.id) === _emberDebugDeprecationManager.deprecationLevels.RAISE) { throw new _emberMetalError["default"](message); } var error; // When using new Error, we can't do the arguments check for Chrome. Alternatives are welcome try { __fail__.fail(); } catch (e) { error = e; } if (arguments.length === 3) { _emberMetalCore["default"].assert('options argument to Ember.deprecate should be an object', options && typeof options === 'object'); if (options.url) { message += ' See ' + options.url + ' for more details.'; } } if (_emberMetalCore["default"].LOG_STACKTRACE_ON_DEPRECATION && error.stack) { var stack; var stackStr = ''; if (error['arguments']) { // Chrome stack = error.stack.replace(/^\s+at\s+/gm, '').replace(/^([^\(]+?)([\n$])/gm, '{anonymous}($1)$2').replace(/^Object.<anonymous>\s*\(([^\)]+)\)/gm, '{anonymous}($1)').split('\n'); stack.shift(); } else { // Firefox stack = error.stack.replace(/(?:\n@:0)?\s+$/m, '').replace(/^\(/gm, '{anonymous}(').split('\n'); } stackStr = "\n " + stack.slice(2).join("\n "); message = message + stackStr; } _emberMetalLogger["default"].warn("DEPRECATION: " + message); }; /** Alias an old, deprecated method with its new counterpart. Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only) when the assigned method is called. Ember build tools will not remove calls to `Ember.deprecateFunc()`, though no warnings will be shown in production. ```javascript Ember.oldMethod = Ember.deprecateFunc('Please use the new, updated method', Ember.newMethod); ``` @method deprecateFunc @param {String} message A description of the deprecation. @param {Object} [options] The options object for Ember.deprecate. @param {Function} func The new function called to replace its deprecated counterpart. @return {Function} a new function that wrapped the original function with a deprecation warning @private */ _emberMetalCore["default"].deprecateFunc = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args.length === 3) { var _ret = (function () { var message = args[0]; var options = args[1]; var func = args[2]; return { v: function () { _emberMetalCore["default"].deprecate(message, false, options); return func.apply(this, arguments); } }; })(); if (typeof _ret === "object") return _ret.v; } else { var _ret2 = (function () { var message = args[0]; var func = args[1]; return { v: function () { _emberMetalCore["default"].deprecate(message); return func.apply(this, arguments); } }; })(); if (typeof _ret2 === "object") return _ret2.v; } }; /** Run a function meant for debugging. Ember build tools will remove any calls to `Ember.runInDebug()` when doing a production build. ```javascript Ember.runInDebug(() => { Ember.Component.reopen({ didInsertElement() { console.log("I'm happy"); } }); }); ``` @method runInDebug @param {Function} func The function to be executed. @since 1.5.0 @public */ _emberMetalCore["default"].runInDebug = function (func) { func(); }; /** Will call `Ember.warn()` if ENABLE_ALL_FEATURES, ENABLE_OPTIONAL_FEATURES, or any specific FEATURES flag is truthy. This method is called automatically in debug canary builds. @private @method _warnIfUsingStrippedFeatureFlags @return {void} */ function _warnIfUsingStrippedFeatureFlags(FEATURES, featuresWereStripped) { if (featuresWereStripped) { _emberMetalCore["default"].warn('Ember.ENV.ENABLE_ALL_FEATURES is only available in canary builds.', !_emberMetalCore["default"].ENV.ENABLE_ALL_FEATURES); _emberMetalCore["default"].warn('Ember.ENV.ENABLE_OPTIONAL_FEATURES is only available in canary builds.', !_emberMetalCore["default"].ENV.ENABLE_OPTIONAL_FEATURES); for (var key in FEATURES) { if (FEATURES.hasOwnProperty(key) && key !== 'isEnabled') { _emberMetalCore["default"].warn('FEATURE["' + key + '"] is set as enabled, but FEATURE flags are only available in canary builds.', !FEATURES[key]); } } } } if (!_emberMetalCore["default"].testing) { // Complain if they're using FEATURE flags in builds other than canary _emberMetalCore["default"].FEATURES['features-stripped-test'] = true; var featuresWereStripped = true; delete _emberMetalCore["default"].FEATURES['features-stripped-test']; _warnIfUsingStrippedFeatureFlags(_emberMetalCore["default"].ENV.FEATURES, featuresWereStripped); // Inform the developer about the Ember Inspector if not installed. var isFirefox = _emberMetalEnvironment["default"].isFirefox; var isChrome = _emberMetalEnvironment["default"].isChrome; if (typeof window !== 'undefined' && (isFirefox || isChrome) && window.addEventListener) { window.addEventListener("load", function () { if (document.documentElement && document.documentElement.dataset && !document.documentElement.dataset.emberExtension) { var downloadURL; if (isChrome) { downloadURL = 'https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi'; } else if (isFirefox) { downloadURL = 'https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/'; } _emberMetalCore["default"].debug('For more advanced debugging, install the Ember Inspector from ' + downloadURL); } }, false); } } _emberMetalCore["default"].Debug = { _addDeprecationLevel: function (id, level) { _emberDebugDeprecationManager["default"].setLevel(id, level); }, _deprecationLevels: _emberDebugDeprecationManager.deprecationLevels }; /* We are transitioning away from `ember.js` to `ember.debug.js` to make it much clearer that it is only for local development purposes. This flag value is changed by the tooling (by a simple string replacement) so that if `ember.js` (which must be output for backwards compat reasons) is used a nice helpful warning message will be printed out. */ var runningNonEmberDebugJS = false; exports.runningNonEmberDebugJS = runningNonEmberDebugJS; if (runningNonEmberDebugJS) { _emberMetalCore["default"].warn('Please use `ember.debug.js` instead of `ember.js` for development and debugging.'); } }); enifed('ember-debug/deprecation-manager', ['exports', 'ember-metal/dictionary', 'ember-metal/utils'], function (exports, _emberMetalDictionary, _emberMetalUtils) { 'use strict'; var deprecationLevels = { RAISE: _emberMetalUtils.symbol('RAISE'), LOG: _emberMetalUtils.symbol('LOG'), SILENCE: _emberMetalUtils.symbol('SILENCE') }; exports.deprecationLevels = deprecationLevels; exports["default"] = { defaultLevel: deprecationLevels.LOG, individualLevels: _emberMetalDictionary["default"](null), setDefaultLevel: function (level) { this.defaultLevel = level; }, setLevel: function (id, level) { this.individualLevels[id] = level; }, getLevel: function (id) { var level = this.individualLevels[id]; if (!level) { level = this.defaultLevel; } return level; } }; }); enifed("ember-testing", ["exports", "ember-metal/core", "ember-testing/initializers", "ember-testing/support", "ember-testing/setup_for_testing", "ember-testing/test", "ember-testing/adapters/adapter", "ember-testing/adapters/qunit", "ember-testing/helpers"], function (exports, _emberMetalCore, _emberTestingInitializers, _emberTestingSupport, _emberTestingSetup_for_testing, _emberTestingTest, _emberTestingAdaptersAdapter, _emberTestingAdaptersQunit, _emberTestingHelpers) { "use strict"; // adds helpers to helpers object in Test /** @module ember @submodule ember-testing */ _emberMetalCore["default"].Test = _emberTestingTest["default"]; _emberMetalCore["default"].Test.Adapter = _emberTestingAdaptersAdapter["default"]; _emberMetalCore["default"].Test.QUnitAdapter = _emberTestingAdaptersQunit["default"]; _emberMetalCore["default"].setupForTesting = _emberTestingSetup_for_testing["default"]; }); // to setup initializer // to handle various edge cases enifed("ember-testing/adapters/adapter", ["exports", "ember-runtime/system/object"], function (exports, _emberRuntimeSystemObject) { "use strict"; function K() { return this; } /** @module ember @submodule ember-testing */ /** The primary purpose of this class is to create hooks that can be implemented by an adapter for various test frameworks. @class Adapter @namespace Ember.Test @public */ var Adapter = _emberRuntimeSystemObject["default"].extend({ /** This callback will be called whenever an async operation is about to start. Override this to call your framework's methods that handle async operations. @public @method asyncStart */ asyncStart: K, /** This callback will be called whenever an async operation has completed. @public @method asyncEnd */ asyncEnd: K, /** Override this method with your testing framework's false assertion. This function is called whenever an exception occurs causing the testing promise to fail. QUnit example: ```javascript exception: function(error) { ok(false, error); }; ``` @public @method exception @param {String} error The exception to be raised. */ exception: function (error) { throw error; } }); exports["default"] = Adapter; }); enifed("ember-testing/adapters/qunit", ["exports", "ember-testing/adapters/adapter", "ember-metal/utils"], function (exports, _emberTestingAdaptersAdapter, _emberMetalUtils) { "use strict"; /** This class implements the methods defined by Ember.Test.Adapter for the QUnit testing framework. @class QUnitAdapter @namespace Ember.Test @extends Ember.Test.Adapter @public */ exports["default"] = _emberTestingAdaptersAdapter["default"].extend({ asyncStart: function () { QUnit.stop(); }, asyncEnd: function () { QUnit.start(); }, exception: function (error) { ok(false, _emberMetalUtils.inspect(error)); } }); }); enifed("ember-testing/helpers", ["exports", "ember-metal/core", "ember-metal/property_get", "ember-metal/error", "ember-metal/run_loop", "ember-views/system/jquery", "ember-testing/test", "ember-runtime/ext/rsvp"], function (exports, _emberMetalCore, _emberMetalProperty_get, _emberMetalError, _emberMetalRun_loop, _emberViewsSystemJquery, _emberTestingTest, _emberRuntimeExtRsvp) { "use strict"; /** @module ember @submodule ember-testing */ var helper = _emberTestingTest["default"].registerHelper; var asyncHelper = _emberTestingTest["default"].registerAsyncHelper; function currentRouteName(app) { var appController = app.__container__.lookup('controller:application'); return _emberMetalProperty_get.get(appController, 'currentRouteName'); } function currentPath(app) { var appController = app.__container__.lookup('controller:application'); return _emberMetalProperty_get.get(appController, 'currentPath'); } function currentURL(app) { var router = app.__container__.lookup('router:main'); return _emberMetalProperty_get.get(router, 'location').getURL(); } function pauseTest() { _emberTestingTest["default"].adapter.asyncStart(); return new _emberMetalCore["default"].RSVP.Promise(function () {}, 'TestAdapter paused promise'); } function focus(el) { if (el && el.is(':input, [contenteditable=true]')) { var type = el.prop('type'); if (type !== 'checkbox' && type !== 'radio' && type !== 'hidden') { _emberMetalRun_loop["default"](el, function () { // Firefox does not trigger the `focusin` event if the window // does not have focus. If the document doesn't have focus just // use trigger('focusin') instead. if (!document.hasFocus || document.hasFocus()) { this.focus(); } else { this.trigger('focusin'); } }); } } } function visit(app, url) { var router = app.__container__.lookup('router:main'); var shouldHandleURL = false; app.boot().then(function () { router.location.setURL(url); if (shouldHandleURL) { _emberMetalRun_loop["default"](app.__deprecatedInstance__, 'handleURL', url); } }); if (app._readinessDeferrals > 0) { router['initialURL'] = url; _emberMetalRun_loop["default"](app, 'advanceReadiness'); delete router['initialURL']; } else { shouldHandleURL = true; } return app.testHelpers.wait(); } function click(app, selector, context) { var $el = app.testHelpers.findWithAssert(selector, context); _emberMetalRun_loop["default"]($el, 'mousedown'); focus($el); _emberMetalRun_loop["default"]($el, 'mouseup'); _emberMetalRun_loop["default"]($el, 'click'); return app.testHelpers.wait(); } function check(app, selector, context) { var $el = app.testHelpers.findWithAssert(selector, context); var type = $el.prop('type'); _emberMetalCore["default"].assert('To check \'' + selector + '\', the input must be a checkbox', type === 'checkbox'); if (!$el.prop('checked')) { app.testHelpers.click(selector, context); } return app.testHelpers.wait(); } function uncheck(app, selector, context) { var $el = app.testHelpers.findWithAssert(selector, context); var type = $el.prop('type'); _emberMetalCore["default"].assert('To uncheck \'' + selector + '\', the input must be a checkbox', type === 'checkbox'); if ($el.prop('checked')) { app.testHelpers.click(selector, context); } return app.testHelpers.wait(); } function triggerEvent(app, selector, contextOrType, typeOrOptions, possibleOptions) { var arity = arguments.length; var context, type, options; if (arity === 3) { // context and options are optional, so this is // app, selector, type context = null; type = contextOrType; options = {}; } else if (arity === 4) { // context and options are optional, so this is if (typeof typeOrOptions === "object") { // either // app, selector, type, options context = null; type = contextOrType; options = typeOrOptions; } else { // or // app, selector, context, type context = contextOrType; type = typeOrOptions; options = {}; } } else { context = contextOrType; type = typeOrOptions; options = possibleOptions; } var $el = app.testHelpers.findWithAssert(selector, context); var event = _emberViewsSystemJquery["default"].Event(type, options); _emberMetalRun_loop["default"]($el, 'trigger', event); return app.testHelpers.wait(); } function keyEvent(app, selector, contextOrType, typeOrKeyCode, keyCode) { var context, type; if (typeof keyCode === 'undefined') { context = null; keyCode = typeOrKeyCode; type = contextOrType; } else { context = contextOrType; type = typeOrKeyCode; } return app.testHelpers.triggerEvent(selector, context, type, { keyCode: keyCode, which: keyCode }); } function fillIn(app, selector, contextOrText, text) { var $el, context; if (typeof text === 'undefined') { text = contextOrText; } else { context = contextOrText; } $el = app.testHelpers.findWithAssert(selector, context); focus($el); _emberMetalRun_loop["default"](function () { $el.val(text).change(); }); return app.testHelpers.wait(); } function findWithAssert(app, selector, context) { var $el = app.testHelpers.find(selector, context); if ($el.length === 0) { throw new _emberMetalError["default"]("Element " + selector + " not found."); } return $el; } function find(app, selector, context) { var $el; context = context || _emberMetalProperty_get.get(app, 'rootElement'); $el = app.$(selector, context); return $el; } function andThen(app, callback) { return app.testHelpers.wait(callback(app)); } function wait(app, value) { return new _emberRuntimeExtRsvp["default"].Promise(function (resolve) { // Every 10ms, poll for the async thing to have finished var watcher = setInterval(function () { var router = app.__container__.lookup('router:main'); // 1. If the router is loading, keep polling var routerIsLoading = router.router && !!router.router.activeTransition; if (routerIsLoading) { return; } // 2. If there are pending Ajax requests, keep polling if (_emberTestingTest["default"].pendingAjaxRequests) { return; } // 3. If there are scheduled timers or we are inside of a run loop, keep polling if (_emberMetalRun_loop["default"].hasScheduledTimers() || _emberMetalRun_loop["default"].currentRunLoop) { return; } if (_emberTestingTest["default"].waiters && _emberTestingTest["default"].waiters.any(function (waiter) { var context = waiter[0]; var callback = waiter[1]; return !callback.call(context); })) { return; } // Stop polling clearInterval(watcher); // Synchronously resolve the promise _emberMetalRun_loop["default"](null, resolve, value); }, 10); }); } /** Loads a route, sets up any controllers, and renders any templates associated with the route as though a real user had triggered the route change while using your app. Example: ```javascript visit('posts/index').then(function() { // assert something }); ``` @method visit @param {String} url the name of the route @return {RSVP.Promise} @public */ asyncHelper('visit', visit); /** Clicks an element and triggers any actions triggered by the element's `click` event. Example: ```javascript click('.some-jQuery-selector').then(function() { // assert something }); ``` @method click @param {String} selector jQuery selector for finding element on the DOM @return {RSVP.Promise} @public */ asyncHelper('click', click); /** Simulates a key event, e.g. `keypress`, `keydown`, `keyup` with the desired keyCode Example: ```javascript keyEvent('.some-jQuery-selector', 'keypress', 13).then(function() { // assert something }); ``` @method keyEvent @param {String} selector jQuery selector for finding element on the DOM @param {String} type the type of key event, e.g. `keypress`, `keydown`, `keyup` @param {Number} keyCode the keyCode of the simulated key event @return {RSVP.Promise} @since 1.5.0 @public */ asyncHelper('keyEvent', keyEvent); /** Fills in an input element with some text. Example: ```javascript fillIn('#email', 'you@example.com').then(function() { // assert something }); ``` @method fillIn @param {String} selector jQuery selector finding an input element on the DOM to fill text with @param {String} text text to place inside the input element @return {RSVP.Promise} @public */ asyncHelper('fillIn', fillIn); /** Finds an element in the context of the app's container element. A simple alias for `app.$(selector)`. Example: ```javascript var $el = find('.my-selector'); ``` @method find @param {String} selector jQuery string selector for element lookup @return {Object} jQuery object representing the results of the query @public */ helper('find', find); /** Like `find`, but throws an error if the element selector returns no results. Example: ```javascript var $el = findWithAssert('.doesnt-exist'); // throws error ``` @method findWithAssert @param {String} selector jQuery selector string for finding an element within the DOM @return {Object} jQuery object representing the results of the query @throws {Error} throws error if jQuery object returned has a length of 0 @public */ helper('findWithAssert', findWithAssert); /** Causes the run loop to process any pending events. This is used to ensure that any async operations from other helpers (or your assertions) have been processed. This is most often used as the return value for the helper functions (see 'click', 'fillIn','visit',etc). Example: ```javascript Ember.Test.registerAsyncHelper('loginUser', function(app, username, password) { visit('secured/path/here') .fillIn('#username', username) .fillIn('#password', password) .click('.submit') return app.testHelpers.wait(); }); @method wait @param {Object} value The value to be returned. @return {RSVP.Promise} @public */ asyncHelper('wait', wait); asyncHelper('andThen', andThen); /** Returns the currently active route name. Example: ```javascript function validateRouteName() { equal(currentRouteName(), 'some.path', "correct route was transitioned into."); } visit('/some/path').then(validateRouteName) ``` @method currentRouteName @return {Object} The name of the currently active route. @since 1.5.0 @public */ helper('currentRouteName', currentRouteName); /** Returns the current path. Example: ```javascript function validateURL() { equal(currentPath(), 'some.path.index', "correct path was transitioned into."); } click('#some-link-id').then(validateURL); ``` @method currentPath @return {Object} The currently active path. @since 1.5.0 @public */ helper('currentPath', currentPath); /** Returns the current URL. Example: ```javascript function validateURL() { equal(currentURL(), '/some/path', "correct URL was transitioned into."); } click('#some-link-id').then(validateURL); ``` @method currentURL @return {Object} The currently active URL. @since 1.5.0 @public */ helper('currentURL', currentURL); /** Pauses the current test - this is useful for debugging while testing or for test-driving. It allows you to inspect the state of your application at any point. Example (The test will pause before clicking the button): ```javascript visit('/') return pauseTest(); click('.btn'); ``` @since 1.9.0 @method pauseTest @return {Object} A promise that will never resolve @public */ helper('pauseTest', pauseTest); /** Triggers the given DOM event on the element identified by the provided selector. Example: ```javascript triggerEvent('#some-elem-id', 'blur'); ``` This is actually used internally by the `keyEvent` helper like so: ```javascript triggerEvent('#some-elem-id', 'keypress', { keyCode: 13 }); ``` @method triggerEvent @param {String} selector jQuery selector for finding element on the DOM @param {String} [context] jQuery selector that will limit the selector argument to find only within the context's children @param {String} type The event type to be triggered. @param {Object} [options] The options to be passed to jQuery.Event. @return {RSVP.Promise} @since 1.5.0 @public */ asyncHelper('triggerEvent', triggerEvent); }); enifed('ember-testing/initializers', ['exports', 'ember-runtime/system/lazy_load'], function (exports, _emberRuntimeSystemLazy_load) { 'use strict'; var name = 'deferReadiness in `testing` mode'; _emberRuntimeSystemLazy_load.onLoad('Ember.Application', function (Application) { if (!Application.initializers[name]) { Application.initializer({ name: name, initialize: function (registry, application) { if (application.testing) { application.deferReadiness(); } } }); } }); }); enifed("ember-testing/setup_for_testing", ["exports", "ember-metal/core", "ember-testing/adapters/qunit", "ember-views/system/jquery"], function (exports, _emberMetalCore, _emberTestingAdaptersQunit, _emberViewsSystemJquery) { "use strict"; exports["default"] = setupForTesting; var Test, requests; function incrementAjaxPendingRequests(_, xhr) { requests.push(xhr); Test.pendingAjaxRequests = requests.length; } function decrementAjaxPendingRequests(_, xhr) { for (var i = 0; i < requests.length; i++) { if (xhr === requests[i]) { requests.splice(i, 1); } } Test.pendingAjaxRequests = requests.length; } /** Sets Ember up for testing. This is useful to perform basic setup steps in order to unit test. Use `App.setupForTesting` to perform integration tests (full application testing). @method setupForTesting @namespace Ember @since 1.5.0 @private */ function setupForTesting() { if (!Test) { Test = requireModule('ember-testing/test')['default']; } _emberMetalCore["default"].testing = true; // if adapter is not manually set default to QUnit if (!Test.adapter) { Test.adapter = _emberTestingAdaptersQunit["default"].create(); } requests = []; Test.pendingAjaxRequests = requests.length; _emberViewsSystemJquery["default"](document).off('ajaxSend', incrementAjaxPendingRequests); _emberViewsSystemJquery["default"](document).off('ajaxComplete', decrementAjaxPendingRequests); _emberViewsSystemJquery["default"](document).on('ajaxSend', incrementAjaxPendingRequests); _emberViewsSystemJquery["default"](document).on('ajaxComplete', decrementAjaxPendingRequests); } }); // import Test from "ember-testing/test"; // ES6TODO: fix when cycles are supported enifed("ember-testing/support", ["exports", "ember-metal/core", "ember-views/system/jquery", "ember-metal/environment"], function (exports, _emberMetalCore, _emberViewsSystemJquery, _emberMetalEnvironment) { "use strict"; /** @module ember @submodule ember-testing */ var $ = _emberViewsSystemJquery["default"]; /** This method creates a checkbox and triggers the click event to fire the passed in handler. It is used to correct for a bug in older versions of jQuery (e.g 1.8.3). @private @method testCheckboxClick */ function testCheckboxClick(handler) { $('<input type="checkbox">').css({ position: 'absolute', left: '-1000px', top: '-1000px' }).appendTo('body').on('click', handler).trigger('click').remove(); } if (_emberMetalEnvironment["default"].hasDOM) { $(function () { /* Determine whether a checkbox checked using jQuery's "click" method will have the correct value for its checked property. If we determine that the current jQuery version exhibits this behavior, patch it to work correctly as in the commit for the actual fix: https://github.com/jquery/jquery/commit/1fb2f92. */ testCheckboxClick(function () { if (!this.checked && !$.event.special.click) { $.event.special.click = { // For checkbox, fire native event so checked state will be right trigger: function () { if ($.nodeName(this, "input") && this.type === "checkbox" && this.click) { this.click(); return false; } } }; } }); // Try again to verify that the patch took effect or blow up. testCheckboxClick(function () { _emberMetalCore["default"].warn("clicked checkboxes should be checked! the jQuery patch didn't work", this.checked); }); }); } }); enifed("ember-testing/test", ["exports", "ember-metal/core", "ember-metal/run_loop", "ember-metal/platform/create", "ember-runtime/ext/rsvp", "ember-testing/setup_for_testing", "ember-application/system/application"], function (exports, _emberMetalCore, _emberMetalRun_loop, _emberMetalPlatformCreate, _emberRuntimeExtRsvp, _emberTestingSetup_for_testing, _emberApplicationSystemApplication) { "use strict"; /** @module ember @submodule ember-testing */ var helpers = {}; var injectHelpersCallbacks = []; /** This is a container for an assortment of testing related functionality: * Choose your default test adapter (for your framework of choice). * Register/Unregister additional test helpers. * Setup callbacks to be fired when the test helpers are injected into your application. @class Test @namespace Ember @public */ var Test = { /** Hash containing all known test helpers. @property _helpers @private @since 1.7.0 */ _helpers: helpers, /** `registerHelper` is used to register a test helper that will be injected when `App.injectTestHelpers` is called. The helper method will always be called with the current Application as the first parameter. For example: ```javascript Ember.Test.registerHelper('boot', function(app) { Ember.run(app, app.advanceReadiness); }); ``` This helper can later be called without arguments because it will be called with `app` as the first parameter. ```javascript App = Ember.Application.create(); App.injectTestHelpers(); boot(); ``` @public @method registerHelper @param {String} name The name of the helper method to add. @param {Function} helperMethod @param options {Object} */ registerHelper: function (name, helperMethod) { helpers[name] = { method: helperMethod, meta: { wait: false } }; }, /** `registerAsyncHelper` is used to register an async test helper that will be injected when `App.injectTestHelpers` is called. The helper method will always be called with the current Application as the first parameter. For example: ```javascript Ember.Test.registerAsyncHelper('boot', function(app) { Ember.run(app, app.advanceReadiness); }); ``` The advantage of an async helper is that it will not run until the last async helper has completed. All async helpers after it will wait for it complete before running. For example: ```javascript Ember.Test.registerAsyncHelper('deletePost', function(app, postId) { click('.delete-' + postId); }); // ... in your test visit('/post/2'); deletePost(2); visit('/post/3'); deletePost(3); ``` @public @method registerAsyncHelper @param {String} name The name of the helper method to add. @param {Function} helperMethod @since 1.2.0 */ registerAsyncHelper: function (name, helperMethod) { helpers[name] = { method: helperMethod, meta: { wait: true } }; }, /** Remove a previously added helper method. Example: ```javascript Ember.Test.unregisterHelper('wait'); ``` @public @method unregisterHelper @param {String} name The helper to remove. */ unregisterHelper: function (name) { delete helpers[name]; delete Test.Promise.prototype[name]; }, /** Used to register callbacks to be fired whenever `App.injectTestHelpers` is called. The callback will receive the current application as an argument. Example: ```javascript Ember.Test.onInjectHelpers(function() { Ember.$(document).ajaxSend(function() { Test.pendingAjaxRequests++; }); Ember.$(document).ajaxComplete(function() { Test.pendingAjaxRequests--; }); }); ``` @public @method onInjectHelpers @param {Function} callback The function to be called. */ onInjectHelpers: function (callback) { injectHelpersCallbacks.push(callback); }, /** This returns a thenable tailored for testing. It catches failed `onSuccess` callbacks and invokes the `Ember.Test.adapter.exception` callback in the last chained then. This method should be returned by async helpers such as `wait`. @public @method promise @param {Function} resolver The function used to resolve the promise. @param {String} label An optional string for identifying the promise. */ promise: function (resolver, label) { var fullLabel = "Ember.Test.promise: " + (label || "<Unknown Promise>"); return new Test.Promise(resolver, fullLabel); }, /** Used to allow ember-testing to communicate with a specific testing framework. You can manually set it before calling `App.setupForTesting()`. Example: ```javascript Ember.Test.adapter = MyCustomAdapter.create() ``` If you do not set it, ember-testing will default to `Ember.Test.QUnitAdapter`. @public @property adapter @type {Class} The adapter to be used. @default Ember.Test.QUnitAdapter */ adapter: null, /** Replacement for `Ember.RSVP.resolve` The only difference is this uses an instance of `Ember.Test.Promise` @public @method resolve @param {Mixed} The value to resolve @since 1.2.0 */ resolve: function (val) { return Test.promise(function (resolve) { return resolve(val); }); }, /** This allows ember-testing to play nicely with other asynchronous events, such as an application that is waiting for a CSS3 transition or an IndexDB transaction. For example: ```javascript Ember.Test.registerWaiter(function() { return myPendingTransactions() == 0; }); ``` The `context` argument allows you to optionally specify the `this` with which your callback will be invoked. For example: ```javascript Ember.Test.registerWaiter(MyDB, MyDB.hasPendingTransactions); ``` @public @method registerWaiter @param {Object} context (optional) @param {Function} callback @since 1.2.0 */ registerWaiter: function (context, callback) { if (arguments.length === 1) { callback = context; context = null; } if (!this.waiters) { this.waiters = _emberMetalCore["default"].A(); } this.waiters.push([context, callback]); }, /** `unregisterWaiter` is used to unregister a callback that was registered with `registerWaiter`. @public @method unregisterWaiter @param {Object} context (optional) @param {Function} callback @since 1.2.0 */ unregisterWaiter: function (context, callback) { if (!this.waiters) { return; } if (arguments.length === 1) { callback = context; context = null; } this.waiters = _emberMetalCore["default"].A(this.waiters.filter(function (elt) { return !(elt[0] === context && elt[1] === callback); })); } }; function helper(app, name) { var fn = helpers[name].method; var meta = helpers[name].meta; return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var lastPromise; args.unshift(app); // some helpers are not async and // need to return a value immediately. // example: `find` if (!meta.wait) { return fn.apply(app, args); } lastPromise = run(function () { return Test.resolve(Test.lastPromise); }); // wait for last helper's promise to resolve and then // execute. To be safe, we need to tell the adapter we're going // asynchronous here, because fn may not be invoked before we // return. Test.adapter.asyncStart(); return lastPromise.then(function () { return fn.apply(app, args); })["finally"](function () { Test.adapter.asyncEnd(); }); }; } function run(fn) { if (!_emberMetalRun_loop["default"].currentRunLoop) { return _emberMetalRun_loop["default"](fn); } else { return fn(); } } _emberApplicationSystemApplication["default"].reopen({ /** This property contains the testing helpers for the current application. These are created once you call `injectTestHelpers` on your `Ember.Application` instance. The included helpers are also available on the `window` object by default, but can be used from this object on the individual application also. @property testHelpers @type {Object} @default {} @public */ testHelpers: {}, /** This property will contain the original methods that were registered on the `helperContainer` before `injectTestHelpers` is called. When `removeTestHelpers` is called, these methods are restored to the `helperContainer`. @property originalMethods @type {Object} @default {} @private @since 1.3.0 */ originalMethods: {}, /** This property indicates whether or not this application is currently in testing mode. This is set when `setupForTesting` is called on the current application. @property testing @type {Boolean} @default false @since 1.3.0 @public */ testing: false, /** This hook defers the readiness of the application, so that you can start the app when your tests are ready to run. It also sets the router's location to 'none', so that the window's location will not be modified (preventing both accidental leaking of state between tests and interference with your testing framework). Example: ``` App.setupForTesting(); ``` @method setupForTesting @public */ setupForTesting: function () { _emberTestingSetup_for_testing["default"](); this.testing = true; this.Router.reopen({ location: 'none' }); }, /** This will be used as the container to inject the test helpers into. By default the helpers are injected into `window`. @property helperContainer @type {Object} The object to be used for test helpers. @default window @since 1.2.0 @private */ helperContainer: null, /** This injects the test helpers into the `helperContainer` object. If an object is provided it will be used as the helperContainer. If `helperContainer` is not set it will default to `window`. If a function of the same name has already been defined it will be cached (so that it can be reset if the helper is removed with `unregisterHelper` or `removeTestHelpers`). Any callbacks registered with `onInjectHelpers` will be called once the helpers have been injected. Example: ``` App.injectTestHelpers(); ``` @method injectTestHelpers @public */ injectTestHelpers: function (helperContainer) { if (helperContainer) { this.helperContainer = helperContainer; } else { this.helperContainer = window; } this.reopen({ willDestroy: function () { this._super.apply(this, arguments); this.removeTestHelpers(); } }); this.testHelpers = {}; for (var name in helpers) { this.originalMethods[name] = this.helperContainer[name]; this.testHelpers[name] = this.helperContainer[name] = helper(this, name); protoWrap(Test.Promise.prototype, name, helper(this, name), helpers[name].meta.wait); } for (var i = 0, l = injectHelpersCallbacks.length; i < l; i++) { injectHelpersCallbacks[i](this); } }, /** This removes all helpers that have been registered, and resets and functions that were overridden by the helpers. Example: ```javascript App.removeTestHelpers(); ``` @public @method removeTestHelpers */ removeTestHelpers: function () { if (!this.helperContainer) { return; } for (var name in helpers) { this.helperContainer[name] = this.originalMethods[name]; delete Test.Promise.prototype[name]; delete this.testHelpers[name]; delete this.originalMethods[name]; } } }); // This method is no longer needed // But still here for backwards compatibility // of helper chaining function protoWrap(proto, name, callback, isAsync) { proto[name] = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } if (isAsync) { return callback.apply(this, args); } else { return this.then(function () { return callback.apply(this, args); }); } }; } Test.Promise = function () { _emberRuntimeExtRsvp["default"].Promise.apply(this, arguments); Test.lastPromise = this; }; Test.Promise.prototype = _emberMetalPlatformCreate["default"](_emberRuntimeExtRsvp["default"].Promise.prototype); Test.Promise.prototype.constructor = Test.Promise; Test.Promise.resolve = Test.resolve; // Patch `then` to isolate async methods // specifically `Ember.Test.lastPromise` var originalThen = _emberRuntimeExtRsvp["default"].Promise.prototype.then; Test.Promise.prototype.then = function (onSuccess, onFailure) { return originalThen.call(this, function (val) { return isolate(onSuccess, val); }, onFailure); }; // This method isolates nested async methods // so that they don't conflict with other last promises. // // 1. Set `Ember.Test.lastPromise` to null // 2. Invoke method // 3. Return the last promise created during method function isolate(fn, val) { var value, lastPromise; // Reset lastPromise for nested helpers Test.lastPromise = null; value = fn(val); lastPromise = Test.lastPromise; Test.lastPromise = null; // If the method returned a promise // return that promise. If not, // return the last async helper's promise if (value && value instanceof Test.Promise || !lastPromise) { return value; } else { return run(function () { return Test.resolve(lastPromise).then(function () { return value; }); }); } } exports["default"] = Test; }); requireModule("ember-testing"); })();
/** * @author mrdoob / http://mrdoob.com/ */ THREE.WebGLExtensions = function ( gl ) { var extensions = {}; this.get = function ( name ) { if ( extensions[ name ] !== undefined ) { return extensions[ name ]; } var extension; switch ( name ) { case 'EXT_texture_filter_anisotropic': extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); break; case 'WEBGL_compressed_texture_s3tc': extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); break; case 'WEBGL_compressed_texture_pvrtc': extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); break; default: extension = gl.getExtension( name ); } if ( extension === null ) { THREE.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); } extensions[ name ] = extension; return extension; }; };
YUI.add('datatable-mutable', function (Y, NAME) { /** Adds mutation convenience methods such as `table.addRow(data)` to `Y.DataTable`. (or other built class). @module datatable @submodule datatable-mutable @since 3.5.0 **/ var toArray = Y.Array, YLang = Y.Lang, isString = YLang.isString, isArray = YLang.isArray, isObject = YLang.isObject, isNumber = YLang.isNumber, arrayIndex = Y.Array.indexOf, Mutable; /** _API docs for this extension are included in the DataTable class._ Class extension to add mutation convenience methods to `Y.DataTable` (or other built class). Column mutation methods are paired with new custom events: * addColumn * removeColumn * modifyColumn * moveColumn Row mutation events are bubbled from the DataTable's `data` ModelList through the DataTable instance. @class DataTable.Mutable @for DataTable @since 3.5.0 **/ Y.namespace('DataTable').Mutable = Mutable = function () {}; Mutable.ATTRS = { /** Controls whether `addRow`, `removeRow`, and `modifyRow` should trigger the underlying Model's sync layer by default. When `true`, it is unnecessary to pass the "sync" configuration property to those methods to trigger per-operation sync. @attribute autoSync @type {Boolean} @default `false` @since 3.5.0 **/ autoSync: { value: false, validator: YLang.isBoolean } }; Y.mix(Mutable.prototype, { /** Adds the column configuration to the DataTable's `columns` configuration. If the `index` parameter is supplied, it is injected at that index. If the table has nested headers, inject a subcolumn by passing an array of indexes to identify the new column's final location. The `index` parameter is required if adding a nested column. This method is a convienience method for fetching the DataTable's `columns` attribute, updating it, and calling `table.set('columns', _updatedColumnsDefs_)` For example: <pre><code>// Becomes last column table.addColumn('name'); // Inserted after the current second column, moving the current third column // to index 4 table.addColumn({ key: 'price', formatter: currencyFormatter }, 2 ); // Insert a new column in a set of headers three rows deep. The index array // translates to // [ 2, -- in the third column's children // 1, -- in the second child's children // 3 ] -- as the fourth child column table.addColumn({ key: 'age', sortable: true }, [ 2, 1, 3 ]); </code></pre> @method addColumn @param {Object|String} config The new column configuration object @param {Number|Number[]} [index] the insertion index @return {DataTable} @chainable @since 3.5.0 **/ addColumn: function (config, index) { if (isString(config)) { config = { key: config }; } if (config) { if (arguments.length < 2 || (!isNumber(index) && !isArray(index))) { index = this.get('columns').length; } this.fire('addColumn', { column: config, index: index }); } return this; }, /** Updates an existing column definition. Fires the `modifyColumn` event. For example: <pre><code>// Add a formatter to the existing 'price' column definition table.modifyColumn('price', { formatter: currencyFormatter }); // Change the label on a header cell in a set of nested headers three rows // deep. The index array translates to // [ 2, -- in the third column's children // 1, -- the second child // 3 ] -- the fourth child column table.modifyColumn([2, 1, 3], { label: 'Experience' }); </code></pre> @method modifyColumn @param {String|Number|Number[]|Object} name The column key, name, index, or current configuration object @param {Object} config The new column configuration properties @return {DataTable} @chainable @since 3.5.0 **/ modifyColumn: function (name, config) { if (isString(config)) { config = { key: config }; } if (isObject(config)) { this.fire('modifyColumn', { column: name, newColumnDef: config }); } return this; }, /** Moves an existing column to a new location. Fires the `moveColumn` event. The destination index can be a number or array of numbers to place a column header in a nested header row. @method moveColumn @param {String|Number|Number[]|Object} name The column key, name, index, or current configuration object @param {Number|Number[]} index The destination index of the column @return {DataTable} @chainable @since 3.5.0 **/ moveColumn: function (name, index) { if (name !== undefined && (isNumber(index) || isArray(index))) { this.fire('moveColumn', { column: name, index: index }); } return this; }, /** Removes an existing column. Fires the `removeColumn` event. @method removeColumn @param {String|Number|Number[]|Object} name The column key, name, index, or current configuration object @return {DataTable} @chainable @since 3.5.0 **/ removeColumn: function (name) { if (name !== undefined) { this.fire('removeColumn', { column: name }); } return this; }, /** Adds a new record to the DataTable's `data` ModelList. Record data can be an object of field values or an instance of the DataTable's configured `recordType` class. This relays all parameters to the `data` ModelList's `add` method. If a configuration object is passed as a second argument, and that object has `sync: true` set, the underlying Model will be `save()`d. If the DataTable's `autoSync` attribute is set to `true`, the additional argument is not needed. If syncing and the last argument is a function, that function will be used as a callback to the Model's `save()` method. @method addRow @param {Object} data The data or Model instance for the new record @param {Object} [config] Configuration to pass along @param {Function} [callback] Callback function for Model's `save()` @param {Error|null} callback.err If an error occurred or validation failed, this parameter will contain the error. If the sync operation succeeded, _err_ will be `null`. @param {Any} callback.response The server's response. This value will be passed to the `parse()` method, which is expected to parse it and return an attribute hash. @return {DataTable} @chainable @since 3.5.0 **/ addRow: function (data, config) { // Allow autoSync: true + addRow({ data }, { sync: false }) var sync = (config && ('sync' in config)) ? config.sync : this.get('autoSync'), models, model, i, len, args; if (data && this.data) { models = this.data.add.apply(this.data, arguments); if (sync) { models = toArray(models); args = toArray(arguments, 1, true); for (i = 0, len = models.length; i < len; ++i) { model = models[i]; if (model.isNew()) { models[i].save.apply(models[i], args); } } } } return this; }, /** Removes a record from the DataTable's `data` ModelList. The record can be provided explicitly or targeted by it's `id` (see ModelList's `getById` method), `clientId`, or index in the ModelList. After locating the target Model, this relays the Model and all other passed arguments to the `data` ModelList's `remove` method. If a configuration object is passed as a second argument, and that object has `sync: true` set, the underlying Model will be destroyed, passing `{ delete: true }` to trigger calling the Model's sync layer. If the DataTable's `autoSync` attribute is set to `true`, the additional argument is not needed. If syncing and the last argument is a function, that function will be used as a callback to the Model's `destroy()` method. @method removeRow @param {Object|String|Number} id The Model instance or identifier @param {Object} [config] Configuration to pass along @param {Function} [callback] Callback function for Model's `save()` @param {Error|null} callback.err If an error occurred or validation failed, this parameter will contain the error. If the sync operation succeeded, _err_ will be `null`. @param {Any} callback.response The server's response. This value will be passed to the `parse()` method, which is expected to parse it and return an attribute hash. @return {DataTable} @chainable @since 3.5.0 **/ removeRow: function (id, config) { var modelList = this.data, // Allow autoSync: true + addRow({ data }, { sync: false }) sync = (config && ('sync' in config)) ? config.sync : this.get('autoSync'), models, model, i, len, args; // TODO: support removing via DOM element. This should be relayed to View if (isObject(id) && id instanceof this.get('recordType')) { model = id; } else if (modelList && id !== undefined) { model = modelList.getById(id) || modelList.getByClientId(id) || modelList.item(id); } if (model) { args = toArray(arguments, 1, true); models = modelList.remove.apply(modelList, [model].concat(args)); if (sync) { if (!isObject(args[0])) { args.unshift({}); } args[0]['delete'] = true; models = toArray(models); for (i = 0, len = models.length; i < len; ++i) { model = models[i]; model.destroy.apply(model, args); } } } return this; }, /** Updates an existing record in the DataTable's `data` ModelList. The record can be provided explicitly or targeted by it's `id` (see ModelList's `getById` method), `clientId`, or index in the ModelList. After locating the target Model, this relays the all other passed arguments to the Model's `setAttrs` method. If a configuration object is passed as a second argument, and that object has `sync: true` set, the underlying Model will be `save()`d. If the DataTable's `autoSync` attribute is set to `true`, the additional argument is not needed. If syncing and the last argument is a function, that function will be used as a callback to the Model's `save()` method. @method modifyRow @param {Object|String|Number} id The Model instance or identifier @param {Object} data New data values for the Model @param {Object} [config] Configuration to pass along to `setAttrs()` @param {Function} [callback] Callback function for Model's `save()` @param {Error|null} callback.err If an error occurred or validation failed, this parameter will contain the error. If the sync operation succeeded, _err_ will be `null`. @param {Any} callback.response The server's response. This value will be passed to the `parse()` method, which is expected to parse it and return an attribute hash. @return {DataTable} @chainable @since 3.5.0 **/ modifyRow: function (id, data, config) { var modelList = this.data, // Allow autoSync: true + addRow({ data }, { sync: false }) sync = (config && ('sync' in config)) ? config.sync : this.get('autoSync'), model, args; if (isObject(id) && id instanceof this.get('recordType')) { model = id; } else if (modelList && id !== undefined) { model = modelList.getById(id) || modelList.getByClientId(id) || modelList.item(id); } if (model && isObject(data)) { args = toArray(arguments, 1, true); model.setAttrs.apply(model, args); if (sync && !model.isNew()) { model.save.apply(model, args); } } return this; }, // -------------------------------------------------------------------------- // Protected properties and methods // -------------------------------------------------------------------------- /** Default function for the `addColumn` event. Inserts the specified column at the provided index. @method _defAddColumnFn @param {EventFacade} e The `addColumn` event @param {Object} e.column The new column definition object @param {Number|Number[]} e.index The array index to insert the new column @protected @since 3.5.0 **/ _defAddColumnFn: function (e) { var index = toArray(e.index), columns = this.get('columns'), cols = columns, i, len; for (i = 0, len = index.length - 1; cols && i < len; ++i) { cols = cols[index[i]] && cols[index[i]].children; } if (cols) { cols.splice(index[i], 0, e.column); this.set('columns', columns, { originEvent: e }); } else { Y.log('addColumn index not findable', 'warn', 'datatable'); } }, /** Default function for the `modifyColumn` event. Mixes the new column properties into the specified column definition. @method _defModifyColumnFn @param {EventFacade} e The `modifyColumn` event @param {Object|String|Number|Number[]} e.column The column definition object or identifier @param {Object} e.newColumnDef The properties to assign to the column @protected @since 3.5.0 **/ _defModifyColumnFn: function (e) { var columns = this.get('columns'), column = this.getColumn(e.column); if (column) { Y.mix(column, e.newColumnDef, true); this.set('columns', columns, { originEvent: e }); } else { Y.log('Could not locate column index to modify column', 'warn', 'datatable'); } }, /** Default function for the `moveColumn` event. Removes the specified column from its current location and inserts it at the specified array index (may be an array of indexes for nested headers). @method _defMoveColumnFn @param {EventFacade} e The `moveColumn` event @param {Object|String|Number|Number[]} e.column The column definition object or identifier @param {Object} e.index The destination index to move to @protected @since 3.5.0 **/ _defMoveColumnFn: function (e) { var columns = this.get('columns'), column = this.getColumn(e.column), toIndex = toArray(e.index), fromCols, fromIndex, toCols, i, len; if (column) { fromCols = column._parent ? column._parent.children : columns; fromIndex = arrayIndex(fromCols, column); if (fromIndex > -1) { toCols = columns; for (i = 0, len = toIndex.length - 1; toCols && i < len; ++i) { toCols = toCols[toIndex[i]] && toCols[toIndex[i]].children; } if (toCols) { len = toCols.length; fromCols.splice(fromIndex, 1); toIndex = toIndex[i]; if (len > toCols.lenth) { // spliced off the same array, so adjust destination // index if necessary if (fromIndex < toIndex) { toIndex--; } } toCols.splice(toIndex, 0, column); this.set('columns', columns, { originEvent: e }); } else { Y.log('Column [' + e.column + '] could not be moved. Destination index invalid for moveColumn', 'warn', 'datatable'); } } } else { Y.log('Column [' + e.column + '] not found for moveColumn', 'warn', 'datatable'); } }, /** Default function for the `removeColumn` event. Splices the specified column from its containing columns array. @method _defRemoveColumnFn @param {EventFacade} e The `removeColumn` event @param {Object|String|Number|Number[]} e.column The column definition object or identifier @protected @since 3.5.0 **/ _defRemoveColumnFn: function (e) { var columns = this.get('columns'), column = this.getColumn(e.column), cols, index; if (column) { cols = column._parent ? column._parent.children : columns; index = Y.Array.indexOf(cols, column); if (index > -1) { cols.splice(index, 1); this.set('columns', columns, { originEvent: e }); } } else { Y.log('Could not locate column [' + e.column + '] for removeColumn', 'warn', 'datatable'); } }, /** Publishes the events used by the mutation methods: * addColumn * removeColumn * modifyColumn * moveColumn @method initializer @protected @since 3.5.0 **/ initializer: function () { this.publish({ addColumn: { defaultFn: Y.bind('_defAddColumnFn', this) }, removeColumn: { defaultFn: Y.bind('_defRemoveColumnFn', this) }, moveColumn: { defaultFn: Y.bind('_defMoveColumnFn', this) }, modifyColumn: { defaultFn: Y.bind('_defModifyColumnFn', this) } }); } }); /** Adds an array of new records to the DataTable's `data` ModelList. Record data can be an array of objects containing field values or an array of instance of the DataTable's configured `recordType` class. This relays all parameters to the `data` ModelList's `add` method. Technically, this is an alias to `addRow`, but please use the appropriately named method for readability. If a configuration object is passed as a second argument, and that object has `sync: true` set, the underlying Models will be `save()`d. If the DataTable's `autoSync` attribute is set to `true`, the additional argument is not needed. If syncing and the last argument is a function, that function will be used as a callback to each Model's `save()` method. @method addRows @param {Object[]} data The data or Model instances to add @param {Object} [config] Configuration to pass along @param {Function} [callback] Callback function for each Model's `save()` @param {Error|null} callback.err If an error occurred or validation failed, this parameter will contain the error. If the sync operation succeeded, _err_ will be `null`. @param {Any} callback.response The server's response. This value will be passed to the `parse()` method, which is expected to parse it and return an attribute hash. @return {DataTable} @chainable @since 3.5.0 **/ Mutable.prototype.addRows = Mutable.prototype.addRow; // Add feature APIs to public Y.DataTable class if (YLang.isFunction(Y.DataTable)) { Y.Base.mix(Y.DataTable, [Mutable]); } /** Fired by the `addColumn` method. @event addColumn @preventable _defAddColumnFn @param {Object} column The new column definition object @param {Number|Number[]} index The array index to insert the new column @since 3.5.0 **/ /** Fired by the `removeColumn` method. @event removeColumn @preventable _defRemoveColumnFn @param {Object|String|Number|Number[]} column The column definition object or identifier @since 3.5.0 **/ /** Fired by the `modifyColumn` method. @event modifyColumn @preventable _defModifyColumnFn @param {Object|String|Number|Number[]} column The column definition object or identifier @param {Object} newColumnDef The properties to assign to the column @since 3.5.0 **/ /** Fired by the `moveColumn` method. @event moveColumn @preventable _defMoveColumnFn @param {Object|String|Number|Number[]} column The column definition object or identifier @param {Object} index The destination index to move to @since 3.5.0 **/ }, '3.18.0', {"requires": ["datatable-base"]});
YUI.add('parallel', function (Y, NAME) { /** * A concurrent parallel processor to help in running several async functions. * @module parallel * @main parallel */ /** A concurrent parallel processor to help in running several async functions. var stack = new Y.Parallel(); for (var i = 0; i < 15; i++) { Y.io('./api/json/' + i, { on: { success: stack.add(function() { }) } }); } stack.done(function() { }); @class Parallel @param {Object} o A config object @param {Object} [o.context=Y] The execution context of the callback to done */ Y.Parallel = function(o) { this.config = o || {}; this.results = []; this.context = this.config.context || Y; this.total = 0; this.finished = 0; }; Y.Parallel.prototype = { /** * An Array of results from all the callbacks in the stack * @property results * @type Array */ results: null, /** * The total items in the stack * @property total * @type Number */ total: null, /** * The number of stacked callbacks executed * @property finished * @type Number */ finished: null, /** * Add a callback to the stack * @method add * @param {Function} fn The function callback we are waiting for */ add: function (fn) { var self = this, index = self.total; self.total += 1; return function () { self.finished++; self.results[index] = (fn && fn.apply(self.context, arguments)) || (arguments.length === 1 ? arguments[0] : Y.Array(arguments)); self.test(); }; }, /** * Test to see if all registered items in the stack have completed, if so call the callback to `done` * @method test */ test: function () { var self = this; if (self.finished >= self.total && self.callback) { self.callback.call(self.context, self.results, self.data); } }, /** * The method to call when all the items in the stack are complete. * @method done * @param {Function} callback The callback to execute on complete * @param {Mixed} callback.results The results of all the callbacks in the stack * @param {Mixed} [callback.data] The data given to the `done` method * @param {Mixed} data Mixed data to pass to the success callback */ done: function (callback, data) { this.callback = callback; this.data = data; this.test(); } }; }, '3.18.0', {"requires": ["yui-base"]});
/*! * Qoopido.js library v3.4.4, 2014-6-15 * https://github.com/dlueth/qoopido.js * (c) 2014 Dirk Lueth * Dual licensed under MIT and GPL *//*! * Qoopido.js library * * version: 3.4.4 * date: 2014-6-15 * author: Dirk Lueth <info@qoopido.com> * website: https://github.com/dlueth/qoopido.js * * Copyright (c) 2014 Dirk Lueth * * Dual licensed under the MIT and GPL licenses. * - http://www.opensource.org/licenses/mit-license.php * - http://www.gnu.org/copyleft/gpl.html */ !function(n){window.qoopido.register("jquery/plugins/shrinkimage",n,["../../dom/element/shrinkimage","jquery"])}(function(n,t,e,r,o){"use strict";var i,c=n.jquery||o.jQuery,u=e.pop(),a="queued",g="cached",s="loaded",f="failed",d="".concat(a,".",u),h="".concat(g,".",u),l="".concat(s,".",u),m="".concat(f,".",u);return c.fn[u]=function(n){return this.each(function(){i.create(this,n)})},i=n["dom/element/shrinkimage"].extend({_constructor:function(n,t){var e=this,r=c(n);i._parent._constructor.call(e,n,t),e.on(a,function(){r.trigger(d)}),e.on(g,function(){r.trigger(h)}),e.on(s,function(){r.trigger(l)}),e.on(f,function(){r.trigger(m)})}})});
;(function () { // closure for web browsers if (typeof module === 'object' && module.exports) { module.exports = LRUCache } else { // just set the global for non-node platforms. this.LRUCache = LRUCache } function hOP (obj, key) { return Object.prototype.hasOwnProperty.call(obj, key) } function naiveLength () { return 1 } function LRUCache (options) { if (!(this instanceof LRUCache)) return new LRUCache(options) if (typeof options === 'number') options = { max: options } if (!options) options = {} this._max = options.max // Kind of weird to have a default max of Infinity, but oh well. if (!this._max || !(typeof this._max === "number") || this._max <= 0 ) this._max = Infinity this._lengthCalculator = options.length || naiveLength if (typeof this._lengthCalculator !== "function") this._lengthCalculator = naiveLength this._allowStale = options.stale || false this._maxAge = options.maxAge || null this._dispose = options.dispose this.reset() } // resize the cache when the max changes. Object.defineProperty(LRUCache.prototype, "max", { set : function (mL) { if (!mL || !(typeof mL === "number") || mL <= 0 ) mL = Infinity this._max = mL if (this._length > this._max) trim(this) } , get : function () { return this._max } , enumerable : true }) // resize the cache when the lengthCalculator changes. Object.defineProperty(LRUCache.prototype, "lengthCalculator", { set : function (lC) { if (typeof lC !== "function") { this._lengthCalculator = naiveLength this._length = this._itemCount for (var key in this._cache) { this._cache[key].length = 1 } } else { this._lengthCalculator = lC this._length = 0 for (var key in this._cache) { this._cache[key].length = this._lengthCalculator(this._cache[key].value) this._length += this._cache[key].length } } if (this._length > this._max) trim(this) } , get : function () { return this._lengthCalculator } , enumerable : true }) Object.defineProperty(LRUCache.prototype, "length", { get : function () { return this._length } , enumerable : true }) Object.defineProperty(LRUCache.prototype, "itemCount", { get : function () { return this._itemCount } , enumerable : true }) LRUCache.prototype.forEach = function (fn, thisp) { thisp = thisp || this var i = 0 var itemCount = this._itemCount for (var k = this._mru - 1; k >= 0 && i < itemCount; k--) if (this._lruList[k]) { i++ var hit = this._lruList[k] if (isStale(this, hit)) { del(this, hit) if (!this._allowStale) hit = undefined } if (hit) { fn.call(thisp, hit.value, hit.key, this) } } } LRUCache.prototype.keys = function () { var keys = new Array(this._itemCount) var i = 0 for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) { var hit = this._lruList[k] keys[i++] = hit.key } return keys } LRUCache.prototype.values = function () { var values = new Array(this._itemCount) var i = 0 for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) { var hit = this._lruList[k] values[i++] = hit.value } return values } LRUCache.prototype.reset = function () { if (this._dispose && this._cache) { for (var k in this._cache) { this._dispose(k, this._cache[k].value) } } this._cache = Object.create(null) // hash of items by key this._lruList = Object.create(null) // list of items in order of use recency this._mru = 0 // most recently used this._lru = 0 // least recently used this._length = 0 // number of items in the list this._itemCount = 0 } // Provided for debugging/dev purposes only. No promises whatsoever that // this API stays stable. LRUCache.prototype.dump = function () { return this._cache } LRUCache.prototype.dumpLru = function () { return this._lruList } LRUCache.prototype.set = function (key, value, maxAge) { maxAge = maxAge || this._maxAge var now = maxAge ? Date.now() : 0 if (hOP(this._cache, key)) { // dispose of the old one before overwriting if (this._dispose) this._dispose(key, this._cache[key].value) this._cache[key].now = now this._cache[key].maxAge = maxAge this._cache[key].value = value this.get(key) return true } var len = this._lengthCalculator(value) var hit = new Entry(key, value, this._mru++, len, now, maxAge) // oversized objects fall out of cache automatically. if (hit.length > this._max) { if (this._dispose) this._dispose(key, value) return false } this._length += hit.length this._lruList[hit.lu] = this._cache[key] = hit this._itemCount ++ if (this._length > this._max) trim(this) return true } LRUCache.prototype.has = function (key) { if (!hOP(this._cache, key)) return false var hit = this._cache[key] if (isStale(this, hit)) { return false } return true } LRUCache.prototype.get = function (key) { return get(this, key, true) } LRUCache.prototype.peek = function (key) { return get(this, key, false) } LRUCache.prototype.pop = function () { var hit = this._lruList[this._lru] del(this, hit) return hit || null } LRUCache.prototype.del = function (key) { del(this, this._cache[key]) } function get (self, key, doUse) { var hit = self._cache[key] if (hit) { if (isStale(self, hit)) { del(self, hit) if (!self._allowStale) hit = undefined } else { if (doUse) use(self, hit) } if (hit) hit = hit.value } return hit } function isStale(self, hit) { if (!hit || (!hit.maxAge && !self._maxAge)) return false var stale = false; var diff = Date.now() - hit.now if (hit.maxAge) { stale = diff > hit.maxAge } else { stale = self._maxAge && (diff > self._maxAge) } return stale; } function use (self, hit) { shiftLU(self, hit) hit.lu = self._mru ++ self._lruList[hit.lu] = hit } function trim (self) { while (self._lru < self._mru && self._length > self._max) del(self, self._lruList[self._lru]) } function shiftLU (self, hit) { delete self._lruList[ hit.lu ] while (self._lru < self._mru && !self._lruList[self._lru]) self._lru ++ } function del (self, hit) { if (hit) { if (self._dispose) self._dispose(hit.key, hit.value) self._length -= hit.length self._itemCount -- delete self._cache[ hit.key ] shiftLU(self, hit) } } // classy, since V8 prefers predictable objects. function Entry (key, value, lu, length, now, maxAge) { this.key = key this.value = value this.lu = lu this.length = length this.now = now if (maxAge) this.maxAge = maxAge } })()
require('./angular-locale_se-fi'); module.exports = 'ngLocale';
define([ 'jquery' ], function ($) { function Tokenizer (decorated, $element, options) { var tokenizer = options.get('tokenizer'); if (tokenizer !== undefined) { this.tokenizer = tokenizer; } decorated.call(this, $element, options); } Tokenizer.prototype.bind = function (decorated, container, $container) { decorated.call(this, container, $container); this.$search = container.dropdown.$search || container.selection.$search || $container.find('.select2-search__field'); }; Tokenizer.prototype.query = function (decorated, params, callback) { var self = this; function select (data) { self.trigger('select', { data: data }); } params.term = params.term || ''; var tokenData = this.tokenizer(params, this.options, select); if (tokenData.term !== params.term) { // Replace the search term if we have the search box if (this.$search.length) { this.$search.val(tokenData.term); this.$search.focus(); } params.term = tokenData.term; } decorated.call(this, params, callback); }; Tokenizer.prototype.tokenizer = function (_, params, options, callback) { var separators = options.get('tokenSeparators') || []; var term = params.term; var i = 0; var createTag = this.createTag || function (params) { return { id: params.term, text: params.term }; }; while (i < term.length) { var termChar = term[i]; if ($.inArray(termChar, separators) === -1) { i++; continue; } var part = term.substr(0, i); var partParams = $.extend({}, params, { term: part }); var data = createTag(partParams); if (data == null) { i++; continue; } callback(data); // Reset the term to not include the tokenized portion term = term.substr(i + 1) || ''; i = 0; } return { term: term }; }; return Tokenizer; });
// AST walker module for Mozilla Parser API compatible trees // A simple walk is one where you simply specify callbacks to be // called on specific nodes. The last two arguments are optional. A // simple use would be // // walk.simple(myTree, { // Expression: function(node) { ... } // }); // // to do something with all expressions. All Parser API node types // can be used to identify node types, as well as Expression, // Statement, and ScopeBody, which denote categories of nodes. // // The base argument can be used to pass a custom (recursive) // walker, and state can be used to give this walked an initial // state. export function simple(node, visitors, base, state, override) { if (!base) base = exports.base ;(function c(node, st, override) { let type = override || node.type, found = visitors[type] base[type](node, st, c) if (found) found(node, st) })(node, state, override) } // An ancestor walk builds up an array of ancestor nodes (including // the current node) and passes them to the callback as the state parameter. export function ancestor(node, visitors, base, state) { if (!base) base = exports.base if (!state) state = [] ;(function c(node, st, override) { let type = override || node.type, found = visitors[type] if (node != st[st.length - 1]) { st = st.slice() st.push(node) } base[type](node, st, c) if (found) found(node, st) })(node, state) } // A recursive walk is one where your functions override the default // walkers. They can modify and replace the state parameter that's // threaded through the walk, and can opt how and whether to walk // their child nodes (by calling their third argument on these // nodes). export function recursive(node, state, funcs, base, override) { let visitor = funcs ? exports.make(funcs, base) : base ;(function c(node, st, override) { visitor[override || node.type](node, st, c) })(node, state, override) } function makeTest(test) { if (typeof test == "string") return type => type == test else if (!test) return () => true else return test } class Found { constructor(node, state) { this.node = node; this.state = state } } // Find a node with a given start, end, and type (all are optional, // null can be used as wildcard). Returns a {node, state} object, or // undefined when it doesn't find a matching node. export function findNodeAt(node, start, end, test, base, state) { test = makeTest(test) if (!base) base = exports.base try { ;(function c(node, st, override) { let type = override || node.type if ((start == null || node.start <= start) && (end == null || node.end >= end)) base[type](node, st, c) if ((start == null || node.start == start) && (end == null || node.end == end) && test(type, node)) throw new Found(node, st) })(node, state) } catch (e) { if (e instanceof Found) return e throw e } } // Find the innermost node of a given type that contains the given // position. Interface similar to findNodeAt. export function findNodeAround(node, pos, test, base, state) { test = makeTest(test) if (!base) base = exports.base try { ;(function c(node, st, override) { let type = override || node.type if (node.start > pos || node.end < pos) return base[type](node, st, c) if (test(type, node)) throw new Found(node, st) })(node, state) } catch (e) { if (e instanceof Found) return e throw e } } // Find the outermost matching node after a given position. export function findNodeAfter(node, pos, test, base, state) { test = makeTest(test) if (!base) base = exports.base try { ;(function c(node, st, override) { if (node.end < pos) return let type = override || node.type if (node.start >= pos && test(type, node)) throw new Found(node, st) base[type](node, st, c) })(node, state) } catch (e) { if (e instanceof Found) return e throw e } } // Find the outermost matching node before a given position. export function findNodeBefore(node, pos, test, base, state) { test = makeTest(test) if (!base) base = exports.base let max ;(function c(node, st, override) { if (node.start > pos) return let type = override || node.type if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node)) max = new Found(node, st) base[type](node, st, c) })(node, state) return max } // Used to create a custom walker. Will fill in all missing node // type properties with the defaults. export function make(funcs, base) { if (!base) base = exports.base let visitor = {} for (var type in base) visitor[type] = base[type] for (var type in funcs) visitor[type] = funcs[type] return visitor } function skipThrough(node, st, c) { c(node, st) } function ignore(_node, _st, _c) {} // Node walkers. export const base = {} base.Program = base.BlockStatement = (node, st, c) => { for (let i = 0; i < node.body.length; ++i) c(node.body[i], st, "Statement") } base.Statement = skipThrough base.EmptyStatement = ignore base.ExpressionStatement = base.ParenthesizedExpression = (node, st, c) => c(node.expression, st, "Expression") base.IfStatement = (node, st, c) => { c(node.test, st, "Expression") c(node.consequent, st, "Statement") if (node.alternate) c(node.alternate, st, "Statement") } base.LabeledStatement = (node, st, c) => c(node.body, st, "Statement") base.BreakStatement = base.ContinueStatement = ignore base.WithStatement = (node, st, c) => { c(node.object, st, "Expression") c(node.body, st, "Statement") } base.SwitchStatement = (node, st, c) => { c(node.discriminant, st, "Expression") for (let i = 0; i < node.cases.length; ++i) { let cs = node.cases[i] if (cs.test) c(cs.test, st, "Expression") for (let j = 0; j < cs.consequent.length; ++j) c(cs.consequent[j], st, "Statement") } } base.ReturnStatement = base.YieldExpression = (node, st, c) => { if (node.argument) c(node.argument, st, "Expression") } base.ThrowStatement = base.SpreadElement = (node, st, c) => c(node.argument, st, "Expression") base.TryStatement = (node, st, c) => { c(node.block, st, "Statement") if (node.handler) { c(node.handler.param, st, "Pattern") c(node.handler.body, st, "ScopeBody") } if (node.finalizer) c(node.finalizer, st, "Statement") } base.WhileStatement = base.DoWhileStatement = (node, st, c) => { c(node.test, st, "Expression") c(node.body, st, "Statement") } base.ForStatement = (node, st, c) => { if (node.init) c(node.init, st, "ForInit") if (node.test) c(node.test, st, "Expression") if (node.update) c(node.update, st, "Expression") c(node.body, st, "Statement") } base.ForInStatement = base.ForOfStatement = (node, st, c) => { c(node.left, st, "ForInit") c(node.right, st, "Expression") c(node.body, st, "Statement") } base.ForInit = (node, st, c) => { if (node.type == "VariableDeclaration") c(node, st) else c(node, st, "Expression") } base.DebuggerStatement = ignore base.FunctionDeclaration = (node, st, c) => c(node, st, "Function") base.VariableDeclaration = (node, st, c) => { for (let i = 0; i < node.declarations.length; ++i) c(node.declarations[i], st) } base.VariableDeclarator = (node, st, c) => { c(node.id, st, "Pattern") if (node.init) c(node.init, st, "Expression") } base.Function = (node, st, c) => { if (node.id) c(node.id, st, "Pattern") for (let i = 0; i < node.params.length; i++) c(node.params[i], st, "Pattern") c(node.body, st, node.expression ? "ScopeExpression" : "ScopeBody") } // FIXME drop these node types in next major version // (They are awkward, and in ES6 every block can be a scope.) base.ScopeBody = (node, st, c) => c(node, st, "Statement") base.ScopeExpression = (node, st, c) => c(node, st, "Expression") base.Pattern = (node, st, c) => { if (node.type == "Identifier") c(node, st, "VariablePattern") else if (node.type == "MemberExpression") c(node, st, "MemberPattern") else c(node, st) } base.VariablePattern = ignore base.MemberPattern = skipThrough base.RestElement = (node, st, c) => c(node.argument, st, "Pattern") base.ArrayPattern = (node, st, c) => { for (let i = 0; i < node.elements.length; ++i) { let elt = node.elements[i] if (elt) c(elt, st, "Pattern") } } base.ObjectPattern = (node, st, c) => { for (let i = 0; i < node.properties.length; ++i) c(node.properties[i].value, st, "Pattern") } base.Expression = skipThrough base.ThisExpression = base.Super = base.MetaProperty = ignore base.ArrayExpression = (node, st, c) => { for (let i = 0; i < node.elements.length; ++i) { let elt = node.elements[i] if (elt) c(elt, st, "Expression") } } base.ObjectExpression = (node, st, c) => { for (let i = 0; i < node.properties.length; ++i) c(node.properties[i], st) } base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration base.SequenceExpression = base.TemplateLiteral = (node, st, c) => { for (let i = 0; i < node.expressions.length; ++i) c(node.expressions[i], st, "Expression") } base.UnaryExpression = base.UpdateExpression = (node, st, c) => { c(node.argument, st, "Expression") } base.BinaryExpression = base.LogicalExpression = (node, st, c) => { c(node.left, st, "Expression") c(node.right, st, "Expression") } base.AssignmentExpression = base.AssignmentPattern = (node, st, c) => { c(node.left, st, "Pattern") c(node.right, st, "Expression") } base.ConditionalExpression = (node, st, c) => { c(node.test, st, "Expression") c(node.consequent, st, "Expression") c(node.alternate, st, "Expression") } base.NewExpression = base.CallExpression = (node, st, c) => { c(node.callee, st, "Expression") if (node.arguments) for (let i = 0; i < node.arguments.length; ++i) c(node.arguments[i], st, "Expression") } base.MemberExpression = (node, st, c) => { c(node.object, st, "Expression") if (node.computed) c(node.property, st, "Expression") } base.ExportNamedDeclaration = base.ExportDefaultDeclaration = (node, st, c) => { if (node.declaration) c(node.declaration, st, node.type == "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression") if (node.source) c(node.source, st, "Expression") } base.ExportAllDeclaration = (node, st, c) => { c(node.source, st, "Expression") } base.ImportDeclaration = (node, st, c) => { for (let i = 0; i < node.specifiers.length; i++) c(node.specifiers[i], st) c(node.source, st, "Expression") } base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore base.TaggedTemplateExpression = (node, st, c) => { c(node.tag, st, "Expression") c(node.quasi, st) } base.ClassDeclaration = base.ClassExpression = (node, st, c) => c(node, st, "Class") base.Class = (node, st, c) => { if (node.id) c(node.id, st, "Pattern") if (node.superClass) c(node.superClass, st, "Expression") for (let i = 0; i < node.body.body.length; i++) c(node.body.body[i], st) } base.MethodDefinition = base.Property = (node, st, c) => { if (node.computed) c(node.key, st, "Expression") c(node.value, st, "Expression") } base.ComprehensionExpression = (node, st, c) => { for (let i = 0; i < node.blocks.length; i++) c(node.blocks[i].right, st, "Expression") c(node.body, st, "Expression") }
!function(t){"use strict";var n="cuid",r=0,e=4,i=36,o=Math.pow(i,e),u=function(t,n){var r="000000000"+t;return r.substr(r.length-n)},g=function(){return u((Math.random()*o<<0).toString(i),e)},a=function(){return r=r<o?r:0,r++,r-1},c=function(){var t,n="c",r=(new Date).getTime().toString(i),o=c.fingerprint(),l=g()+g();return t=u(a().toString(i),e),n+r+t+o+l};c.slug=function(){var t,n=(new Date).getTime().toString(36),r=c.fingerprint().slice(0,1)+c.fingerprint().slice(-1),e=g().slice(-2);return t=a().toString(36).slice(-4),n.slice(-2)+t+r+e},c.globalCount=function(){var t=function(){var t,n=0;for(t in window)n++;return n}();return c.globalCount=function(){return t},t},c.fingerprint=function(){return u((navigator.mimeTypes.length+navigator.userAgent.length).toString(36)+c.globalCount().toString(36),4)},t.register?t.register(n,c):"undefined"!=typeof module?module.exports=c:t[n]=c}(this.applitude||this); //# sourceMappingURL=browser-cuid.min.js.map
$(function() { var calculator_select = $('select#calc_type') var original_calc_type = calculator_select.prop('value'); $('.calculator-settings-warning').hide(); calculator_select.change(function() { if (calculator_select.prop('value') == original_calc_type) { $('div.calculator-settings').show(); $('.calculator-settings-warning').hide(); $('.calculator-settings').find('input,textarea').prop("disabled", false); } else { $('div.calculator-settings').hide(); $('.calculator-settings-warning').show(); $('.calculator-settings').find('input,texttarea').prop("disabled", true); } }); })
/*! jquery.allowed-chars 03-06-2014 jQuery Allowed Chars - simple plugin v1.0.4 Copyright (c) 2014 Pavlo Voznenko and other contributors. Distributed under the MIT license. https://github.com/fosco-maestro/jquery-allowed-chars-simple-plugin */ !function(a,b){"use strict";a.fn.allowedChars=function(c){var d={allowed:"0123456789",caseSensitive:!0},e=a(this),f={init:function(c){if(b!==c){var e=Object.prototype.toString.call(c);switch(e){case"[object RegExp]":case"[object String]":d.allowed=c;break;case"[object Object]":a.extend(d,c);break;default:return f.errorHandler("Unexpected 'options' type: "+e+"; Supported types: RegExp, String, Object"),!1}}return!0},errorHandler:function(a){b!==console&&b!==console.log&&console.log("jquery.allowedChars error: "+a)}};f.init(c)&&e.keypress(function(a){var c,e=window.event?window.event.keyCode:a.keyCode||a.charCode||b,f=d.allowed,g="[object RegExp]"===Object.prototype.toString.call(f);if(e===b)return!0;if(c=String.fromCharCode(e),g)f.test(c)||a.preventDefault();else{if(d.caseSensitive||(f=f.toLowerCase(),c=c.toLowerCase()),-1!==f.indexOf(c))return!0;var h=-1===[null,0,8,9,13,27].indexOf(e);h&&a.preventDefault()}return!0})}}(jQuery); //# sourceMappingURL=jquery.allowed-chars.min.map
/* Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl> Copyright (C) 2011 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 node: true */ /*global document: true, window:true, esprima: true, testReflect: true */ var runTests; function getContext(esprima, reportCase, reportFailure) { 'use strict'; var Reflect, Pattern; // Maps Mozilla Reflect object to our Esprima parser. Reflect = { parse: function (code) { var result; reportCase(code); try { result = esprima.parse(code); } catch (error) { result = error; } return result; } }; // This is used by Reflect test suite to match a syntax tree. Pattern = function (obj) { var pattern; // Poor man's deep object cloning. pattern = JSON.parse(JSON.stringify(obj)); // Special handling for regular expression literal since we need to // convert it to a string literal, otherwise it will be decoded // as object "{}" and the regular expression would be lost. if (obj.type && obj.type === 'Literal') { if (obj.value instanceof RegExp) { pattern = { type: obj.type, value: obj.value.toString() }; } } // Special handling for branch statement because SpiderMonkey // prefers to put the 'alternate' property before 'consequent'. if (obj.type && obj.type === 'IfStatement') { pattern = { type: pattern.type, test: pattern.test, consequent: pattern.consequent, alternate: pattern.alternate }; } // Special handling for do while statement because SpiderMonkey // prefers to put the 'test' property before 'body'. if (obj.type && obj.type === 'DoWhileStatement') { pattern = { type: pattern.type, body: pattern.body, test: pattern.test }; } function adjustRegexLiteralAndRaw(key, value) { if (key === 'value' && value instanceof RegExp) { value = value.toString(); } else if (key === 'raw' && typeof value === "string") { // Ignore Esprima-specific 'raw' property. return undefined; } return value; } if (obj.type && (obj.type === 'Program')) { pattern.assert = function (tree) { var actual, expected; actual = JSON.stringify(tree, adjustRegexLiteralAndRaw, 4); expected = JSON.stringify(obj, null, 4); if (expected !== actual) { reportFailure(expected, actual); } }; } return pattern; }; return { Reflect: Reflect, Pattern: Pattern }; } if (typeof window !== 'undefined') { // Run all tests in a browser environment. runTests = function () { 'use strict'; var total = 0, failures = 0; function setText(el, str) { if (typeof el.innerText === 'string') { el.innerText = str; } else { el.textContent = str; } } function reportCase(code) { var report, e; report = document.getElementById('report'); e = document.createElement('pre'); e.setAttribute('class', 'code'); setText(e, code); report.appendChild(e); total += 1; } function reportFailure(expected, actual) { var report, e; failures += 1; report = document.getElementById('report'); e = document.createElement('p'); setText(e, 'Expected'); report.appendChild(e); e = document.createElement('pre'); e.setAttribute('class', 'expected'); setText(e, expected); report.appendChild(e); e = document.createElement('p'); setText(e, 'Actual'); report.appendChild(e); e = document.createElement('pre'); e.setAttribute('class', 'actual'); setText(e, actual); report.appendChild(e); } setText(document.getElementById('version'), esprima.version); window.setTimeout(function () { var tick, context = getContext(esprima, reportCase, reportFailure); tick = new Date(); testReflect(context.Reflect, context.Pattern); tick = (new Date()) - tick; if (failures > 0) { setText(document.getElementById('status'), total + ' tests. ' + 'Failures: ' + failures + '. ' + tick + ' ms'); } else { setText(document.getElementById('status'), total + ' tests. ' + 'No failure. ' + tick + ' ms'); } }, 513); }; } else { (function (global) { 'use strict'; var esprima = require('../esprima'), tick, total = 0, failures = [], header, current, context; function reportCase(code) { total += 1; current = code; } function reportFailure(expected, actual) { failures.push({ source: current, expected: expected.toString(), actual: actual.toString() }); } context = getContext(esprima, reportCase, reportFailure); tick = new Date(); require('./reflect').testReflect(context.Reflect, context.Pattern); tick = (new Date()) - tick; header = total + ' tests. ' + failures.length + ' failures. ' + tick + ' ms'; if (failures.length) { console.error(header); failures.forEach(function (failure) { console.error(failure.source + ': Expected\n ' + failure.expected.split('\n').join('\n ') + '\nto match\n ' + failure.actual); }); } else { console.log(header); } process.exit(failures.length === 0 ? 0 : 1); }(this)); } /* vim: set sw=4 ts=4 et tw=80 : */
var Lab = require('lab'), lab = exports.lab = Lab.script(), describe = lab.experiment, before = lab.before, after = lab.after, it = lab.test, expect = Lab.expect; var server, serverResponse, source, ctx; before(function (done) { server = require('../fixtures/setupServer')(done); server.ext('onPreResponse', function (request, next) { source = request.response.source; ctx = source.context; next(); }); }); describe('Getting to the home page', function () { it('gets there, no problem', function (done) { var opts = { url: '/about' }; server.inject(opts, function (resp) { expect(resp.statusCode).to.equal(200); expect(source.template).to.equal('company/about'); done(); }); }); it('has all the pieces', function (done) { expect(ctx.title).to.equal('About'); expect(ctx.package.name).to.equal('newww'); expect(ctx.dependencies).to.be.an('Array'); expect(ctx.contributors).to.be.an('Array'); done(); }); });
/** * The [Harmonic Mean](https://en.wikipedia.org/wiki/Harmonic_mean) is * a mean function typically used to find the average of rates. * This mean is calculated by taking the reciprocal of the arithmetic mean * of the reciprocals of the input numbers. * * This is a [measure of central tendency](https://en.wikipedia.org/wiki/Central_tendency): * a method of finding a typical or central value of a set of numbers. * * This runs on `O(n)`, linear time in respect to the array. * * @param {Array<number>} x sample of one or more data points * @returns {number} harmonic mean * @throws {Error} if x is empty * @throws {Error} if x contains a negative number * @example * harmonicMean([2, 3]).toFixed(2) // => '2.40' */ function harmonicMean(x) { // The mean of no numbers is null if (x.length === 0) { throw new Error("harmonicMean requires at least one data point"); } let reciprocalSum = 0; for (let i = 0; i < x.length; i++) { // the harmonic mean is only valid for positive numbers if (x[i] <= 0) { throw new Error( "harmonicMean requires only positive numbers as input" ); } reciprocalSum += 1 / x[i]; } // divide n by the the reciprocal sum return x.length / reciprocalSum; } export default harmonicMean;
const express = require('express'), mongoose = require('mongoose'), path = require('path'), bodyParser = require('body-parser'), morgan = require('morgan'), User = require('./app/models/user'), jwt = require('jsonwebtoken'), passport = require('passport'), config = require('./config/main'), app = express(); app.use(express.static('./bower_components')); // view engine setup app.set('views', path.join(__dirname)); app.set('view engine', 'jade'); app.locals.basedir = __dirname ; // to get POST requests for REST-API app.use(bodyParser.urlencoded({ extended: false })); // value can be Array or String app.use(bodyParser.json()); // application/json // log requests to console app.use(morgan('dev')); // initialize passport for use app.use(passport.initialize()); // connect to database mongoose.connect(config.database) require('./config/passport')(passport); // create API routes var apiRoutes = express.Router(); //register new users apiRoutes.post('/register', (req, res) => { if(!req.body.user || !req.body.pass) { res.json({ success: false, massage: 'please enter an username and password to register.'}); } else { // if exists User.findOne({ username: req.body.user }, (err, user) => { if (err) throw err; if (user) { res.send({ success: false, massage: 'This user already exists.' }); } else { var newUser = new User({ username: req.body.user, password: req.body.pass, }); // save the new user newUser.save(function(err) { if (!err) { res.json({ success: true, message: 'Successfully created new user.' }); } }); } }); } }); // protect dashboard route with JWT apiRoutes.get('/dashboard', passport.authenticate('jwt', { session: false }), (req, res) => { res.send('It worked! user id is:' + req.user._id + '.'); }); // authenticate the user and get a JWT apiRoutes.post('/login', (req, res) => { User.findOne({ username: req.body.user }, (err, user) => { if (err) throw err; if (!user) { res.send({ success: false, massage: 'User not found.' }); } else { // check if the password matches user.comparePassword(req.body.pass, (err, isMatch) => { if (isMatch && !err) { var token = jwt.sign(user, config.secret, { expiresIn: 10080 // in seconds }); //res.json({ success: true, token: 'JWT ' + token }); res.render("./public/index"); // render index.jade file } else { res.send({ success: false, massage: 'login failed, invalid password.' }); } }); } }); }); // set url for API routes app.use('/api', apiRoutes); // home route apiRoutes.get('/login', (req, res) => { res.render("public/login"); // render login.jade file }); app.listen(3000, (error) => { if (error) { return console.log('something bad happened', err); } console.log("Server running at http://localhost:3000/api/login"); });
var create = require('../utils').create; var Base = require('../native/observer/model'); var Model = require('../model'); var Observer = function (obj, cb) { Base.call(this, obj, cb); }; Observer.prototype = create(Base); Observer.prototype.constructor = Observer; Observer.prototype.model = function (cb) { return new Model(this.object, cb); }; Observer.prototype.update = function (cb) { var changes = []; var model = this.model(function (change) { if (change) { changes = changes.concat(change); } }); cb(model); this.listener(changes); return this; }; module.exports = Observer;
import { compose, createStore } from 'redux'; import rootReducer from 'reducers//'; import routes from 'routes'; export default function configureStore(initialState) { const store = createStore(rootReducer, initialState); return store; }
jest.dontMock('object-assign'); jest.dontMock('../ThreadsForm'); jest.dontMock('../ThreadsFormSelectableRecipients'); jest.dontMock('../ThreadsFormSelectedRecipients'); jest.dontMock('../ThreadsFormSelectedRecipientsSave'); jest.dontMock('../ThreadsFormDefaultRecipientSelectedBagde'); jest.dontMock('../../constants/MessageConstants'); jest.dontMock('../MessagesForm'); jest.dontMock('jquery') jest.dontMock('keymirror'); jest.dontMock('../../utils/users'); describe('ThreadsForm', function() { var React; var ReactDOM; var TestUtils; var ThreadsForm; var ThreadsFormDefaultRecipientRow; var ThreadsFormDefaultRecipientSelectedBagde; var ThreadsFormSelectableRecipients; var ThreadsFormSelectedRecipients; var ThreadsFormSelectedRecipientsSave; var MessageStore; var MessagesForm; var MessagesFormDefaultInput; var $ = require('jquery'); var AppDispatcher; var callback; var MessageConstants = require('../../constants/MessageConstants'); var users = [ { "id": 1, "username": "user1", "picture": "/path/to/picture1.png" }, { "id": 2, "username": "user2", "picture": "/path/to/picture2.png" }, { "id": 3, "username": "user3", "picture": "/path/to/picture3.png" }, ]; beforeEach(function() { React = require('react'); ReactDOM = require('react-dom'); TestUtils = require('react-addons-test-utils'); ThreadsForm = require('../ThreadsForm'); ThreadsFormDefaultRecipientRow = require('../ThreadsFormDefaultRecipientRow'); ThreadsFormDefaultRecipientSelectedBagde = require('../ThreadsFormDefaultRecipientSelectedBagde'); ThreadsFormSelectableRecipients = require('../ThreadsFormSelectableRecipients'); ThreadsFormSelectedRecipients = require('../ThreadsFormSelectedRecipients'); ThreadsFormSelectedRecipientsSave = require('../ThreadsFormSelectedRecipientsSave'); MessageStore = require('../../stores/MessageStore'); MessagesForm = require('../MessagesForm'); MessagesFormDefaultInput = require('../MessagesFormDefaultInput'); MessageStore.getLoggedInParticipantId.mockReturnValue(1); // we say the user is logged in MessageStore.getCurrentThread.mockReturnValue({ id: null, name: null, participants: [], }); MessageStore.postMessage.mockReturnValue({}); // we do not care about the value actually returned MessageStore.getRecipients.mockReturnValue(users); // users to choose from }); it('defaults props', function(){ // we instantiate var renderedThreadsForm = TestUtils.renderIntoDocument( <ThreadsForm/> ); var threadsFormNode = ReactDOM.findDOMNode(renderedThreadsForm); // by default, the content is rendered in a div with class "wrappingClass" expect(renderedThreadsForm.props.wrappingTag).toEqual('div'); expect(renderedThreadsForm.props.wrappingClass).toEqual('messagesThreadsForm'); expect(renderedThreadsForm.props.wrappingStyle).toEqual({}); expect(renderedThreadsForm.props.recipientsIterator).toEqual("username"); expect(renderedThreadsForm.props.recipientsRowLayout).toEqual(ThreadsFormDefaultRecipientRow); expect(renderedThreadsForm.props.recipientsAdditionalInfo).toEqual({}); expect(renderedThreadsForm.props.recipientsRowStyle).toEqual({}); expect(renderedThreadsForm.props.recipientsSelectedClassName).toEqual('recipientsSelected'); expect(renderedThreadsForm.props.recipientsSelectedStyle).toEqual({}); expect(renderedThreadsForm.props.recipientsSelectedBagde).toEqual(ThreadsFormDefaultRecipientSelectedBagde); expect(renderedThreadsForm.props.recipientsPlaceholder).toEqual("Filter ..."); expect(renderedThreadsForm.props.recipientsFilterClass).toEqual("recipientsFilterClass form-control"); }); it('login state', function(){ // we say we createa new thread (does not require us to select participants for testing) MessageStore.getCurrentThread.mockReturnValue({ id:0, name:"null", participants:[] }); // we start with a logged in user var renderedThreadsForm = TestUtils.renderIntoDocument( <ThreadsForm/> ); var threadsFormNode = ReactDOM.findDOMNode(renderedThreadsForm); expect(threadsFormNode.classList[0]).toEqual('messagesThreadsForm'); // we ensure the component listens to the login status of the user on logout renderedThreadsForm.setState({loggedInParticipantId: null}); expect(threadsFormNode.classList[0]).toEqual('messagesThreadsFormUnauthenticated'); // we ensure the component listens to the login status of the user on login renderedThreadsForm.setState({loggedInParticipantId: 1}); expect(threadsFormNode.classList[0]).toEqual('messagesThreadsForm'); }); it('users badges list, remove recipient (TODO: split tests)', function(){ MessageStore.getCurrentThread.mockReturnValue({ id: 1, name: null, participants: [users[0].id], }); // we ensure the user list is correctly rendered var renderedThreadsForm = TestUtils.renderIntoDocument( <ThreadsForm /> ); renderedThreadsForm.setState({recipientsSelected: users}); // we see the names of the participants var threadsFormNode = ReactDOM.findDOMNode(renderedThreadsForm); expect(threadsFormNode.classList[0]).toEqual('threadFormTitleHeader'); // we ask to update it renderedThreadsForm.setState({recipientsSelected: users, showForm: true}); // we get the children var children = TestUtils.scryRenderedComponentsWithType(renderedThreadsForm, ThreadsFormDefaultRecipientSelectedBagde); expect(children[0].props.recipient).toEqual(users[0]); expect(children[1].props.recipient).toEqual(users[1]); expect(children[2].props.recipient).toEqual(users[2]); // for now, all the users are in expect(renderedThreadsForm.state.recipientsSelected).toEqual([users[0], users[1], users[2]]); // we can remove a user expect(children[0].props.removeRecipient).toEqual(renderedThreadsForm.removeRecipient); var removeBtn = TestUtils.scryRenderedDOMComponentsWithClass(renderedThreadsForm, 'removeRecipientBadge')[0]; TestUtils.Simulate.click(ReactDOM.findDOMNode(removeBtn)); expect(renderedThreadsForm.state.recipientsSelected.length).toEqual(2); }); it('users default badges list will not allow to remove recipient if he is in the thread store', function(){ MessageStore.getCurrentThread.mockReturnValue({ id: 1, name: null, participants: [users[0].id], }); var renderedThreadsForm = TestUtils.renderIntoDocument( <ThreadsForm /> ); renderedThreadsForm.setState({ recipientsSelected: users, showForm: true, }); // we get the children var children = TestUtils.scryRenderedComponentsWithType(renderedThreadsForm, ThreadsFormDefaultRecipientSelectedBagde); // for now, all the users are in expect(renderedThreadsForm.state.recipientsSelected).toEqual([users[0], users[1], users[2]]); // we can NOT remove user 0 var removeBtn0 = TestUtils.scryRenderedDOMComponentsWithTag(children[0], 'i'); expect(removeBtn0.length).toEqual(0); // user 1 can be removed as usual var removeBtn1 = TestUtils.scryRenderedDOMComponentsWithTag(children[1], 'i'); expect(removeBtn1.length).toEqual(1); }); it('componentWillUpdate, registerInStore', function(){ // we ensure the user list is correctly rendered var renderedThreadsForm = TestUtils.renderIntoDocument( <ThreadsForm /> ); expect(renderedThreadsForm.state.currentThread.id).toEqual(null); // people in recipientsSelected but not in participants will be added var newThread = { id: 0, name: null, participants: [], }; // we spy spyOn(renderedThreadsForm, "registerInStore"); // we update the state renderedThreadsForm.componentWillUpdate({}, {currentThread: newThread}); expect(renderedThreadsForm.registerInStore).toHaveBeenCalled(); }); it('registerInStore, setThreadForm', function(){ // we ensure the user list is correctly rendered var renderedThreadsForm = TestUtils.renderIntoDocument( <ThreadsForm /> ); // we spy spyOn(MessageStore, "setThreadForm"); // we call renderedThreadsForm.registerInStore(); expect(MessageStore.setThreadForm).toHaveBeenCalledWith(renderedThreadsForm); }); it('chekSelectableSelected', function(){ // we ensure the user list is correctly rendered var renderedThreadsForm = TestUtils.renderIntoDocument( <ThreadsForm /> ); renderedThreadsForm.setState({ recipients: users, }); var currentThread = { id: 1, name: null, participants: [users[0].id], } // check selectable and selected renderedThreadsForm.chekSelectableSelected(currentThread); expect(renderedThreadsForm.state.recipientsSelectable).toEqual([users[1], users[2]]); expect(renderedThreadsForm.state.recipientsSelected).toEqual([users[0]]); }); it('saveRecipients', function(){ // we ensure the user list is correctly rendered var renderedThreadsForm = TestUtils.renderIntoDocument( <ThreadsForm /> ); // people in recipientsSelected but not in participants will be added renderedThreadsForm.setState({ currentThread: { id: 1, name: null, participants: [users[0].id], }, recipientsSelected: [users[0], users[1]], }); // we spy spyOn(MessageStore, "addThreadParticipants"); // we update the state renderedThreadsForm.saveRecipients(); expect(MessageStore.addThreadParticipants).toHaveBeenCalledWith(1, [users[1].id]); }); it('saveThreadWithRecipients', function(){ // we ensure the user list is correctly rendered var renderedThreadsForm = TestUtils.renderIntoDocument( <ThreadsForm /> ); // people in recipientsSelected but not in participants will be added renderedThreadsForm.setState({ currentThread: { id: 0, name: null, participants: [], }, recipientsSelected: [users[0], users[1]], }); // we spy spyOn(MessageStore, "createThread"); // we update the state renderedThreadsForm.saveThreadWithRecipients(); expect(MessageStore.createThread).toHaveBeenCalledWith(null, [users[0].id, users[1].id]); }); it('saveThreadWithRecipients', function(){ // we ensure the user list is correctly rendered var renderedThreadsForm = TestUtils.renderIntoDocument( <ThreadsForm /> ); // people in recipientsSelected but not in participants will be added renderedThreadsForm.setState({ currentThread: { id: 0, name: null, participants: [], }, recipientsSelected: [users[0], users[1]], }); // we spy spyOn(MessageStore, "createThread"); // we update the state renderedThreadsForm.saveThreadWithRecipients(); expect(MessageStore.createThread).toHaveBeenCalledWith(null, [users[0].id, users[1].id]); }); });
import React, { PropTypes } from 'react'; import Loader from '~/components/Loader'; import { connect } from 'react-redux'; import { CSS } from '~/theme'; import { windowResize } from '~/redux/navigation'; import './App.css'; export class App extends React.Component { static propTypes = { children: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, }; componentDidMount() { const { dispatch } = this.props; window.addEventListener('resize', () => dispatch(windowResize())); } render() { const { children } = this.props; return <div children={children} />; } } export default connect()(App);
let oldBoard = {}; const statusListeners = {}; // This allows things to listen for certain board statuses to happen export const listenForBoardStatus = (status, thunk) => { statusListeners[status] = statusListeners[status] || []; statusListeners[status].push(thunk); }; export const init = (store) => { store.subscribe(() => { const { room } = store.getState(); const newBoard = room && room.gameState && room.gameState.board || {}; if (oldBoard.status !== newBoard.status || oldBoard.data !== newBoard.data) { oldBoard = newBoard; if (statusListeners[newBoard.status]) { statusListeners[newBoard.status].forEach((thunk) => store.dispatch(thunk(newBoard))); } } }); };
import {createStore} from 'redux'; import reducers from './reducers'; const store = createStore(reducers); export default store;
'use strict'; const http = require('http'); const request = require('request-promise'); const responseTime = require('../index.js'); const Koa = require('koa'); const app = new Koa(); let server; const host = '127.0.0.1'; const port = '8080'; app.use(responseTime()) server = http.createServer(app.callback()); describe('responseTime', () => { let head = request.defaults({ method: 'HEAD', uri: `http://${host}:${port}`, simple: false }); beforeAll(done => server.listen(port, host, done)); afterAll(done => server.close(done)); it('adds an X-Response-Time header', done => { head() .then(headers => expect(headers['x-response-time']).toBeDefined()) .catch(this.fail) .finally(done); }); it('has microsecond precision', done => { head() .then(headers => headers['x-response-time']) .then(time => expect(time).toMatch(/\d+\.\d{3}ms/)) .catch(this.fail) .finally(done); }); });
import gimmeData from '../utils/gimmeData'; import EventMusicians from '../components/EventMusicians'; import { approveEventMusician, rejectEventMusician } from '../actions/eventActions'; function urlFn(state, props) { const id = props.eventId; return `eventVolunteers?filter=${JSON.stringify({ where: { eventId: id }, include: 'volunteer' })}`; } const mapDispatchToProps = { approveEventMusician, rejectEventMusician }; export default gimmeData(urlFn, null, mapDispatchToProps)(EventMusicians);
"use strict" var opts = require("minimist")(process.argv.slice(2), {stopEarly: true, boolean: true}) if (opts._.length==0) usage() var cmd = opts._.shift() var cmds = { "set": require("./set.js"), "get": require("./get.js"), "ls": require("./ls.js") } if (!cmds[cmd]) usage("Unknown command '"+cmd+"'") cmds[cmd](opts) function usage(err) { if (err) console.error(err) console.error("Usage: "+process.argv[1]+" [--help] cmd [args...]") console.error("Where cmd is: set, get, ls") process.exit(1) }
import React from 'react' import styles from './Spinner.css' const Spinner = () => ( <div className={styles.container}> <div className={styles.spinner}></div> <div className={`${styles.spinner} ${styles.rect2}`}></div> <div className={`${styles.spinner} ${styles.rect3}`}></div> <div className={`${styles.spinner} ${styles.rect4}`}></div> <div className={`${styles.spinner} ${styles.rect5}`}></div> </div> ) export default Spinner
/** * Created by BG236557 on 2016/9/23. */ let idCounter = 0; export let uniqueID = function () { return idCounter++ + new Date().getTime() + Math.random(); }; export let empty = function () { }; export let isObj = function (input) { return Object.prototype.toString.call(input) === '[object Object]'; }; export let isArr = function (input) { return Object.prototype.toString.call(input) === '[object Array]'; }; export let diff = function (a, b) { return a.filter(x => { return b.indexOf(x) === -1 }); }; export let getScrollBarWidth = function () { const inner = document.createElement('p'); inner.style.width = '100%'; inner.style.height = '200px'; const outer = document.createElement('div'); outer.style.position = 'absolute'; outer.style.top = '0px'; outer.style.left = '0px'; outer.style.visibility = 'hidden'; outer.style.width = '200px'; outer.style.height = '150px'; outer.style.overflow = 'hidden'; outer.appendChild(inner); document.body.appendChild(outer); const w1 = inner.offsetWidth; outer.style.overflow = 'scroll'; let w2 = inner.offsetWidth; if (w1 === w2) w2 = outer.clientWidth; document.body.removeChild(outer); return w1 - w2; }; export let extend = function (target) { for (let i = 1; i < arguments.length; i++) { let source = arguments[i]; for (let key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; export let sort = function (arr) { let auto = []; let left = []; let right = []; for (let i = 0, len = arr.length; i < len; i++) { let item = arr[i].props || arr[i]; if (item.dataFixed === 'left') { left.push(arr[i]); } else if (item.dataFixed === 'right') { right.push(arr[i]); } else { auto.push(arr[i]); } } let sorted = left.concat(auto).concat(right); return {sorted, left, right} };
const Core=(behavior)=>{ const doc={str:'', lines:[]},/* Document (string) */ cur={y:0, x:0, maxcol:0, height:1.0, scroll:false, color:'normal'}, /* number -> valid index into [lines] */ idx=(n)=>{n|=0;const l=doc.lines.length; if(0<=n&&n<l){return n;} if(n>=l){return l-1;} return Math.max(0,n+l);}, /* (start+i.count) { cutLF lines */ lines=(start,count)=>{const c=idx(start); return doc.lines.slice(c,Math.max(c,c+count|0));}, put=(a)=>{doc.str=a; doc.lines=doc.str.match(/^.*/mg);}, ins=(a,b)=>{},/* TODO insert string (a) at position(s) (b) */ del=(a,b)=>{},/* TODO delete #(a) chars at position(s) (b) */ save=(a)=>{},/* TODO Send a save/commit request to persistent storage. */ /* Listener */ hears=(parsed)=>{ let heard=false, ps=parsed.status; if(ps){ if('error'===ps || 'ignore'===ps){return false;} heard=behavior.dispatch(parsed,cur,doc.lines); heard|=1>(cur.height=('continue'===ps)?0.5:1); } return heard; }; return ({lines, put, hears, cur}); };
version https://git-lfs.github.com/spec/v1 oid sha256:7d2aaed108c346009f5e563ce0a7065707fb4147a50b5a54b06f150e02089105 size 2895
version https://git-lfs.github.com/spec/v1 oid sha256:6683c17321dfff35f0f1d1d29d0cd95c721e766edc78a6223d7bfc0801b4d344 size 1476
version https://git-lfs.github.com/spec/v1 oid sha256:47c432b84ffe13730117c609be08a5d1178ee04b6f50d3d1c169b263651fec80 size 4642
version https://git-lfs.github.com/spec/v1 oid sha256:47c0c4ddabd7948468e6fae2927839de30a50dd20bf78317de093ee4038aeb44 size 270810
const sqlSelect = require('./select.js'); /* All basic insert codes will come here. Inserts are minimal means only mandatory (not null) fields will insert. each function will inserts one new row into only one table. No log here. for tables with relation if FOREIGN_KEY is not an Integer, function trys to find an integer id for it. addTableName(db, data) inserts data into TableName all keys with a _ before contains internal data data._clms are column names data._ip ip value of remote computer data._user user account data._tbl table name */ function values(len) { var str = 'VALUES ('; for (var i=1; i<len; i++) { str += '?, '; } str += '?)'; return str; } const bcrypt = require('bcrypt-nodejs'); exports.insert = function (/*basedb*/ db, data, dataArray) { if (dataArray === undefined) { data._clms='('; for(var k in data) { if(data.hasOwnProperty(k) && k[0]!=='_'){ dataArray.push(data[k]); data._clms += k + ','; } } data._clms[data._clms.length-1]=')'; } return db.pRun(`INSERT INTO ${data._tbl} ${data._clms} ${values(data._clmc)};`, dataArray); }; exports.insertjson = function (/*basedb*/ db, data) { data._clms = '('; data._vals = '('; for (var k in data) { if (data.hasOwnProperty(k) && k[0]!=='_') { data._clms += k + ','; data._vals += "'" + data[k] + "'" + ','; } } data._clms = data._clms.substr(0, data._clms.length-1) + ')'; data._vals = data._vals.substr(0, data._vals.length-1) + ')'; return db.pRun(`INSERT INTO ${data._tbl} ${data._clms} VALUES${data._vals};`); }; exports.addUser = function (/*basedb*/ db, data) { return exports.insert(db, data, [data.account, bcrypt.hashSync(data.password), data.fname, data.lname, data.pcode, data.workunit, data.sysadmin, data.github, data.telegram]); }; exports.addReportClass = function (/*basedb*/ db, data) { return new Promise((resolve, reject) => { var p = (Number.isInteger(data.user_owner) ? Promise.resolve(data.user_owner) : sqlSelect.idfordata(db, {_tbl:'tblUser', _where: 'account', account:data.user_owner})); p.then((owner_id)=>{ exports.insert(db, data, [data.caption, data.duration, owner_id, data.caption_cat_1, data.caption_cat_2, data.caption_cat_3, data.caption_variable]).then(resolve); }).catch((err)=>{ reject('addReportClass() fails to find owner ' + err); }); }); }; exports.addVariableCat_1 = function (/*basedb*/ db, data) { return db.pRun(`INSERT INTO ${data._tbl} ${data._clms} ${values(data._clmc)};`, [data.caption, data.code, data.weight]); }; exports.addVariableCat_2 = function (/*basedb*/ db, data) { return new Promise((resolve, reject) => { var p = (Number.isInteger(data.variablecat_1_id)) ? Promise.resolve(data.variablecat_1_id) : sqlSelect.idfordata(db, {_tbl:'tblVariableCat_1', _where: 'caption', caption:data.variablecat_1_id}); p.then((VariableCat_1_id)=>{ exports.insert(db, data, [data.caption, data.code, VariableCat_1_id, data.weight]).then(resolve); }).catch((err)=>{ reject('addVariableCat_2() fails with: ' + err); }); }); }; exports.addVariableCat_3 = function (/*basedb*/ db, data) { return new Promise((resolve, reject) => { var p = (Number.isInteger(data.variablecat_2_id)) ? Promise.resolve(data.variablecat_2_id) : sqlSelect.idfordata(db, {_tbl:'tblVariableCat_2', _where: 'caption', caption:data.variablecat_2_id}); p.then((VariableCat_2_id)=>{ exports.insert(db, data, [data.caption, data.code, VariableCat_2_id, data.weight]).then(resolve); }).catch((err)=>{ reject('addVariableCat_3() fails to fined related records with: ' + err); }); }); }; exports.addVariableDef = function (/*basedb*/ db, data) { return new Promise((resolve, reject) => { var p1 = (Number.isInteger(data.user_owner) ? Promise.resolve(data.user_owner) : sqlSelect.idfordata(db, {_tbl:'tblUser', _where: 'account', account:data.user_owner})); var p2 = (Number.isInteger(data.user_provider) ? Promise.resolve(data.user_provider) : sqlSelect.idfordata(db, {_tbl:'tblUser', _where: 'account', account:data.user_provider})); var p3 = (Number.isInteger(data.user_reviewer) ? Promise.resolve(data.user_reviewer) : sqlSelect.idfordata(db, {_tbl:'tblUser', _where: 'account', account:data.user_reviewer})); Promise.all([p1, p2, p3]).then(([user_owner, user_provider, user_reviewer])=>{ db.pRun(`INSERT INTO ${data._tbl} ${data._clms} ${values(data._clmc)};`, [data.unit, data.caption, data.code, user_provider, user_owner, user_reviewer]) .then(resolve); }).catch((err)=>{ reject('addVariableDef() fails (related records?) with: ' + err); }); }); }; exports.addReportClassVariable = function (/*basedb*/ db, data) { return new Promise((resolve, reject) => { var p1 = (Number.isInteger(data.variabledef_id)) ? Promise.resolve(data.variabledef_id) : sqlSelect.idfordata(db, {_tbl:'tblVariableDef', _where:'caption', caption:data.variabledef_id}); var p2 = (Number.isInteger(data.reportclass_id)) ? Promise.resolve(data.reportclass_id) : sqlSelect.idfordata(db, {_tbl:'tblReportClass', _where:'caption', caption:data.reportclass_id}); Promise.all([p1, p2]).then(([variabledef_id, reportclass_id])=>{ exports.insert(db, data, [reportclass_id, variabledef_id, data.weight]).then(resolve); }).catch((err)=>{ reject('addReportClassVariable() fails (related records?) with: ' + err); }); }); }; exports.createReport = function (/*basedb*/ db, data) { return new Promise((resolve, reject) => { db.pRun(`INSERT INTO tblReport(caption, title, time_limit, user_owner, user_creator, ip_user, time_create, time_reference) SELECT tblReportClass.caption, '${data.title}', ${data.time_limit}, tblReportClass.user_owner, ${data.user_creator}, '${data.ip_user}', ${data.time_create}, ${data.time_reference} FROM tblReportClass WHERE tblReportClass.id=${data.id}`) .then((newreport)=>{ db.pRun(`INSERT INTO tblVariable(unit, caption, code, user_provider, user_owner, user_reviewer, time_reference, limit_lower, limit_upper) SELECT tblVariableDef.unit, tblVariableDef.caption, tblVariableDef.code, tblVariableDef.user_provider, tblVariableDef.user_owner, tblVariableDef.user_reviewer, ${data.time_reference}, tblVariableDef.limit_lower, tblVariableDef.limit_upper FROM tblVariableDef INNER JOIN tblReportClassVariable ON tblReportClassVariable.variabledef_id = tblVariableDef.id WHERE tblReportClassVariable.reportclass_id = ${data.id}`) .then(()=>{ db.pRun(`INSERT INTO tblReportVariable(report_id, variable_id, variablecat_3_id, weight) SELECT ${newreport.lastID}, tblVariable.id, variablecat_3_id, weight FROM tblReportClassVariable INNER JOIN tblVariableDef ON tblVariableDef.id = tblReportClassVariable.variabledef_id INNER JOIN tblVariable ON tblVariableDef.code = tblVariable.code WHERE reportclass_id = ${data.id} AND time_reference = ${data.time_reference}`) .then(()=>{ resolve(newreport); }); }) }); }); }; exports.addVariable = function (/*basedb*/ db, data) { return exports.insert(db, data, [data.piclass_id, data.report_id, data.unit, data.caption, data.user_provider, data.user_owner, data.user_reviewer, data.attribute]); }; //exports.addReportVariable = function (/*basedb*/ db, data) { // //TODO //}; exports.addAttachment = function (/*basedb*/ db, data) { return exports.insert(db, data, [data.report_id, data.pathfile, data.user_attach, data.ip_user, data.time_attach, data.attribute]); }; exports.addValue = function (/*basedb*/ db, data) { return exports.insert(db, data, [data.pi_id, data.value, data.time_update, data.user_update, data.ip_user , data.attribute]); }; exports.addTarget = function (/*basedb*/ db, data) { return exports.insert(db, data, [data.pi_id, data.value, data.time_target, data.time_update, data.user_update , data.ip_user, data.attribute]); }; exports.addMessage = function (/*basedb*/ db, data) { return exports.insert(db, data, [data.textmessage, data.time_message, data.ip_sender, data.user_sender, data.user_reciever, data.pi_id, data.time_read, data.attribute]); };
// Prevent event for IE8 and modern browsers function PreventEvent( event ) { event.preventDefault ? event.preventDefault() : ( event.returnValue = false ); } // Change EventListener to attachEvent function AddEvent( elements, event, onEvent ) { if( elements ) { // Create an array of elements if a singular or array of elements is passed in if( elements.length === undefined ) { elements = [ elements ]; } // For each element add the correct event listener for( var i = 0; i < elements.length; i++ ) { if( typeof Element.prototype.addEventListener === "undefined" ) { // Make sure that we pass this ( function( element, event ) { element.attachEvent( "on" + event, function( actualEvent ) { onEvent( actualEvent, element ); }); })( elements[ i ], event ); } else { ( function( element, event ) { element.addEventListener( event, function( actualEvent ) { onEvent( actualEvent, element ); }); })( elements[ i ], event ); } } } } var accordions = document.querySelectorAll( '.js-au-accordion' ); AddEvent( accordions, 'click', function( event, $this ) { PreventEvent( event ); AU.accordion.Toggle( $this ); });
/** * http://www.nodejs.org/api/cluster.html#cluster_event_fork * * */ var cluster = require('cluster'); var http = require('http'); var numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for ( var i = 0; i < numCPUs; i++) { cluster.fork(); } var timeouts = []; function errorMsg() { console.error("Something must be wrong with the connection ..."); } cluster.on('fork', function(worker) { timeouts[worker.id] = setTimeout(errorMsg, 2000); }); cluster.on('listening', function(worker, address) { clearTimeout(timeouts[worker.id]); }); cluster.on('exit', function(worker, code, signal) { clearTimeout(timeouts[worker.id]); errorMsg(); }); } else { // Workers can share any TCP connection // In this case its a HTTP server http.createServer(function(req, res) { res.writeHead(200); res.end("hello world\n"); }).listen(8000); }
'use strict'; module.exports = { help: 'Return a given number of objects from the JSON input. If the input has fewer objects than the given number, all of the input is returned.', usageString: '<count>', minPositionalArguments: 1, maxPositionalArguments: 1, options: [ { names: ['from-end', 'e'], type: 'bool', help: 'Remove objects from the end of the input rather than the beginning.' } ], outputsObject: true, needsSandbox: false, hasWithClauseOpt: false, handler: takeCommandHandler }; function takeCommandHandler(runtimeSettings, config, opts) { let count = parseInt(opts._args[0]); if(isNaN(count)) { console.error('Invalid count parameter: "' + opts._args[0] + '". Expected an integer.'); process.exit(1); } let data = runtimeSettings.data; if(!Array.isArray(data)) data = [data]; if(opts.from_end) count = -count; if(count < 0) return data.slice(count); return data.slice(0, count); }
/** * inferno-firebase * * Copyright © 2017 Magnus Bergman <hello@magnus.sexy>. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ export Provider from './Provider'; export connect from './connect';
import "@babel/polyfill"; import "!style-loader!css-loader!postcss-loader!sass-loader!./styles/normalize.css"; import "!style-loader!css-loader!postcss-loader!sass-loader!./styles/style.css"; import "./components"; import "./scenery"; import "./scenes"; import "./systems/SeaLevel"; Game.start(false); /** * Screen size management */ const scaleGame = () => { const stage = document.getElementById("cr-stage"); const stageHeight = stage.clientHeight; const stageWidth = stage.clientWidth; const viewportHeight = window.innerHeight - 60; const viewportWidth = window.innerWidth; const ratioY = viewportHeight / stageHeight; const ratioX = viewportWidth / stageWidth; const ratio = Math.min(ratioY, ratioX); stage.style.transform = `scale(${ratio})`; const left = Math.max(0, (viewportWidth - stageWidth * ratio) * 0.5); stage.style.left = `${left}px`; document.getElementsByTagName("footer")[0].style.top = `${576 * ratio}px`; }; window.addEventListener("resize", scaleGame); // Handle the fullscreen button const button = document.querySelector("button"); button.addEventListener("click", () => { const theater = document.getElementById("theater"); theater.requestFullscreen(); document.body.classList.add("fullscreen"); scaleGame(); document.addEventListener("fullscreenchange", () => { if (!document.fullscreenElement) { // exit fullscreen code here document.body.classList.remove("fullscreen"); scaleGame(); } }); }); setTimeout(scaleGame, 0); /* eslint-env node */ document.getElementById("version").textContent = process.env.VERSION;
angular.module('locmap.controllers') .controller('LocationsCtrl', function($scope, $state, ResourcesService, UserService, ModalsService) { $scope.locations = []; ResourcesService.get('users/' + UserService.getId()).then(function(data) { $scope.locations = data.locations; }, function(err) { console.log(err); }); $scope.deleteLocation = function(id) { console.log(id); var r = confirm("Do you really want to delete this location?"); if (r == true) { ResourcesService.delete('/locations/' + id).then(function(data) { $state.go($state.current, {}, {reload: true}); }); } } });
/** * Gen 3 moves */ function clampIntRange(num, min, max) { num = Math.floor(num); if (num < min) num = min; if (typeof max !== 'undefined' && num > max) num = max; return num; } exports.BattleMovedex = { absorb: { inherit: true, pp: 20 }, acid: { inherit: true, secondary: { chance: 10, boosts: { def: -1 } } }, ancientpower: { inherit: true, isContact: true }, assist: { inherit: true, desc: "The user performs a random move from any of the Pokemon on its team. Assist cannot generate itself, Chatter, Copycat, Counter, Covet, Destiny Bond, Detect, Endure, Feint, Focus Punch, Follow Me, Helping Hand, Me First, Metronome, Mimic, Mirror Coat, Mirror Move, Protect, Sketch, Sleep Talk, Snatch, Struggle, Switcheroo, Thief or Trick.", onHit: function(target) { var moves = []; for (var j=0; j<target.side.pokemon.length; j++) { var pokemon = target.side.pokemon[j]; if (pokemon === target) continue; for (var i=0; i<pokemon.moves.length; i++) { var move = pokemon.moves[i]; var noAssist = { assist:1, chatter:1, copycat:1, counter:1, covet:1, destinybond:1, detect:1, endure:1, feint:1, focuspunch:1, followme:1, helpinghand:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, protect:1, sketch:1, sleeptalk:1, snatch:1, struggle:1, switcheroo:1, thief:1, trick:1 }; if (move && !noAssist[move]) { moves.push(move); } } } var move = ''; if (moves.length) move = moves[this.random(moves.length)]; if (!move) { return false; } this.useMove(move, target); } }, astonish: { inherit: true, basePowerCallback: function(pokemon, target) { if (target.volatiles['minimize']) return 60; return 30; } }, beatup: { inherit: true, basePower: 10, basePowerCallback: null }, bide: { inherit: true, accuracy: 100, priority: 0 }, bind: { inherit: true, accuracy: 75 }, blizzard: { inherit: true, onModifyMove: null }, bonerush: { inherit: true, accuracy: 80 }, brickbreak: { inherit: true, onTryHit: function(pokemon) { pokemon.side.removeSideCondition('reflect'); pokemon.side.removeSideCondition('lightscreen'); } }, bulletseed: { inherit: true, basePower: 10 }, charge: { inherit: true, boosts: false }, clamp: { inherit: true, accuracy: 75, pp: 10 }, cottonspore: { inherit: true, accuracy: 85 }, counter: { inherit: true, damageCallback: function(pokemon) { if (pokemon.lastAttackedBy && pokemon.lastAttackedBy.thisTurn && (this.getCategory(pokemon.lastAttackedBy.move) === 'Physical' || this.getMove(pokemon.lastAttackedBy.move).id === 'hiddenpower')) { return 2 * pokemon.lastAttackedBy.damage; } this.add('-fail', pokemon); return false; } }, covet: { inherit: true, basePower: 40, isContact: false }, crabhammer: { inherit: true, accuracy: 85 }, crunch: { inherit: true, secondary: { chance: 20, boosts: { spd: -1 } } }, curse: { inherit: true, type: "???" }, detect: { inherit: true, //desc: "", priority: 3 }, dig: { inherit: true, basePower: 60 }, disable: { inherit: true, accuracy: 55, isBounceable: false, volatileStatus: 'disable', effect: { durationCallback: function() { return this.random(2,6); }, noCopy: true, onStart: function(pokemon) { if (!this.willMove(pokemon)) { this.effectData.duration++; } if (!pokemon.lastMove) { return false; } var moves = pokemon.moveset; for (var i=0; i<moves.length; i++) { if (moves[i].id === pokemon.lastMove) { if (!moves[i].pp) { return false; } else { this.add('-start', pokemon, 'Disable', moves[i].move); this.effectData.move = pokemon.lastMove; return; } } } return false; }, onEnd: function(pokemon) { this.add('-message', pokemon.name+' is no longer disabled! (placeholder)'); }, onBeforeMove: function(attacker, defender, move) { if (move.id === this.effectData.move) { this.add('cant', attacker, 'Disable', move); return false; } }, onModifyPokemon: function(pokemon) { var moves = pokemon.moveset; for (var i=0; i<moves.length; i++) { if (moves[i].id === this.effectData.move) { moves[i].disabled = true; } } } } }, dive: { inherit: true, basePower: 60 }, doomdesire: { inherit: true, accuracy: 85, basePower: 120, onModifyMove: function(move) { move.type = '???'; } }, dreameater: { inherit: true, desc: "Deals damage to one adjacent target, if it is asleep and does not have a Substitute. The user recovers half of the HP lost by the target, rounded up. If Big Root is held by the user, the HP recovered is 1.3x normal, rounded half down.", onTryHit: function(target) { if (target.status !== 'slp' || target.volatiles['substitute']) { this.add('-immune', target, '[msg]'); return null; } } }, encore: { inherit: true, isBounceable: false, volatileStatus: 'encore', effect: { durationCallback: function() { return this.random(3,7); }, onStart: function(target) { var noEncore = {encore:1, mimic:1, mirrormove:1, sketch:1, transform:1}; var moveIndex = target.moves.indexOf(target.lastMove); if (!target.lastMove || noEncore[target.lastMove] || (target.moveset[moveIndex] && target.moveset[moveIndex].pp <= 0)) { // it failed this.add('-fail', target); delete target.volatiles['encore']; return; } this.effectData.move = target.lastMove; this.add('-start', target, 'Encore'); if (!this.willMove(target)) { this.effectData.duration++; } }, onOverrideDecision: function(pokemon) { return this.effectData.move; }, onResidualOrder: 13, onResidual: function(target) { if (target.moves.indexOf(target.lastMove) >= 0 && target.moveset[target.moves.indexOf(target.lastMove)].pp <= 0) { // early termination if you run out of PP delete target.volatiles.encore; this.add('-end', target, 'Encore'); } }, onEnd: function(target) { this.add('-end', target, 'Encore'); }, onModifyPokemon: function(pokemon) { if (!this.effectData.move || !pokemon.hasMove(this.effectData.move)) { return; } for (var i=0; i<pokemon.moveset.length; i++) { if (pokemon.moveset[i].id !== this.effectData.move) { pokemon.moveset[i].disabled = true; } } } } }, explosion: { inherit: true, basePower: 500 }, extrasensory: { inherit: true, basePowerCallback: function(pokemon, target) { if (target.volatiles['minimize']) return 160; return 80; } }, extremespeed: { inherit: true, priority: 1 }, feintattack: { inherit: true, isContact: false }, fakeout: { inherit: true, priority: 1, isContact: false }, firespin: { inherit: true, accuracy: 70, basePower: 15 }, flail: { inherit: true, accuracy: 100, basePower: 0, basePowerCallback: function(pokemon, target) { var hpPercent = pokemon.hp * 100 / pokemon.maxhp; if (hpPercent <= 5) { return 200; } if (hpPercent <= 10) { return 150; } if (hpPercent <= 20) { return 100; } if (hpPercent <= 35) { return 80; } if (hpPercent <= 70) { return 40; } return 20; }, isViable: true, pp: 15, priority: 0, isContact: true, secondary: false, target: "normal", type: "Normal" }, flash: { inherit: true, accuracy: 70 }, fly: { inherit: true, basePower: 70 }, foresight: { inherit: true, isBounceable: false }, furycutter: { inherit: true, basePower: 10 }, futuresight: { inherit: true, accuracy: 90, basePower: 80, pp: 15, onModifyMove: function(move) { move.type = '???'; } }, gigadrain: { inherit: true, basePower: 60, pp: 5 }, glare: { inherit: true, accuracy: 75, affectedByImmunities: true }, growth: { inherit: true, onModifyMove: null, boosts: { spa: 1 } }, hiddenpower: { num: 237, accuracy: 100, basePower: 0, basePowerCallback: function(pokemon) { return pokemon.hpPower || 70; }, id: "hiddenpower", isViable: true, name: "Hidden Power", pp: 15, priority: 0, onModifyMove: function(move, pokemon) { move.type = pokemon.hpType || 'Dark'; }, secondary: false, target: "normal", type: "Normal" }, highjumpkick: { inherit: true, basePower: 85, pp: 20, onMoveFail: function(target, source, move) { if (target.runImmunity('Fighting')) { var damage = this.getDamage(source, target, move, true); this.damage(clampIntRange(damage/2, 1, Math.floor(target.maxhp/2)), source); } } }, hypnosis: { inherit: true, accuracy: 60 }, iciclespear: { inherit: true, basePower: 10 }, jumpkick: { inherit: true, basePower: 70, pp: 25, onMoveFail: function(target, source, move) { if (target.runImmunity('Fighting')) { var damage = this.getDamage(source, target, move, true); this.damage(clampIntRange(damage/2, 1, Math.floor(target.maxhp/2)), source); } } }, leafblade: { inherit: true, basePower: 70 }, megadrain: { inherit: true, pp: 10 }, metronome: { inherit: true, onHit: function(target) { var moves = []; for (var i in exports.BattleMovedex) { var move = exports.BattleMovedex[i]; if (i !== move.id) continue; if (move.isNonstandard) continue; var noMetronome = { assist:1, counter:1, covet:1, destinybond:1, detect:1, endure:1, focuspunch:1, followme:1, helpinghand:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, protect:1, sketch:1, sleeptalk:1, snatch:1, struggle:1, thief:1, trick:1 }; if (!noMetronome[move.id] && move.num < 355) { moves.push(move.id); } } var move = ''; if (moves.length) move = moves[this.random(moves.length)]; if (!move) return false; this.useMove(move, target); } }, minimize: { inherit: true, boosts: { evasion: 1 } }, mirrormove: { inherit: true, accuracy: true, basePower: 0, category: "Status", pp: 20, priority: 0, isNotProtectable: true, onTryHit: function(target) { var noMirrorMove = {acupressure:1, afteryou:1, aromatherapy:1, chatter:1, conversion2:1, curse:1, doomdesire:1, feint:1, finalgambit:1, focuspunch:1, futuresight:1, gravity:1, guardsplit:1, hail:1, haze:1, healbell:1, healpulse:1, helpinghand:1, lightscreen:1, luckychant:1, mefirst:1, mimic:1, mirrorcoat:1, mirrormove:1, mist:1, mudsport:1, naturepower:1, perishsong:1, powersplit:1, psychup:1, quickguard:1, raindance:1, reflect:1, reflecttype:1, roleplay:1, safeguard:1, sandstorm:1, sketch:1, spikes:1, spitup:1, stealthrock:1, sunnyday:1, tailwind:1, taunt:1, teeterdance:1, toxicspikes:1, transform:1, watersport:1, wideguard:1}; if (!target.lastMove || noMirrorMove[target.lastMove] || this.getMove(target.lastMove).target === 'self') { return false; } }, onHit: function(target, source) { this.useMove(this.lastMove, source); }, secondary: false, target: "normal", type: "Flying" }, naturepower: { inherit: true, accuracy: true, onHit: function(target) { this.useMove('swift', target); } }, needlearm: { inherit: true, basePowerCallback: function(pokemon, target) { if (target.volatiles['minimize']) return 120; return 60; } }, odorsleuth: { inherit: true, isBounceable: false }, outrage: { inherit: true, basePower: 90, pp: 15 }, overheat: { inherit: true, isContact: true }, payback: { inherit: true, basePowerCallback: function(pokemon, target) { if (this.willMove(target)) { return 50; } return 100; } }, petaldance: { inherit: true, basePower: 70, pp: 20 }, poisongas: { inherit: true, accuracy: 55, target: "normal" }, protect: { inherit: true, priority: 3 }, recover: { inherit: true, pp: 20 }, roar: { inherit: true, isBounceable: false }, rockblast: { inherit: true, accuracy: 80 }, rocksmash: { inherit: true, basePower: 20 }, sandtomb: { inherit: true, accuracy: 70, basePower: 15 }, scaryface: { inherit: true, accuracy: 90 }, selfdestruct: { inherit: true, basePower: 400 }, skillswap: { inherit: true, onHit: function(target, source) { var targetAbility = target.ability; var sourceAbility = source.ability; if (!target.setAbility(sourceAbility) || !source.setAbility(targetAbility)) { target.ability = targetAbility; source.ability = sourceAbility; return false; } this.add('-activate', source, 'move: Skill Swap'); } }, spikes: { inherit: true, isBounceable: false }, spite: { inherit: true, isBounceable: false, onHit: function(target) { var roll = this.random(2,6); if (target.deductPP(target.lastMove, roll)) { this.add("-activate", target, 'move: Spite', target.lastMove, roll); return; } return false; }, }, stockpile: { inherit: true, pp: 10, boosts: false }, struggle: { inherit: true, accuracy: true, basePower: 50, pp: 1, noPPBoosts: true, priority: 0, isContact: true, beforeMoveCallback: function(pokemon) { this.add('-message', pokemon.name+' has no moves left! (placeholder)'); }, onModifyMove: function(move) { move.type = '???'; }, recoil: [1,2], secondary: false, target: "normal", type: "Normal" }, tackle: { inherit: true, accuracy: 95, basePower: 35 }, tailglow: { inherit: true, boosts: { spa: 2 } }, taunt: { inherit: true, isBounceable: false, effect: { duration: 2, onStart: function(target) { this.add('-start', target, 'move: Taunt'); }, onResidualOrder: 12, onEnd: function(target) { this.add('-end', target, 'move: Taunt'); }, onModifyPokemon: function(pokemon) { var moves = pokemon.moveset; for (var i=0; i<moves.length; i++) { if (this.getMove(moves[i].move).category === 'Status') { moves[i].disabled = true; } } }, onBeforeMove: function(attacker, defender, move) { if (move.category === 'Status') { this.add('cant', attacker, 'move: Taunt', move); return false; } } } }, thrash: { inherit: true, basePower: 90, pp: 20 }, tickle: { inherit: true, notSubBlocked: true }, torment: { inherit: true, isBounceable: false }, toxic: { inherit: true, accuracy: 85 }, uproar: { inherit: true, basePower: 50 }, vinewhip: { inherit: true, pp: 10 }, volttackle: { inherit: true, recoil: [1,3], secondary: false }, waterfall: { inherit: true, secondary: false }, whirlpool: { inherit: true, accuracy: 70, basePower: 15 }, whirlwind: { inherit: true, isBounceable: false }, wish: { inherit: true, effect: { duration: 2, onResidualOrder: 2, onEnd: function(side) { var target = side.active[this.effectData.sourcePosition]; if (!target.fainted) { var source = this.effectData.source; var damage = this.heal(target.maxhp/2, target, target); if (damage) this.add('-heal', target, target.getHealth, '[from] move: Wish', '[wisher] '+source.name); } } } }, wrap: { inherit: true, accuracy: 85 }, zapcannon: { inherit: true, basePower: 100 }, magikarpsrevenge: null };
var analytics = require('../index.js'); var fs = require('fs'); /** * Indicators selected for calculation * @type {Array} */ var indicators = [ 'CCI', 'MACD', 'MACD_Signal', 'MACD_Histogram', 'Momentum', 'RSI', 'BOP', 'ATR', 'SAR', 'SMA15_SMA50', 'Stochastic' ]; var stopLoss = 0.0030; var takeProfit = 0.0030; /** * Training csv file worth of 6 month data * @type {String} */ var trainingFile = './data/DAT_MT_EURUSD_M1_2015.csv'; /** * Testing data file worth of 1 month data. * The strategy trained on the training data set will be applied * to this data set to verify the output strategy * * @type {String} */ var testingFile = './data/DAT_MT_EURUSD_M1_201601.csv'; /** * Loads candlestick data from a file and then fires a callback with the data * as a parameter * @param {String} inputFile Path to the csv file * @param {Function} callback Callback function that is fired after data * is loaded */ function loadCsvData(inputFile, callback) { var csvContent = ''; var stream = fs.createReadStream(inputFile) .on('readable', function() { var buf = stream.read(); if (buf) { csvContent += buf.toString(); } }) .on('end', function() { var candlesticks = parseCsv(csvContent); candlesticks.sort(function(a, b) { a.time - b.time; }); callback(candlesticks); }); } /** * Calculates and presents potential revenue of a given strategy for given * candlesticks */ function calculateTrades(candlesticks, strategy) { var trades = getTrades(candlesticks, strategy); var totalRevenue = 0; var totalNoOfTrades = 0; var numberOfProfitTrades = 0; var numberOfLossTrades = 0; var maximumLoss = 0; for (var i = 0; i < trades.length; i++) { var revenue; if (stopLoss < trades[i].MaximumLoss) { revenue = -stopLoss; } else if (takeProfit < trades[i].MaximumProfit && (!trades[i].ProfitBeforeLoss || takeProfit > trades[i].MaximumProfit)) { revenue = takeProfit; } else { revenue = trades[i].Revenue || 0; } if (revenue > 0) numberOfProfitTrades++; else numberOfLossTrades++; totalNoOfTrades++; totalRevenue += revenue; if (maximumLoss < trades[i].MaximumLoss) maximumLoss = trades[i].MaximumLoss; } console.log('Total theoretical revenue is: ' + totalRevenue + ' PIPS'); console.log('Maximum theoretical loss is: ' + maximumLoss + ' PIPS'); console.log('Total number of Profitable trades is: ' + numberOfProfitTrades); console.log('Total number of loss trades is: ' + numberOfLossTrades); console.log('Total number of trades is: ' + totalNoOfTrades); } /** * Returns an object representing buy/sell strategy * @param {Object} candlesticks Input candlesticks for strategy estimation */ function createStrategy(candlesticks, testing30MinuteCandlesticks) { var lastFitness = -1; return analytics.findStrategy(candlesticks, { populationCount: 3000, generationCount: 100, selectionAmount: 10, leafValueMutationProbability: 0.3, leafSignMutationProbability: 0.1, logicalNodeMutationProbability: 0.05, leafIndicatorMutationProbability: 0.2, crossoverProbability: 0.03, indicators: indicators }, function(strategy, fitness, generation) { console.log('---------------------------------'); console.log('Fitness: ' + fitness + '; Generation: ' + generation); if (lastFitness == fitness) return; lastFitness = fitness; console.log('-----------Training--------------'); calculateTrades(candlesticks, strategy); console.log('-----------Testing--------------'); calculateTrades(testing30MinuteCandlesticks, strategy); }); } /** * Gets an array of trades using a set of candlesticks and strategy * @param {Object} candlesticks Input candlesticks for trade estimation * @param {Object} strategy Strategy obtained by the findStrategy function */ function getTrades(candlesticks, strategy) { return analytics.getTrades(candlesticks, { strategy: strategy }); } /** * Parses the given csv and returns array of candlesticks * @param {String} text The csv file content */ function parseCsv(text) { var candlesticks = []; var lines = text.split('\n'); for (var i = 0; i < lines.length; i++) { var parts = lines[i].split(','); var date = new Date(parts[0] + ' ' + parts[1]); var time = (date.getTime()) / 1000; if (time) { candlesticks.push({ open: parts[2], high: parts[3], low: parts[4], close: parts[5], time: time }); } } return candlesticks; } /** * Converts candlesticks from lower timeframe to 30 minute timeframe */ function convertTo30MOhlc(candlesticks) { var n = analytics.convertOHLC(candlesticks, 1800); return n; } console.log('Loading training data set'); loadCsvData(testingFile, function(testingCandlesticks) { loadCsvData(trainingFile, function(candlesticks) { var thirtyMinuteCandlesticks = convertTo30MOhlc(candlesticks); var testing30MinuteCandlesticks = convertTo30MOhlc(testingCandlesticks); console.log('Calculating strategy') createStrategy(thirtyMinuteCandlesticks, testing30MinuteCandlesticks) .then(function(strategy) { console.log('------------Strategy-------------'); console.log(JSON.stringify(strategy, null, 4)); console.log('---------------------------------'); calculateTrades(testing30MinuteCandlesticks, strategy); }); }); });
import React from 'react'; import { Link } from 'react-router-dom'; export const Layout = props => ( <div className="app-container"> <header> <Link to="/"> <img className="logo" src="/img/tinglado-logo.png" alt="Teatro El Tinglado" /> </Link> </header> <div className="app-content">{props.children}</div> <footer> </footer> </div> ); export default Layout;
'use strict'; function podcastIndexOrgService($http, $window) { const AUTH_KEY = 'NUKSUA3RXTJ8AEQPHCNP'; const AUTH_SECRET = 'BufqJNuREeuP2ThUMUq55z2A3peQt#bsw$Zdsvc3'; var service = { search: search, getPodcastValue: getPodcastValue }; return service; function getAuthHeaders() { const authDate = Math.floor((new Date()).valueOf() / 1000); return $window.crypto.subtle.digest('SHA-1', (new $window.TextEncoder()).encode(AUTH_KEY + AUTH_SECRET + authDate)).then((authArrayBuffer) => { return { 'X-Auth-Date': authDate, 'X-Auth-Key': AUTH_KEY, 'User-Agent': 'podStation', 'Authorization': buf2hex(authArrayBuffer) } }); } function search(searchTerms) { return getAuthHeaders().then((headers) => { return $http.get('https://api.podcastindex.org/api/1.0/search/byterm', { headers: headers, params: { "q": searchTerms } }); }); } function getPodcastValue(feedUrl) { return getAuthHeaders().then((headers) => { return $http.get('https://api.podcastindex.org/api/1.0/value/byfeedurl', { headers: headers, params: { url: feedUrl } }); }); } // https://stackoverflow.com/a/40031979/4274827 function buf2hex(buffer) { return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join(''); } } export default podcastIndexOrgService;
angular.module('conapps').directive('estimatesAddProductsFilters', estimatesAddProductsFilters); function estimatesAddProductsFilters(){ return { restrict : 'E', replace : true, templateUrl : 'meraki-estimates/client/views/estimates-add-products-filters.template.ng.html', controller : controller, controllerAs : 'vm', bindToController : true, scope : { line : '=', showSelected : '=', }, link: link } } controller.$inject = ['estimateEditService']; function controller(es){ var vm = this; vm.currentLine = ''; vm.filterBy = filterBy; vm.toggleSelected = toggleSelected; vm.selProdLen = es.selectedProductsLength; /////////// function filterBy(line){ if (!line) return; if (vm.currentLine === 'Selected') toggleSelected(); if (line === vm.currentLine){ vm.line = ''; vm.currentLine = ''; } else { vm.line = line; vm.currentLine = line; } } function toggleSelected(){ toggleCurrentLine(); toggleShowSelected(); } function toggleCurrentLine(){ if (vm.currentLine === 'Selected'){ vm.currentLine = ''; vm.line = ''; } else { vm.currentLine = 'Selected'; } } function toggleShowSelected(){ vm.showSelected = (vm.currentLine === 'Selected'); } } function link(scope, element){ scope.$watch('vm.currentLine', function(line){ element.find('.btn').removeClass('active'); if (!angular.isString(line) || line === '') return; element.find('[name=' + line.replace(' ', '_') + ']').addClass('active'); }); }
import deepfreeze from 'deepfreeze'; import processSections from '../processSections'; const sections = deepfreeze([ { sections: [ { name: 'Components', components: [ { props: { displayName: 'Button', }, module: 1, }, ], }, ], }, ]); describe('processSections', () => { it('should recursively process all sections and components', () => { const result = processSections(sections); expect(result[0].sections[0].components[0].name).toBe('Button'); }); it('should set visibleName property on each section', () => { const result = processSections(sections); expect(result[0].sections[0].visibleName).toBe('Components'); }); });
/** * Author: Jeff Whelpley * Date: 2/25/14 * * Build for fakeblock */ var gulp = require('gulp'); var taste = require('taste'); var batter = require('batter'); batter.whip(gulp, taste, {});
var cl = jQuery('table.summaryTable tr').has('th:contains("Inheritance")').find('td a:first').text().trim(); if (cl != "") { var clextends = jQuery('table.summaryTable tr').has('th:contains("Inheritance")').find('td a:nth-child(2)').text(); var desc = jQuery('div.class-description p strong').first().text(); var is_static = false; if (jQuery('div.detail-header span.detail-header-tag.small:contains("static")').length) { is_static = true; } WeBuilderAddClass(cl, desc, "", clextends, is_static); jQuery('div.method-doc div.detail-header').each(function(i) { var scope = jQuery(this).find('span.detail-header-tag').text().trim(); if (scope.indexOf("public") > -1 || scope == "") { var desc = jQuery(this).next('div.doc-description').find('p').first().text().normalize_spaces(); var funcname = jQuery(this).clone(); funcname.find('*').remove(); funcname = funcname.text().trim(); funcname = funcname.replace(/\(\)/, ""); var func = jQuery(this).nextAll('table.detail-table').first().find('td.signature').text().normalize_spaces(); var fnArgsRegex = /\(.*\)/; var funcargs = func.match(fnArgsRegex); var funcres = jQuery(this).nextAll('table.detail-table').first().find('th:contains("return")').next('td.param-type-col').first().text().normalize_spaces(); var is_static = "0"; if (scope.indexOf("static") > -1) { is_static = "1"; } WeBuilderAddMethod(cl, funcname, funcargs[0], funcres, desc, is_static); } }); jQuery('div.property-doc div.detail-header').each(function(i) { var scope = jQuery(this).find('span.detail-header-tag').text().trim(); if (scope.indexOf("public") > -1 || scope == "") { var desc = jQuery(this).next('div.doc-description').find('p').first().text().normalize_spaces(); var fieldname = jQuery(this).clone(); fieldname.find('*').remove(); fieldname = fieldname.text().trim(); var fieldtype = jQuery(this).nextAll('div.signature').first().find('span.signature-type').text().normalize_spaces(); var is_static = "0"; if (scope.indexOf("static") > -1) { is_static = "1"; } WeBuilderAddProperty(cl, fieldname, fieldtype, desc, is_static); } }); }
export function canUndo (state) { return state.undoables.past.length > 0; } export function canRedo (state) { return state.undoables.future.length > 0; }
'use strict'; /* Controllers */ angular.module('myApp.controllers', []). controller('MyCtrl1', function($scope) { $scope.form = { firstName: 'Joe', lastName: 'Bloggs', dateOfBirth: '11-01-1980', nationalities: ['British', 'American'], favouriteColour: 'Green', favouriteThings: ['iPhone', 'iPad'] }; }) .controller('MyCtrl2', [function() { }]);
Serendip.FacetsRenderInactive = (function(serendip){ var my = {}; var _facetsCore = null; init(); function init(){ serendip.on("init.facets.core", function(facetsCore) { _facetsCore = facetsCore; }); serendip.on("render", function(data){ var facets = processFacets(data); var visibleFacets = getOnlyVisibleFacetRowValues(facets); serendip.trigger("render.facets.inactive", facets, visibleFacets); }); }; function processFacets(data){ var facetsData = []; if ( typeof (data.facet_counts) != "undefined") { var facets = getValidFacets(serendip.facets); for (var i = 0; i < facets.length; i++) { var facet = facets[i]; var facetData = processFacetTypes(data, facet); if(facetData != ""){ facetsData.push(facetData); } } } return facetsData; }; function getValidFacets(facets){ var validFacets = []; for (var i = 0; i < facets.length; i++) { var facet = facets[i]; if(isParentActive(facets, facet)){ validFacets.push(facet); } } return validFacets; }; function isParentActive(facets, facet){ var parents = facet.parents; var queries = _facetsCore.getActiveFacetsQueriesMap(); for(var i = 0; i < parents.length;i++){ var parentFacet = parents[i]; for (var id in queries) { if(id == parentFacet.id){ return true; } } } if(parents.length == 0){ return true; } return false; }; function processFacetTypes(data, facet) { var values = facet.process(data); if(values){ return processFacet(data, facet, values); } return ""; }; function processFacet(data, facet, facetArray) { var facetRow = []; facetArray = removeEmptyFacets(facetArray); var len = facetArray.length; for (var i = 0; i < len; i += 2) { var value = facetArray[i]; var count = facetArray[i + 1]; if (value == "") continue; var isActive = isFacetFieldActive(data, facet, value); var facetFieldData = processFacetField(facet, value, count, isActive); if (facetFieldData != ""){ facetRow.push(facetFieldData); } } var facetdata = { facet: facet, values : facetRow }; return facetdata; }; function removeEmptyFacets(facets) { var result = []; for (var i = 0; i < facets.length; i += 2) { var value = facets[i]; var docCount = facets[i + 1]; // -1 is sentinel value for facets that cannot have count if (docCount > 0 || docCount == -1) { result.push(value); result.push(docCount); } } return result; }; function processFacetField(facet, value, count, isActive) { var formattedValue = facet.getFormattedValue(value); value = facet.getFacetValue(value); value = encodeURIComponent(value); return processFacetFieldValue(facet, value, formattedValue, count, isActive); }; function isFacetFieldActive(data, facet, value) { var header = data.responseHeader; if (!header.params) { return false; } if (!header.params.fq) { return false; } var activeFacets = header.params.fq; if (activeFacets) { // Might be single value and not an array... if (!Serendip.Utils.isArray(activeFacets) || activeFacets[0].length == 1) { if (isFacetMatch(activeFacets, facet, value)) { return true; } } else { // If not previous match, we probably have an array with multiple active facets for (var i = 0; i < activeFacets.length; i++) { if (isFacetMatch(activeFacets[i], facet, value)) { return true; } } } } return false; }; function isFacetMatch(activeFacetValue, facet, value) { var facetValue = facet.getFacetValue(value); var activeValues = facet.parseActiveFacetValue(activeFacetValue); for(var i = 0; i < activeValues.length;i++){ var active = activeValues[i]; if(facetValue == active){ return true; } } return false; }; function processFacetFieldValue(facet, value, formattedValue, count, isActive) { if (isActive) return ""; var facetFieldData = { "name" : facet.id, "value" : value, "displayValue" : formattedValue, "countValue" : count, "countValueCls" : "count" + count, "isActive" : "false" }; return facetFieldData; }; function getOnlyVisibleFacetRowValues(facets) { var facetRows = []; for (var i = 0; i < facets.length; i++) { var data = facets[i]; var values = getVisibleFacetRowValues(data.facet, data.values); var row = { facet: data.facet, values: values }; facetRows.push(row); } return facetRows; }; function getVisibleFacetRowValues(facet, values) { var visibleValues = []; var len = Math.min(facet.minFacetsToDisplay, values.length); for (var i = 0; i < len; i++) { visibleValues.push(values[i]); } return visibleValues; }; return my; }(serendip));
/** * @license Highcharts JS v9.3.2 (2021-11-29) * * Vector plot series module * * (c) 2010-2021 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports = factory; } else if (typeof define === 'function' && define.amd) { define('highcharts/modules/vector', ['highcharts'], function (Highcharts) { factory(Highcharts); factory.Highcharts = Highcharts; return factory; }); } else { factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined); } }(function (Highcharts) { var _modules = Highcharts ? Highcharts._modules : {}; function _registerModule(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } } _registerModule(_modules, 'Series/Vector/VectorSeries.js', [_modules['Core/Animation/AnimationUtilities.js'], _modules['Core/Globals.js'], _modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (A, H, SeriesRegistry, U) { /* * * * Vector plot series module * * (c) 2010-2021 Torstein Honsi * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var animObject = A.animObject; var Series = SeriesRegistry.series, ScatterSeries = SeriesRegistry.seriesTypes.scatter; var arrayMax = U.arrayMax, extend = U.extend, merge = U.merge, pick = U.pick; /* * * * Class * * */ /** * The vector series class. * * @private * @class * @name Highcharts.seriesTypes.vector * * @augments Highcharts.seriesTypes.scatter */ var VectorSeries = /** @class */ (function (_super) { __extends(VectorSeries, _super); function VectorSeries() { /* * * * Static Properties * * */ var _this = _super !== null && _super.apply(this, arguments) || this; /* * * * Properties * * */ _this.data = void 0; _this.lengthMax = void 0; _this.options = void 0; _this.points = void 0; return _this; /* eslint-enable valid-jsdoc */ } /* * * * Functions * * */ /* eslint-disable valid-jsdoc */ /** * Fade in the arrows on initializing series. * @private */ VectorSeries.prototype.animate = function (init) { if (init) { this.markerGroup.attr({ opacity: 0.01 }); } else { this.markerGroup.animate({ opacity: 1 }, animObject(this.options.animation)); } }; /** * Create a single arrow. It is later rotated around the zero * centerpoint. * @private */ VectorSeries.prototype.arrow = function (point) { var path, fraction = point.length / this.lengthMax, u = fraction * this.options.vectorLength / 20, o = { start: 10 * u, center: 0, end: -10 * u }[this.options.rotationOrigin] || 0; // The stem and the arrow head. Draw the arrow first with rotation // 0, which is the arrow pointing down (vector from north to south). path = [ ['M', 0, 7 * u + o], ['L', -1.5 * u, 7 * u + o], ['L', 0, 10 * u + o], ['L', 1.5 * u, 7 * u + o], ['L', 0, 7 * u + o], ['L', 0, -10 * u + o] // top ]; return path; }; /* drawLegendSymbol: function (legend, item) { let options = legend.options, symbolHeight = legend.symbolHeight, square = options.squareSymbol, symbolWidth = square ? symbolHeight : legend.symbolWidth, path = this.arrow.call({ lengthMax: 1, options: { vectorLength: symbolWidth } }, { length: 1 }); item.legendLine = this.chart.renderer.path(path) .addClass('highcharts-point') .attr({ zIndex: 3, translateY: symbolWidth / 2, rotation: 270, 'stroke-width': 1, 'stroke': 'black' }).add(item.legendGroup); }, */ /** * @private */ VectorSeries.prototype.drawPoints = function () { var chart = this.chart; this.points.forEach(function (point) { var plotX = point.plotX, plotY = point.plotY; if (this.options.clip === false || chart.isInsidePlot(plotX, plotY, { inverted: chart.inverted })) { if (!point.graphic) { point.graphic = this.chart.renderer .path() .add(this.markerGroup) .addClass('highcharts-point ' + 'highcharts-color-' + pick(point.colorIndex, point.series.colorIndex)); } point.graphic .attr({ d: this.arrow(point), translateX: plotX, translateY: plotY, rotation: point.direction }); if (!this.chart.styledMode) { point.graphic .attr(this.pointAttribs(point)); } } else if (point.graphic) { point.graphic = point.graphic.destroy(); } }, this); }; /** * Get presentational attributes. * @private */ VectorSeries.prototype.pointAttribs = function (point, state) { var options = this.options, stroke = point.color || this.color, strokeWidth = this.options.lineWidth; if (state) { stroke = options.states[state].color || stroke; strokeWidth = (options.states[state].lineWidth || strokeWidth) + (options.states[state].lineWidthPlus || 0); } return { 'stroke': stroke, 'stroke-width': strokeWidth }; }; /** * @private */ VectorSeries.prototype.translate = function () { Series.prototype.translate.call(this); this.lengthMax = arrayMax(this.lengthData); }; /** * A vector plot is a type of cartesian chart where each point has an X and * Y position, a length and a direction. Vectors are drawn as arrows. * * @sample {highcharts|highstock} highcharts/demo/vector-plot/ * Vector pot * * @since 6.0.0 * @extends plotOptions.scatter * @excluding boostThreshold, marker, connectEnds, connectNulls, * cropThreshold, dashStyle, dragDrop, gapSize, gapUnit, * dataGrouping, linecap, shadow, stacking, step, jitter, * boostBlending * @product highcharts highstock * @requires modules/vector * @optionparent plotOptions.vector */ VectorSeries.defaultOptions = merge(ScatterSeries.defaultOptions, { /** * The line width for each vector arrow. */ lineWidth: 2, /** * @ignore */ marker: null, /** * What part of the vector it should be rotated around. Can be one of * `start`, `center` and `end`. When `start`, the vectors will start * from the given [x, y] position, and when `end` the vectors will end * in the [x, y] position. * * @sample highcharts/plotoptions/vector-rotationorigin-start/ * Rotate from start * * @validvalue ["start", "center", "end"] */ rotationOrigin: 'center', states: { hover: { /** * Additonal line width for the vector errors when they are * hovered. */ lineWidthPlus: 1 } }, tooltip: { /** * @default [{point.x}, {point.y}] Length: {point.length} Direction: {point.direction}° */ pointFormat: '<b>[{point.x}, {point.y}]</b><br/>Length: <b>{point.length}</b><br/>Direction: <b>{point.direction}\u00B0</b><br/>' }, /** * Maximum length of the arrows in the vector plot. The individual arrow * length is computed between 0 and this value. */ vectorLength: 20 }); return VectorSeries; }(ScatterSeries)); extend(VectorSeries.prototype, { /** * @ignore * @deprecated */ drawGraph: H.noop, /** * @ignore * @deprecated */ getSymbol: H.noop, /** * @ignore * @deprecated */ markerAttribs: H.noop, parallelArrays: ['x', 'y', 'length', 'direction'], pointArrayMap: ['y', 'length', 'direction'] }); SeriesRegistry.registerSeriesType('vector', VectorSeries); /* * * * Default Export * * */ /* * * * API Options * * */ /** * A `vector` series. If the [type](#series.vector.type) option is not * specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.vector * @excluding dataParser, dataURL, boostThreshold, boostBlending * @product highcharts highstock * @requires modules/vector * @apioption series.vector */ /** * An array of data points for the series. For the `vector` series type, * points can be given in the following ways: * * 1. An array of arrays with 4 values. In this case, the values correspond to * to `x,y,length,direction`. If the first value is a string, it is applied * as the name of the point, and the `x` value is inferred. * ```js * data: [ * [0, 0, 10, 90], * [0, 1, 5, 180], * [1, 1, 2, 270] * ] * ``` * * 2. An array of objects with named values. The following snippet shows only a * few settings, see the complete options set below. If the total number of * data points exceeds the series' * [turboThreshold](#series.area.turboThreshold), this option is not * available. * ```js * data: [{ * x: 0, * y: 0, * name: "Point2", * length: 10, * direction: 90 * }, { * x: 1, * y: 1, * name: "Point1", * direction: 270 * }] * ``` * * @sample {highcharts} highcharts/series/data-array-of-arrays/ * Arrays of numeric x and y * @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/ * Arrays of datetime x and y * @sample {highcharts} highcharts/series/data-array-of-name-value/ * Arrays of point.name and y * @sample {highcharts} highcharts/series/data-array-of-objects/ * Config objects * * @type {Array<Array<(number|string),number,number,number>|*>} * @extends series.line.data * @product highcharts highstock * @apioption series.vector.data */ /** * The length of the vector. The rendered length will relate to the * `vectorLength` setting. * * @type {number} * @product highcharts highstock * @apioption series.vector.data.length */ /** * The vector direction in degrees, where 0 is north (pointing towards south). * * @type {number} * @product highcharts highstock * @apioption series.vector.data.direction */ ''; // adds doclets above to the transpiled file return VectorSeries; }); _registerModule(_modules, 'masters/modules/vector.src.js', [], function () { }); }));
/* eslint-disable import/no-extraneous-dependencies */ require('@babel/register')({ plugins: [ '@babel/plugin-transform-modules-commonjs', ], });
var config = require('./config'), express = require('express'), morgan = require('morgan'), compress = require('compression'), bodyParser = require('body-parser'), methodOverride = require('method-override'), session = require('express-session'); module.exports = function() { var app = express(); if (process.env.NODE_ENV == 'development') { app.use(morgan('dev')); } else if (process.env.NODE_ENV == 'production') { app.use(compress()); } app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(methodOverride()); app.use(session({ saveUninitialized: true, resave: true, secret: config.sessionSecret })); app.set('views', './app/views'); app.set('view engine', 'ejs'); require('../app/routes/index.server.routes.js')(app); require('../app/routes/users.server.routes.js')(app); app.use(express.static('./public')); return app; };
(function() { // Place code in an IIFE // Test: Create an input element, and see if the placeholder is supported if ('placeholder' in document.createElement('input')) { return; } var length = document.forms.length; // Get number of forms for (var i = 0, l = length; i < l; i++ ) { // Loop through each one showPlaceholder(document.forms[i].elements); // Call showPlaceholder() } function showPlaceholder(elements) { // Declare function for (var i = 0, l = elements.length; i < l; i++) { // For each element var el = elements[i]; // Store that element if (!el.placeholder) { // If no placeholder set continue; // Go to next element } // Otherwise el.style.color = '#666666'; // Set text to gray el.value = el.placeholder; // Add placeholder text addEvent(el, 'focus', function () { // If it gains focus if (this.value === this.placeholder) { // If value=placeholder this.value = ''; // Empty text input this.style.color = '#000000'; // Make text black } }); addEvent(el, 'blur', function () { // On blur event if (this.value === '') { // If the input is empty this.value = this.placeholder; // Make value placeholder this.style.color = '#666666'; // Set text to gray } }); } // End of for loop } // End showPlaceholder() }());
/*****************************************************************************/ /* LeaveEntitlementCreate: Event Handlers */ /*****************************************************************************/ Template.LeaveEntitlementCreate.events({ 'click #LeaveEntitlementCreate': (e, tmpl) => { e.preventDefault() let leaveEntitlementName = $('#leaveEntitlementName').val(); let numberOfLeaveDaysPerAnnum = $('#numberOfLeaveDaysPerAnnum').val(); let allowLeavesInHours = $('#allowLeavesInHours').is(":checked") let applyEntitlementToEmployeesWithPaygrade = $('#applyEntitlementToEmployeesWithPaygrade').is(":checked") let numberOfLeaveDaysPerAnnumAsNumber = parseFloat(numberOfLeaveDaysPerAnnum) if(!leaveEntitlementName || leaveEntitlementName.trim().length === 0) { tmpl.inputErrorMsg.set("You need to specify the entitlement's name") return } if(!numberOfLeaveDaysPerAnnum || numberOfLeaveDaysPerAnnum.trim().length === 0) { tmpl.inputErrorMsg.set("You need to number of leave days per year for this entitlement") return } let employeePayGradesToApplyEntitlementTo = [] if(applyEntitlementToEmployeesWithPaygrade) { employeePayGradesToApplyEntitlementTo = tmpl.selectedPaygrades.get() } tmpl.inputErrorMsg.set(null) //-- let leaveEntitlementDoc = { name: leaveEntitlementName, allowLeaveRequestsInHours: allowLeavesInHours, numberOfLeaveDaysPerAnnum: numberOfLeaveDaysPerAnnum, payGradeIds: employeePayGradesToApplyEntitlementTo, businessId: Session.get('context') } let currentYear = moment().year() let currentYearAsNumber = parseInt(currentYear) Meteor.call('LeaveEntitlement/create', leaveEntitlementDoc, currentYearAsNumber, function(err, res) { Modal.hide('LeaveEntitlementCreate') if(!err) { swal('Successful', "Leave entitlement successful", 'success') } else { swal('Error', err.reason, 'error') } }) }, 'change #applyEntitlementToEmployeesWithPaygrade': function(e, tmpl) { let applyEntitlementToEmployeesWithPaygrade = $('#applyEntitlementToEmployeesWithPaygrade').is(":checked") if(applyEntitlementToEmployeesWithPaygrade) { $('#payGradesSemanticSelect').show() } else { $('#payGradesSemanticSelect').hide() } }, 'change [name="employeePayGrades"]': (e, tmpl) => { let selected = Core.returnSelection($(e.target)); tmpl.selectedPaygrades.set(selected) } }); /*****************************************************************************/ /* LeaveEntitlementCreate: Helpers */ /*****************************************************************************/ Template.LeaveEntitlementCreate.helpers({ inputErrorMsg: function() { return Template.instance().inputErrorMsg.get() }, payGrades: function() { return PayGrades.find({status: 'Active'}).fetch() }, }); /*****************************************************************************/ /* LeaveEntitlementCreate: Lifecycle Hooks */ /*****************************************************************************/ Template.LeaveEntitlementCreate.onCreated(function () { let self = this self.inputErrorMsg = new ReactiveVar() self.selectedPaygrades = new ReactiveVar() self.subscribe('paygrades', Session.get('context')); }); Template.LeaveEntitlementCreate.onRendered(function () { let self = this; $('#payGradesSemanticSelect').hide() }); Template.LeaveEntitlementCreate.onDestroyed(function () { });
'use strict'; var gulp = require('gulp'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var tap = require('gulp-tap'); var manifest = require('gulp-concat-filenames'); var mocha = require('gulp-mocha'); var concat = require('gulp-concat'); var stylus = require('gulp-stylus'); var livereload = require('gulp-livereload'); var nodemon = require('gulp-nodemon'); var git = require('gulp-git'); var del = require('del'); var runSequence = require('run-sequence'); var options = { 'buildDir': './dist/', 'javascript': { 'core': { 'buildFile': 'core.js', 'sources': [ './src/public/core/**/*.js' ] }, 'common': { 'buildFile': 'common.js', 'sources': [ './src/public/common/**/*.js' ] }, 'features': { 'buildFile': 'features.js', 'sources': [ './src/public/features/**/*.js' ] } }, 'server': { 'app': './src/server/app.js', 'sources': [ './src/server/**/*.js' ], 'tests': [ './test/unit/server/**/*.js' ] }, 'partials': { 'sources': [ './src/public/common/**/*.html', './src/public/features/**/*.html' ] }, 'pages': { 'sources': [ './src/public/pages/**/*.html', './src/server/**/*.html' // for indexes and stuff ] }, 'images': [ './src/public/common/images/**/*' ], 'markdown': { 'sources': [ './src/public/common/markdown/**/*.md', ], 'targetWiki': 'git@github.com:Telogical/TelUI.wiki.git', 'cloneOptions': { 'args': 'src/public/common/markdown', 'quiet': false } }, 'browserify': { 'debug': true }, 'manifest': { 'root': './', 'prepend': 'require("./', 'append': '");' }, 'styles': { 'buildFile': 'styles.css', 'sources': [ './src/public/core/**/*.styl', './src/public/common/**/*.styl', './src/public/features/**/*.styl' ] } }; function buildJavascript(target) { function doBrowserification(file) { return browserify(file, options.browserify) .bundle() .pipe(source(target.buildFile)) //.pipe(buffer()) //.pipe(uglify()) .pipe(gulp.dest(options.buildDir)) .pipe(livereload()); } return gulp .src(target.sources) //.pipe(uglify()) .pipe(manifest(target.buildFile, options.manifest)) .pipe(tap(doBrowserification)); } function buildCore() { return buildJavascript(options.javascript.core); } function buildCommon() { return buildJavascript(options.javascript.common); } function buildFeatures() { return buildJavascript(options.javascript.features); } function buildStyles() { gulp.src(options.styles.sources) .pipe(stylus()) .pipe(concat(options.styles.buildFile)) .pipe(gulp.dest(options.buildDir)) .pipe(livereload()) ; } function buildPartials() { gulp.src(options.partials.sources) .pipe(gulp.dest(options.buildDir + '/partials')) .pipe(livereload()) ; } function buildPages() { gulp.src(options.pages.sources) .pipe(gulp.dest(options.buildDir)) .pipe(livereload()) ; } function buildImages() { gulp.src(options.images) .pipe(gulp.dest(options.buildDir + '/images')) .pipe(livereload()) ; } function buildMarkdown() { git.clone(options.markdown.targetWiki, options.markdown.cloneOptions, function errorInclone(err) { if(err) { throw err; } gulp.src(options.markdown.sources) .pipe(gulp.dest(options.buildDir + '/markdown')); }); } function unitTestServer() { return gulp.src(options.server.tests) .pipe(mocha({ 'reporter': 'nyan' })); } function watchUnitTests() { gulp.watch([options.server.sources, options.server.tests], ['test-server']); } function watchClientSide(target, taskList) { gulp.watch(target.sources, taskList); } function watchCore() { watchClientSide(options.javascript.core, ['build-core']); } function watchCommon() { watchClientSide(options.javascript.common, ['build-common']); } function watchFeatures() { watchClientSide(options.javascript.features, ['build-features']); } function watchStyles() { watchClientSide(options.styles, ['build-styles']); } function watchPartials() { watchClientSide(options.partials, ['build-partials']); } function watchPages() { watchClientSide(options.pages, ['build-pages']); } function watchImages() { gulp.watch(options.images, ['build-images']); } function startLiveReload() { livereload.listen(); } function serveProject() { nodemon({ 'script': options.server.app, 'watch': options.server.sources }); } function cleanDist(cb) { var deletionTarget = [ options.buildDir, options.markdown.cloneOptions.args ]; del(deletionTarget, cb); } // Testing gulp.task('test-server', unitTestServer); // Building gulp.task('build-core', buildCore); gulp.task('build-common', buildCommon); gulp.task('build-features', buildFeatures); gulp.task('build-javascript', [ 'build-core', 'build-common', 'build-features' ]); gulp.task('build-styles', buildStyles); gulp.task('build-partials', buildPartials); gulp.task('build-pages', buildPages); gulp.task('build-images', buildImages); gulp.task('build-markdown', buildMarkdown); gulp.task('build', function() { runSequence( 'clean', ['build-javascript', 'build-styles', 'build-partials', 'build-pages', 'build-markdown'] ); }); // Watches gulp.task('start-livereload', startLiveReload); gulp.task('watch-server-test-unit', watchUnitTests); gulp.task('watch-core', watchCore); gulp.task('watch-common', watchCommon); gulp.task('watch-features', watchFeatures); gulp.task('watch-styles', watchStyles); gulp.task('watch-partials', watchPartials); gulp.task('watch-pages', watchPages); gulp.task('watch-images', watchImages); gulp.task('watch-client', [ 'start-livereload', 'watch-core', 'watch-common', 'watch-features', 'watch-styles', 'watch-partials', 'watch-pages', 'watch-images' ]); // Other gulp.task('clean', cleanDist); gulp.task('serve', serveProject); gulp.task('watch', ['serve', 'watch-client']);
angular.module('Speck').controller('SpecsCtrl', ['$scope', '$rootScope', '$http', '$stateParams', '$q', '$mdDialog', '$state', 'DataService',SpecsCtrl]); angular.module('Speck').controller('SendSpecCtrl', ['$scope', '$mdDialog', SendSpecCtrl]); function SpecsCtrl($scope, $rootScope, $http, $stateParams, $q, $mdDialog, $state, dS) { $scope.initSpecs = function() { console.log('SpecsCtrl Ctrl', $scope.userSpecInvites); } $scope.initMultiDropzone = function() { $scope.multidropzone = new Dropzone("div#multidropzone", { url: "/specs/post", acceptedFiles: ".docx", clickable: ".md-clicker" }); $scope.multidropzone.on("sending", function(file, xhr, formdata) { if($scope.currentUser) { formdata.append("email", $scope.currentUser) } else { formdata.append("email", $scope.guest) } }); $scope.multidropzone.on("success", function(xhr, resp) { dS.updateUserSpecs(); }); } $scope.deleteSpec = function(sid) { var urlz = '/api/specs/' + sid + '/delete' $http({ url: urlz, method: 'POST' }).success(function(data, status, headers, config) { dS.updateUserSpecs(); }).error(function(data, status, headers, config) { console.log('deleteSpec Error', sid, data); }); } $scope.makeDraft = function(sid) { var urlz = '/api/specs/' + sid + '/makedraft' $http({ url: urlz, method: 'POST' }).success(function(data, status, headers, config) { $state.go('v2add', { specId: sid }); }).error(function(data, status, headers, config) { console.log('makedraft Error', sid, data); }); } $scope.showDocxHelp = function(ev) { $mdDialog.show($mdDialog.alert().parent(angular.element(document.body)).title('How to convert .doc files to .docx format?').content('Older versions of Microsoft Word used the .doc format. From Microsoft 2007 onwards, the .docx version was introduced. Microsoft 2007 and above can read/write .doc and also .docx formats. The easiest way to convert to .docx format is to Open the file Word and Save As .docx').ariaLabel('How to convert .doc files to .docx format?').ok('Got it!').targetEvent(ev)); }; $scope.sendSpec = function(ev, sid) { $mdDialog.show({ controller: SendSpecCtrl, templateUrl: '/speck-templates/v2-dash-specs-send.html', parent: angular.element(document.body), targetEvent: ev, locals: { ddata: [] } }).then(function(ans) { if(ans.answer == 'send') { ans.ddata['uid'] = $rootScope.currentUserUid; var urlz = '/api/specs/' + sid + '/send' $http({ url: urlz, method: 'POST', data: { 'details': ans.ddata } }).success(function(data, status, headers, config) { console.log('Success', data); }).error(function(data, status, headers, config) { console.log('Error', data); }); } }, function() { console.log('You cancelled the dialog.'); }); } } function SendSpecCtrl($scope, $mdDialog) { $scope.answer = function(answer, ddata) { var ans = []; ans.answer = answer; ans.ddata = ddata; $mdDialog.hide(ans); }; $scope.cancelDialog = function() { $mdDialog.cancel(); } }
8.0-alpha2:badca410df5d67215f046e887c774ac15f7e6e102779be798c7cda3454f68833