code
stringlengths
2
1.05M
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; const u = undefined; function plural(n) { let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } global.ng.common.locales['en-ki'] = [ 'en-KI', [['a', 'p'], ['am', 'pm'], u], [['am', 'pm'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'] ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] ], u, [['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']], 1, [6, 0], ['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM y'], ['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'], ['{1}, {0}', u, '{1} \'at\' {0}', u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'AUD', '$', 'Australian Dollar', {'AUD': ['$'], 'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, 'ltr', plural, [ [ ['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], ['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u ], [['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u], [ '00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'], ['21:00', '06:00'] ] ] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); (function (factory) { if (typeof module === "object" && typeof module.exports === "object") { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === "function" && define.amd) { define(["require", "exports", "@angular/core", "../../config/config", "../ion", "../../util/util"], factory); } })(function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var config_1 = require("../../config/config"); var ion_1 = require("../ion"); var util_1 = require("../../util/util"); /** * \@name Spinner * \@description * The `ion-spinner` component provides a variety of animated SVG spinners. * Spinners enables you to give users feedback that the app is actively * processing/thinking/waiting/chillin’ out, or whatever you’d like it to indicate. * By default, the `ion-refresher` feature uses this spinner component while it's * the refresher is in the `refreshing` state. * * Ionic offers a handful of spinners out of the box, and by default, it will use * the appropriate spinner for the platform on which it’s running. * * <table class="table spinner-table"> * <tr> * <th> * <code>ios</code> * </th> * <td> * <ion-spinner name="ios"></ion-spinner> * </td> * </tr> * <tr> * <th> * <code>ios-small</code> * </th> * <td> * <ion-spinner name="ios-small"></ion-spinner> * </td> * </tr> * <tr> * <th> * <code>bubbles</code> * </th> * <td> * <ion-spinner name="bubbles"></ion-spinner> * </td> * </tr> * <tr> * <th> * <code>circles</code> * </th> * <td> * <ion-spinner name="circles"></ion-spinner> * </td> * </tr> * <tr> * <th> * <code>crescent</code> * </th> * <td> * <ion-spinner name="crescent"></ion-spinner> * </td> * </tr> * <tr> * <th> * <code>dots</code> * </th> * <td> * <ion-spinner name="dots"></ion-spinner> * </td> * </tr> * </table> * * \@usage * The following code would use the default spinner for the platform it's * running from. If it's neither iOS or Android, it'll default to use `ios`. * * ```html * <ion-spinner></ion-spinner> * ``` * * By setting the `name` property, you can specify which predefined spinner to * use, no matter what the platform is. * * ```html * <ion-spinner name="bubbles"></ion-spinner> * ``` * * ## Styling SVG with CSS * One cool thing about SVG is its ability to be styled with CSS! One thing to note * is that some of the CSS properties on an SVG element have different names. For * example, SVG uses the term `stroke` instead of `border`, and `fill` instead * of `background-color`. * * ```css * ion-spinner * { * width: 28px; * height: 28px; * stroke: #444; * fill: #222; * } * ``` */ var Spinner = (function (_super) { __extends(Spinner, _super); /** * @param {?} config * @param {?} elementRef * @param {?} renderer */ function Spinner(config, elementRef, renderer) { var _this = _super.call(this, config, elementRef, renderer, 'spinner') || this; _this._dur = null; _this._paused = false; return _this; } Object.defineProperty(Spinner.prototype, "name", { /** * \@input {string} SVG spinner name. * @return {?} */ get: function () { return this._name; }, /** * @param {?} val * @return {?} */ set: function (val) { this._name = val; this.load(); }, enumerable: true, configurable: true }); Object.defineProperty(Spinner.prototype, "duration", { /** * \@input {string} How long it takes it to do one loop. * @return {?} */ get: function () { return this._dur; }, /** * @param {?} val * @return {?} */ set: function (val) { this._dur = val; this.load(); }, enumerable: true, configurable: true }); Object.defineProperty(Spinner.prototype, "paused", { /** * \@input {boolean} If true, pause the animation. * @return {?} */ get: function () { return this._paused; }, /** * @param {?} val * @return {?} */ set: function (val) { this._paused = util_1.isTrueProperty(val); }, enumerable: true, configurable: true }); /** * @hidden * @return {?} */ Spinner.prototype.ngOnInit = function () { this._init = true; this.load(); }; /** * @hidden * @return {?} */ Spinner.prototype.load = function () { if (this._init) { this._l = []; this._c = []; var /** @type {?} */ name = this._name || this._config.get('spinner', 'ios'); var /** @type {?} */ spinner = SPINNERS[name]; if (spinner) { if (spinner.lines) { for (var /** @type {?} */ i = 0, /** @type {?} */ l = spinner.lines; i < l; i++) { this._l.push(this._loadEle(spinner, i, l)); } } else if (spinner.circles) { for (var /** @type {?} */ i = 0, /** @type {?} */ l = spinner.circles; i < l; i++) { this._c.push(this._loadEle(spinner, i, l)); } } this.setElementClass("spinner-" + name, true); this.setElementClass("spinner-" + this._mode + "-" + name, true); } } }; /** * @param {?} spinner * @param {?} index * @param {?} total * @return {?} */ Spinner.prototype._loadEle = function (spinner, index, total) { var /** @type {?} */ duration = this._dur || spinner.dur; var /** @type {?} */ data = spinner.fn(duration, index, total); data.style.animationDuration = duration + 'ms'; return data; }; return Spinner; }(ion_1.Ion)); Spinner.decorators = [ { type: core_1.Component, args: [{ selector: 'ion-spinner', template: '<svg viewBox="0 0 64 64" *ngFor="let i of _c" [ngStyle]="i.style">' + '<circle [attr.r]="i.r" transform="translate(32,32)"></circle>' + '</svg>' + '<svg viewBox="0 0 64 64" *ngFor="let i of _l" [ngStyle]="i.style">' + '<line [attr.y1]="i.y1" [attr.y2]="i.y2" transform="translate(32,32)"></line>' + '</svg>', host: { '[class.spinner-paused]': '_paused' }, changeDetection: core_1.ChangeDetectionStrategy.OnPush, encapsulation: core_1.ViewEncapsulation.None, },] }, ]; /** * @nocollapse */ Spinner.ctorParameters = function () { return [ { type: config_1.Config, }, { type: core_1.ElementRef, }, { type: core_1.Renderer, }, ]; }; Spinner.propDecorators = { 'name': [{ type: core_1.Input },], 'duration': [{ type: core_1.Input },], 'paused': [{ type: core_1.Input },], }; exports.Spinner = Spinner; function Spinner_tsickle_Closure_declarations() { /** @type {?} */ Spinner.decorators; /** * @nocollapse * @type {?} */ Spinner.ctorParameters; /** @type {?} */ Spinner.propDecorators; /** @type {?} */ Spinner.prototype._c; /** @type {?} */ Spinner.prototype._l; /** @type {?} */ Spinner.prototype._name; /** @type {?} */ Spinner.prototype._dur; /** @type {?} */ Spinner.prototype._init; /** @type {?} */ Spinner.prototype._paused; } var /** @type {?} */ SPINNERS = { ios: { dur: 1000, lines: 12, fn: function (dur, index, total) { var /** @type {?} */ transform = 'rotate(' + (30 * index + (index < 6 ? 180 : -180)) + 'deg)'; var /** @type {?} */ animationDelay = -(dur - ((dur / total) * index)) + 'ms'; return { y1: 17, y2: 29, style: { transform: transform, webkitTransform: transform, animationDelay: animationDelay, webkitAnimationDelay: animationDelay } }; } }, 'ios-small': { dur: 1000, lines: 12, fn: function (dur, index, total) { var /** @type {?} */ transform = 'rotate(' + (30 * index + (index < 6 ? 180 : -180)) + 'deg)'; var /** @type {?} */ animationDelay = -(dur - ((dur / total) * index)) + 'ms'; return { y1: 12, y2: 20, style: { transform: transform, webkitTransform: transform, animationDelay: animationDelay, webkitAnimationDelay: animationDelay } }; } }, bubbles: { dur: 1000, circles: 9, fn: function (dur, index, total) { var /** @type {?} */ animationDelay = -(dur - ((dur / total) * index)) + 'ms'; return { r: 5, style: { top: (9 * Math.sin(2 * Math.PI * index / total)) + 'px', left: (9 * Math.cos(2 * Math.PI * index / total)) + 'px', animationDelay: animationDelay, webkitAnimationDelay: animationDelay } }; } }, circles: { dur: 1000, circles: 8, fn: function (dur, index, total) { var /** @type {?} */ animationDelay = -(dur - ((dur / total) * index)) + 'ms'; return { r: 5, style: { top: (9 * Math.sin(2 * Math.PI * index / total)) + 'px', left: (9 * Math.cos(2 * Math.PI * index / total)) + 'px', animationDelay: animationDelay, webkitAnimationDelay: animationDelay } }; } }, crescent: { dur: 750, circles: 1, fn: function (dur) { return { r: 26, style: {} }; } }, dots: { dur: 750, circles: 3, fn: function (dur, index, total) { var /** @type {?} */ animationDelay = -(110 * index) + 'ms'; return { r: 6, style: { left: (9 - (9 * index)) + 'px', animationDelay: animationDelay, webkitAnimationDelay: animationDelay } }; } } }; }); //# sourceMappingURL=spinner.js.map
export const a = 1; export const b = 2; export default 42;
define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/on', 'dojo/topic', 'dijit/popup', 'dijit/TooltipDialog', './IDMappingGrid', './GridContainer' ], function ( declare, lang, on, Topic, popup, TooltipDialog, IDMappingGrid, GridContainer ) { return declare([GridContainer], { gridCtor: IDMappingGrid, containerType: 'feature_data', facetFields: [], enableFilterPanel: false, buildQuery: function () { // prevent further filtering. DO NOT DELETE }, _setQueryAttr: function (query) { // block default query handler for now. }, onSetState: function (state) { // block default behavior }, _setStateAttr: function (state) { this.inherited(arguments); if (!state) { return; } if (this.grid) { this.grid.set('state', state); } else { // console.log("No Grid Yet (IDMappingGridContainer)"); } this._set('state', state); } }); });
(function(){ module('data-method', { setup: function() { $('#qunit-fixture').append($('<a />', { href: '/echo', 'data-method': 'delete', text: 'destroy!' })); }, teardown: function() { $(document).unbind('iframe:loaded'); } }); function submit(fn, options) { $(document).bind('iframe:loaded', function(e, data) { fn(data); start(); }); $('#qunit-fixture').find('a') .trigger('click'); } asyncTest('link with "data-method" set to "delete"', 3, function() { submit(function(data) { equal(data.REQUEST_METHOD, 'DELETE'); strictEqual(data.params.authenticity_token, undefined); strictEqual(data.HTTP_X_CSRF_TOKEN, undefined); }); }); asyncTest('link with "data-method" and CSRF', 1, function() { $('#qunit-fixture') .append('<meta name="csrf-param" content="authenticity_token"/>') .append('<meta name="csrf-token" content="cf50faa3fe97702ca1ae"/>'); submit(function(data) { equal(data.params.authenticity_token, 'cf50faa3fe97702ca1ae'); }); }); asyncTest('link "target" should be carried over to generated form', 1, function() { $('a[data-method]').attr('target', 'super-special-frame'); submit(function(data) { equal(data.params._target, 'super-special-frame'); }); }); })();
console.warn("warn -",`Imports like "const rarible = require('simple-icons/icons/rarible');" have been deprecated in v6.0.0 and will no longer work from v7.0.0, use "const { siRarible } = require('simple-icons/icons');" instead`),module.exports={title:"Rarible",slug:"rarible",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Rarible</title><path d="'+this.path+'"/></svg>'},path:"M4.8 0A4.79 4.79 0 000 4.8v14.4A4.79 4.79 0 004.8 24h14.4a4.79 4.79 0 004.8-4.8V4.8A4.79 4.79 0 0019.2 0zm1.32 7.68h8.202c2.06 0 3.666.44 3.666 2.334 0 1.137-.671 1.702-1.427 1.898.904.268 1.558 1 1.558 2.16v2.131h-3.451V14.18c0-.62-.37-.87-1-.87H9.572v2.893H6.12zm3.452 2.5v.834h4.155c.452 0 .726-.06.726-.416 0-.358-.274-.418-.726-.418z",source:"https://rarible.com/",hex:"FEDA03",guidelines:void 0,license:void 0};
const fs = require('fs'); const _ = require('lodash'); const cache = require('./state/cache'); const broadcast = cache.get('broadcast'); const apiKeysFile = __dirname + '/../SECRET-api-keys.json'; // on init: const noApiKeysFile = !fs.existsSync(apiKeysFile); if(noApiKeysFile) fs.writeFileSync( apiKeysFile, JSON.stringify({}) ); const apiKeys = JSON.parse( fs.readFileSync(apiKeysFile, 'utf8') ); module.exports = { get: () => _.keys(apiKeys), // note: overwrites if exists add: (exchange, props) => { apiKeys[exchange] = props; fs.writeFileSync(apiKeysFile, JSON.stringify(apiKeys)); broadcast({ type: 'apiKeys', exchanges: _.keys(apiKeys) }); }, remove: exchange => { if(!apiKeys[exchange]) return; delete apiKeys[exchange]; fs.writeFileSync(apiKeysFile, JSON.stringify(apiKeys)); broadcast({ type: 'apiKeys', exchanges: _.keys(apiKeys) }); }, // retrieve api keys // this cannot touch the frontend for security reaons. _getApiKeyPair: key => apiKeys[key] }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var locale = { placeholder: 'Zeit auswählen' }; exports['default'] = locale; module.exports = exports['default'];
$(document).ready(function() { $('#servicio_ingreso').select2({ width: '60%', placeholder:'Seleccione...', allowClear:true }); $("#fecha_inicio").datepicker().mask("99-99-9999"); $("#fecha_fin").datepicker().mask("99-99-9999"); $("#emitir_informe").click(function() { if ($("#fecha_inicio").val() == '' || $("#fecha_fin").val() == '') { ($('#error')) ? $('#error').remove() : ''; var elem = $("<div id='error' title='Error de llenado'><center>" + "Debe de seleccionar ambas fechas para generar el reporte." + "</center></div>"); elem.insertAfter($("#pacientesIngresados")); $("#error").dialog({ close: function() { if ($("#fecha_inicio").val() == '') $("#fecha_inicio").focus(); else $("#fecha_fin").focus(); } }); } else if( $("#fecha_inicio").datepicker("getDate") > $("#fecha_fin").datepicker("getDate")){ ($('#error')) ? $('#error').remove() : ''; var elem = $("<div id='error' title='Error de llenado'><center>" + "La fecha de inicio debe de ser menor que la fecha fin." + "</center></div>"); elem.insertAfter($("#pacientesIngresados")); $("#error").dialog({ close: function() { $("#fecha_inicio").val(''); $("#fecha_fin").val(''); $("#fecha_inicio").focus(); } }); } else { $('#resultado').load(Routing.generate('buscar_ingresos_pacientes'), {'datos': $('#pacientesIngresados').serialize()}); } return false; }); $.getJSON(Routing.generate('get_servicios_hospitalarios_todos'), function(data) { $.each(data.especialidades, function(indice, aux) { $('#servicio_ingreso').append('<option value="' + aux.id + '">' + aux.nombre + '</option>'); }); }); });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * * Take a screenshot of the current viewport. To get the screenshot of the whole page * use the action command `saveScreenshot` * * @returns {String} screenshot The screenshot as a base64 encoded PNG. * * @see https://w3c.github.io/webdriver/webdriver-spec.html#dfn-take-screenshot * @type protocol * */ var screenshot = function screenshot() { return this.requestHandler.create('/session/:sessionId/screenshot'); }; exports.default = screenshot; module.exports = exports['default'];
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact Commercial Usage Licensees holding valid commercial licenses may use this file in accordance with the Commercial Software License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Sencha. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2013-09-18 17:18:59 (940c324ac822b840618a3a8b2b4b873f83a1a9b1) */ /** * @class Ext.fx.Animator * * This class is used to run keyframe based animations, which follows the CSS3 based animation structure. * Keyframe animations differ from typical from/to animations in that they offer the ability to specify values * at various points throughout the animation. * * ## Using Keyframes * * The {@link #keyframes} option is the most important part of specifying an animation when using this * class. A key frame is a point in a particular animation. We represent this as a percentage of the * total animation duration. At each key frame, we can specify the target values at that time. Note that * you *must* specify the values at 0% and 100%, the start and ending values. There is also a {@link #keyframe} * event that fires after each key frame is reached. * * ## Example * * In the example below, we modify the values of the element at each fifth throughout the animation. * * @example * Ext.create('Ext.fx.Animator', { * target: Ext.getBody().createChild({ * style: { * width: '100px', * height: '100px', * 'background-color': 'red' * } * }), * duration: 10000, // 10 seconds * keyframes: { * 0: { * opacity: 1, * backgroundColor: 'FF0000' * }, * 20: { * x: 30, * opacity: 0.5 * }, * 40: { * x: 130, * backgroundColor: '0000FF' * }, * 60: { * y: 80, * opacity: 0.3 * }, * 80: { * width: 200, * y: 200 * }, * 100: { * opacity: 1, * backgroundColor: '00FF00' * } * } * }); */ Ext.define('Ext.fx.Animator', { /* Begin Definitions */ mixins: { observable: 'Ext.util.Observable' }, requires: ['Ext.fx.Manager'], /* End Definitions */ /** * @property {Boolean} isAnimator * `true` in this class to identify an object as an instantiated Animator, or subclass thereof. */ isAnimator: true, /** * @cfg {Number} duration * Time in milliseconds for the animation to last. Defaults to 250. */ duration: 250, /** * @cfg {Number} delay * Time to delay before starting the animation. Defaults to 0. */ delay: 0, /* private used to track a delayed starting time */ delayStart: 0, /** * @cfg {Boolean} dynamic * Currently only for Component Animation: Only set a component's outer element size bypassing layouts. Set to true to do full layouts for every frame of the animation. Defaults to false. */ dynamic: false, /** * @cfg {String} easing * * This describes how the intermediate values used during a transition will be calculated. It allows for a transition to change * speed over its duration. * * - backIn * - backOut * - bounceIn * - bounceOut * - ease * - easeIn * - easeOut * - easeInOut * - elasticIn * - elasticOut * - cubic-bezier(x1, y1, x2, y2) * * Note that cubic-bezier will create a custom easing curve following the CSS3 [transition-timing-function][0] * specification. The four values specify points P1 and P2 of the curve as (x1, y1, x2, y2). All values must * be in the range [0, 1] or the definition is invalid. * * [0]: http://www.w3.org/TR/css3-transitions/#transition-timing-function_tag */ easing: 'ease', /** * Flag to determine if the animation has started * @property running * @type Boolean */ running: false, /** * Flag to determine if the animation is paused. Only set this to true if you need to * keep the Anim instance around to be unpaused later; otherwise call {@link #end}. * @property paused * @type Boolean */ paused: false, /** * @private */ damper: 1, /** * @cfg {Number} iterations * Number of times to execute the animation. Defaults to 1. */ iterations: 1, /** * Current iteration the animation is running. * @property currentIteration * @type Number */ currentIteration: 0, /** * Current keyframe step of the animation. * @property keyframeStep * @type Number */ keyframeStep: 0, /** * @private */ animKeyFramesRE: /^(from|to|\d+%?)$/, /** * @cfg {Ext.fx.target.Target} target * The Ext.fx.target to apply the animation to. If not specified during initialization, this can be passed to the applyAnimator * method to apply the same animation to many targets. */ /** * @cfg {Object} keyframes * Animation keyframes follow the CSS3 Animation configuration pattern. 'from' is always considered '0%' and 'to' * is considered '100%'.<b>Every keyframe declaration must have a keyframe rule for 0% and 100%, possibly defined using * "from" or "to"</b>. A keyframe declaration without these keyframe selectors is invalid and will not be available for * animation. The keyframe declaration for a keyframe rule consists of properties and values. Properties that are unable to * be animated are ignored in these rules, with the exception of 'easing' which can be changed at each keyframe. For example: <pre><code> keyframes : { '0%': { left: 100 }, '40%': { left: 150 }, '60%': { left: 75 }, '100%': { left: 100 } } </code></pre> */ constructor: function(config) { var me = this; config = Ext.apply(me, config || {}); me.config = config; me.id = Ext.id(null, 'ext-animator-'); me.addEvents( /** * @event beforeanimate * Fires before the animation starts. A handler can return false to cancel the animation. * @param {Ext.fx.Animator} this */ 'beforeanimate', /** * @event keyframe * Fires at each keyframe. * @param {Ext.fx.Animator} this * @param {Number} keyframe step number */ 'keyframe', /** * @event afteranimate * Fires when the animation is complete. * @param {Ext.fx.Animator} this * @param {Date} startTime */ 'afteranimate' ); me.mixins.observable.constructor.call(me, config); me.timeline = []; me.createTimeline(me.keyframes); if (me.target) { me.applyAnimator(me.target); Ext.fx.Manager.addAnim(me); } }, /** * @private */ sorter: function (a, b) { return a.pct - b.pct; }, /** * @private * Takes the given keyframe configuration object and converts it into an ordered array with the passed attributes per keyframe * or applying the 'to' configuration to all keyframes. Also calculates the proper animation duration per keyframe. */ createTimeline: function(keyframes) { var me = this, attrs = [], to = me.to || {}, duration = me.duration, prevMs, ms, i, ln, pct, attr; for (pct in keyframes) { if (keyframes.hasOwnProperty(pct) && me.animKeyFramesRE.test(pct)) { attr = {attrs: Ext.apply(keyframes[pct], to)}; // CSS3 spec allow for from/to to be specified. if (pct == "from") { pct = 0; } else if (pct == "to") { pct = 100; } // convert % values into integers attr.pct = parseInt(pct, 10); attrs.push(attr); } } // Sort by pct property Ext.Array.sort(attrs, me.sorter); // Only an end //if (attrs[0].pct) { // attrs.unshift({pct: 0, attrs: element.attrs}); //} ln = attrs.length; for (i = 0; i < ln; i++) { prevMs = (attrs[i - 1]) ? duration * (attrs[i - 1].pct / 100) : 0; ms = duration * (attrs[i].pct / 100); me.timeline.push({ duration: ms - prevMs, attrs: attrs[i].attrs }); } }, /** * Applies animation to the Ext.fx.target * @private * @param target * @type String/Object */ applyAnimator: function(target) { var me = this, anims = [], timeline = me.timeline, ln = timeline.length, anim, easing, damper, attrs, i; if (me.fireEvent('beforeanimate', me) !== false) { for (i = 0; i < ln; i++) { anim = timeline[i]; attrs = anim.attrs; easing = attrs.easing || me.easing; damper = attrs.damper || me.damper; delete attrs.easing; delete attrs.damper; anim = new Ext.fx.Anim({ target: target, easing: easing, damper: damper, duration: anim.duration, paused: true, to: attrs }); anims.push(anim); } me.animations = anims; me.target = anim.target; for (i = 0; i < ln - 1; i++) { anim = anims[i]; anim.nextAnim = anims[i + 1]; anim.on('afteranimate', function() { this.nextAnim.paused = false; }); anim.on('afteranimate', function() { this.fireEvent('keyframe', this, ++this.keyframeStep); }, me); } anims[ln - 1].on('afteranimate', function() { this.lastFrame(); }, me); } }, /** * @private * Fires beforeanimate and sets the running flag. */ start: function(startTime) { var me = this, delay = me.delay, delayStart = me.delayStart, delayDelta; if (delay) { if (!delayStart) { me.delayStart = startTime; return; } else { delayDelta = startTime - delayStart; if (delayDelta < delay) { return; } else { // Compensate for frame delay; startTime = new Date(delayStart.getTime() + delay); } } } if (me.fireEvent('beforeanimate', me) !== false) { me.startTime = startTime; me.running = true; me.animations[me.keyframeStep].paused = false; } }, /** * @private * Perform lastFrame cleanup and handle iterations * @returns a hash of the new attributes. */ lastFrame: function() { var me = this, iter = me.iterations, iterCount = me.currentIteration; iterCount++; if (iterCount < iter) { me.startTime = new Date(); me.currentIteration = iterCount; me.keyframeStep = 0; me.applyAnimator(me.target); me.animations[me.keyframeStep].paused = false; } else { me.currentIteration = 0; me.end(); } }, /** * Fire afteranimate event and end the animation. Usually called automatically when the * animation reaches its final frame, but can also be called manually to pre-emptively * stop and destroy the running animation. */ end: function() { var me = this; me.fireEvent('afteranimate', me, me.startTime, new Date() - me.startTime); }, isReady: function() { return this.paused === false && this.running === false && this.iterations > 0; }, isRunning: function() { // Explicitly return false, we don't want to be run continuously by the manager return false; } });
function substr(str, start, len) { // discuss at: http://phpjs.org/functions/substr/ // version: 909.322 // original by: Martijn Wieringa // bugfixed by: T.Wild // improved by: Onno Marsman // improved by: Brett Zamir (http://brett-zamir.me) // revised by: Theriault // note: Handles rare Unicode characters if 'unicode.semantics' ini (PHP6) is set to 'on' // example 1: substr('abcdef', 0, -1); // returns 1: 'abcde' // example 2: substr(2, 0, -6); // returns 2: false // example 3: ini_set('unicode.semantics', 'on'); // example 3: substr('a\uD801\uDC00', 0, -1); // returns 3: 'a' // example 4: ini_set('unicode.semantics', 'on'); // example 4: substr('a\uD801\uDC00', 0, 2); // returns 4: 'a\uD801\uDC00' // example 5: ini_set('unicode.semantics', 'on'); // example 5: substr('a\uD801\uDC00', -1, 1); // returns 5: '\uD801\uDC00' // example 6: ini_set('unicode.semantics', 'on'); // example 6: substr('a\uD801\uDC00z\uD801\uDC00', -3, 2); // returns 6: '\uD801\uDC00z' // example 7: ini_set('unicode.semantics', 'on'); // example 7: substr('a\uD801\uDC00z\uD801\uDC00', -3, -1) // returns 7: '\uD801\uDC00z' var i = 0, allBMP = true, es = 0, el = 0, se = 0, ret = ''; str += ''; var end = str.length; // BEGIN REDUNDANT this.php_js = this.php_js || {}; this.php_js.ini = this.php_js.ini || {}; // END REDUNDANT switch ((this.php_js.ini['unicode.semantics'] && this.php_js.ini['unicode.semantics'].local_value.toLowerCase())) { case 'on': // Full-blown Unicode including non-Basic-Multilingual-Plane characters // strlen() for (i = 0; i < str.length; i++) { if (/[\uD800-\uDBFF]/.test(str.charAt(i)) && /[\uDC00-\uDFFF]/.test(str.charAt(i + 1))) { allBMP = false; break; } } if (!allBMP) { if (start < 0) { for (i = end - 1, es = (start += end); i >= es; i--) { if (/[\uDC00-\uDFFF]/.test(str.charAt(i)) && /[\uD800-\uDBFF]/.test(str.charAt(i - 1))) { start--; es--; } } } else { var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; while ((surrogatePairs.exec(str)) != null) { var li = surrogatePairs.lastIndex; if (li - 2 < start) { start++; } else { break; } } } if (start >= end || start < 0) { return false; } if (len < 0) { for (i = end - 1, el = (end += len); i >= el; i--) { if (/[\uDC00-\uDFFF]/.test(str.charAt(i)) && /[\uD800-\uDBFF]/.test(str.charAt(i - 1))) { end--; el--; } } if (start > end) { return false; } return str.slice(start, end); } else { se = start + len; for (i = start; i < se; i++) { ret += str.charAt(i); if (/[\uD800-\uDBFF]/.test(str.charAt(i)) && /[\uDC00-\uDFFF]/.test(str.charAt(i + 1))) { se++; // Go one further, since one of the "characters" is part of a surrogate pair } } return ret; } break; } // Fall-through case 'off': // assumes there are no non-BMP characters; // if there may be such characters, then it is best to turn it on (critical in true XHTML/XML) default: if (start < 0) { start += end; } end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start); // PHP returns false if start does not fall within the string. // PHP returns false if the calculated end comes before the calculated start. // PHP returns an empty string if start and end are the same. // Otherwise, PHP returns the portion of the string from start to end. return start >= str.length || start < 0 || start > end ? !1 : str.slice(start, end); } return undefined; // Please Netbeans }
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 __()); }; (function (factory) { if (typeof module === 'object' && typeof module.exports === 'object') { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === 'function' && define.amd) { define(["require", "exports", '../animations/animation', '../util/util', './page-transition'], factory); } })(function (require, exports) { "use strict"; var animation_1 = require('../animations/animation'); var util_1 = require('../util/util'); var page_transition_1 = require('./page-transition'); var DURATION = 500; var EASING = 'cubic-bezier(0.36,0.66,0.04,1)'; var OPACITY = 'opacity'; var TRANSFORM = 'transform'; var TRANSLATEX = 'translateX'; var OFF_RIGHT = '99.5%'; var OFF_LEFT = '-33%'; var CENTER = '0%'; var OFF_OPACITY = 0.8; var SHOW_BACK_BTN_CSS = 'show-back-button'; var IOSTransition = (function (_super) { __extends(IOSTransition, _super); function IOSTransition() { _super.apply(this, arguments); } IOSTransition.prototype.init = function () { _super.prototype.init.call(this); var plt = this.plt; var enteringView = this.enteringView; var leavingView = this.leavingView; var opts = this.opts; this.duration(util_1.isPresent(opts.duration) ? opts.duration : DURATION); this.easing(util_1.isPresent(opts.easing) ? opts.easing : EASING); var backDirection = (opts.direction === 'back'); var enteringHasNavbar = (enteringView && enteringView.hasNavbar()); var leavingHasNavbar = (leavingView && leavingView.hasNavbar()); if (enteringView) { // get the native element for the entering page var enteringPageEle = enteringView.pageRef().nativeElement; // entering content var enteringContent = new animation_1.Animation(plt, enteringView.contentRef()); enteringContent.element(enteringPageEle.querySelectorAll('ion-header > *:not(ion-navbar),ion-footer > *')); this.add(enteringContent); if (backDirection) { // entering content, back direction enteringContent .fromTo(TRANSLATEX, OFF_LEFT, CENTER, true) .fromTo(OPACITY, OFF_OPACITY, 1, true); } else { // entering content, forward direction enteringContent .beforeClearStyles([OPACITY]) .fromTo(TRANSLATEX, OFF_RIGHT, CENTER, true); } if (enteringHasNavbar) { // entering page has a navbar var enteringNavbarEle = enteringPageEle.querySelector('ion-navbar'); var enteringNavBar = new animation_1.Animation(plt, enteringNavbarEle); this.add(enteringNavBar); var enteringTitle = new animation_1.Animation(plt, enteringNavbarEle.querySelector('ion-title')); var enteringNavbarItems = new animation_1.Animation(plt, enteringNavbarEle.querySelectorAll('ion-buttons,[menuToggle]')); var enteringNavbarBg = new animation_1.Animation(plt, enteringNavbarEle.querySelector('.toolbar-background')); var enteringBackButton = new animation_1.Animation(plt, enteringNavbarEle.querySelector('.back-button')); enteringNavBar .add(enteringTitle) .add(enteringNavbarItems) .add(enteringNavbarBg) .add(enteringBackButton); enteringTitle.fromTo(OPACITY, 0.01, 1, true); enteringNavbarItems.fromTo(OPACITY, 0.01, 1, true); // set properties depending on direction if (backDirection) { // entering navbar, back direction enteringTitle.fromTo(TRANSLATEX, OFF_LEFT, CENTER, true); if (enteringView.enableBack()) { // back direction, entering page has a back button enteringBackButton .beforeAddClass(SHOW_BACK_BTN_CSS) .fromTo(OPACITY, 0.01, 1, true); } } else { // entering navbar, forward direction enteringTitle.fromTo(TRANSLATEX, OFF_RIGHT, CENTER, true); enteringNavbarBg .beforeClearStyles([OPACITY]) .fromTo(TRANSLATEX, OFF_RIGHT, CENTER, true); if (enteringView.enableBack()) { // forward direction, entering page has a back button enteringBackButton .beforeAddClass(SHOW_BACK_BTN_CSS) .fromTo(OPACITY, 0.01, 1, true); var enteringBackBtnText = new animation_1.Animation(plt, enteringNavbarEle.querySelector('.back-button-text')); enteringBackBtnText.fromTo(TRANSLATEX, '100px', '0px'); enteringNavBar.add(enteringBackBtnText); } else { enteringBackButton.beforeRemoveClass(SHOW_BACK_BTN_CSS); } } } } // setup leaving view if (leavingView && leavingView.pageRef()) { // leaving content var leavingPageEle = leavingView.pageRef().nativeElement; var leavingContent = new animation_1.Animation(plt, leavingView.contentRef()); leavingContent.element(leavingPageEle.querySelectorAll('ion-header > *:not(ion-navbar),ion-footer > *')); this.add(leavingContent); if (backDirection) { // leaving content, back direction leavingContent .beforeClearStyles([OPACITY]) .fromTo(TRANSLATEX, CENTER, '100%'); } else { // leaving content, forward direction leavingContent .fromTo(TRANSLATEX, CENTER, OFF_LEFT) .fromTo(OPACITY, 1, OFF_OPACITY) .afterClearStyles([TRANSFORM, OPACITY]); } if (leavingHasNavbar) { // leaving page has a navbar var leavingNavbarEle = leavingPageEle.querySelector('ion-navbar'); var leavingNavBar = new animation_1.Animation(plt, leavingNavbarEle); var leavingTitle = new animation_1.Animation(plt, leavingNavbarEle.querySelector('ion-title')); var leavingNavbarItems = new animation_1.Animation(plt, leavingNavbarEle.querySelectorAll('ion-buttons,[menuToggle]')); var leavingNavbarBg = new animation_1.Animation(plt, leavingNavbarEle.querySelector('.toolbar-background')); var leavingBackButton = new animation_1.Animation(plt, leavingNavbarEle.querySelector('.back-button')); leavingNavBar .add(leavingTitle) .add(leavingNavbarItems) .add(leavingBackButton) .add(leavingNavbarBg); this.add(leavingNavBar); // fade out leaving navbar items leavingBackButton.fromTo(OPACITY, 0.99, 0); leavingTitle.fromTo(OPACITY, 0.99, 0); leavingNavbarItems.fromTo(OPACITY, 0.99, 0); if (backDirection) { // leaving navbar, back direction leavingTitle.fromTo(TRANSLATEX, CENTER, '100%'); // leaving navbar, back direction, and there's no entering navbar // should just slide out, no fading out leavingNavbarBg .beforeClearStyles([OPACITY]) .fromTo(TRANSLATEX, CENTER, '100%'); var leavingBackBtnText = new animation_1.Animation(plt, leavingNavbarEle.querySelector('.back-button-text')); leavingBackBtnText.fromTo(TRANSLATEX, CENTER, (300) + 'px'); leavingNavBar.add(leavingBackBtnText); } else { // leaving navbar, forward direction leavingTitle .fromTo(TRANSLATEX, CENTER, OFF_LEFT) .afterClearStyles([TRANSFORM]); leavingBackButton.afterClearStyles([OPACITY]); leavingTitle.afterClearStyles([OPACITY]); leavingNavbarItems.afterClearStyles([OPACITY]); } } } }; return IOSTransition; }(page_transition_1.PageTransition)); exports.IOSTransition = IOSTransition; }); //# sourceMappingURL=transition-ios.js.map
/* Copyright (c) 2006-2015 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the 2-clause BSD license. * See license.txt in the OpenLayers distribution or repository for the * full text of the license. */ /** * @requires OpenLayers/Format/XML/VersionedOGC.js */ /** * Class: OpenLayers.Format.OWSCommon * Read OWSCommon. Create a new instance with the <OpenLayers.Format.OWSCommon> * constructor. * * Inherits from: * - <OpenLayers.Format.XML.VersionedOGC> */ OpenLayers.Format.OWSCommon = OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC, { /** * APIProperty: defaultVersion * {String} Version number to assume if none found. Default is "1.0.0". */ defaultVersion: "1.0.0", /** * Constructor: OpenLayers.Format.OWSCommon * Create a new parser for OWSCommon. * * Parameters: * options - {Object} An optional object whose properties will be set on * this instance. */ /** * Method: getVersion * Returns the version to use. Subclasses can override this function * if a different version detection is needed. * * Parameters: * root - {DOMElement} * options - {Object} Optional configuration object. * * Returns: * {String} The version to use. */ getVersion: function(root, options) { var version = this.version; if(!version) { // remember version does not correspond to the OWS version // it corresponds to the WMS/WFS/WCS etc. request version var uri = root.getAttribute("xmlns:ows"); // the above will fail if the namespace prefix is different than // ows and if the namespace is declared on a different element if (uri && uri.substring(uri.lastIndexOf("/")+1) === "1.1") { version ="1.1.0"; } if(!version) { version = this.defaultVersion; } } return version; }, /** * APIMethod: read * Read an OWSCommon document and return an object. * * Parameters: * data - {String | DOMElement} Data to read. * options - {Object} Options for the reader. * * Returns: * {Object} An object representing the structure of the document. */ CLASS_NAME: "OpenLayers.Format.OWSCommon" });
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; var util = require('util'); var msRest = require('ms-rest'); var msRestAzure = require('ms-rest-azure'); var WebResource = msRest.WebResource; /** * @class * LRORetrys * __NOTE__: An instance of this class is automatically created for an * instance of the AutoRestLongRunningOperationTestService. * Initializes a new instance of the LRORetrys class. * @constructor * * @param {AutoRestLongRunningOperationTestService} client Reference to the service client. */ function LRORetrys(client) { this.client = client; } /** * * Long running put request, service returns a 500, then a 201 to the initial * request, with an entity that contains ProvisioningState=’Creating’. Polls * return this value until the last poll returns a ‘200’ with * ProvisioningState=’Succeeded’ * * @param {object} [options] Optional Parameters. * * @param {object} [options.product] Product to put * * @param {string} [options.product.provisioningState] * * @param {object} [options.product.tags] * * @param {string} [options.product.location] Resource Location * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object. * See {@link Product} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ LRORetrys.prototype.put201CreatingSucceeded200 = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Send request this.beginPut201CreatingSucceeded200(options, function (err, parsedResult, httpRequest, response){ if (err) return callback(err); var initialResult = new msRest.HttpOperationResponse(); initialResult.request = httpRequest; initialResult.response = response; initialResult.body = response.body; client.getLongRunningOperationResult(initialResult, options, function (err, pollingResult) { if (err) return callback(err); // Create Result var result = null; httpRequest = pollingResult.request; response = pollingResult.response; var responseBody = pollingResult.body; if (responseBody === '') responseBody = null; // Deserialize Response var parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { var resultMapper = new client.models['Product']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } return callback(null, result, httpRequest, response); }); }); }; /** * * Long running put request, service returns a 500, then a 200 to the initial * request, with an entity that contains ProvisioningState=’Creating’. Poll the * endpoint indicated in the Azure-AsyncOperation header for operation status * * @param {object} [options] Optional Parameters. * * @param {object} [options.product] Product to put * * @param {string} [options.product.provisioningState] * * @param {object} [options.product.tags] * * @param {string} [options.product.location] Resource Location * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object. * See {@link Product} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ LRORetrys.prototype.putAsyncRelativeRetrySucceeded = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Send request this.beginPutAsyncRelativeRetrySucceeded(options, function (err, parsedResult, httpRequest, response){ if (err) return callback(err); var initialResult = new msRest.HttpOperationResponse(); initialResult.request = httpRequest; initialResult.response = response; initialResult.body = response.body; client.getLongRunningOperationResult(initialResult, options, function (err, pollingResult) { if (err) return callback(err); // Create Result var result = null; httpRequest = pollingResult.request; response = pollingResult.response; var responseBody = pollingResult.body; if (responseBody === '') responseBody = null; // Deserialize Response var parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { var resultMapper = new client.models['Product']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } return callback(null, result, httpRequest, response); }); }); }; /** * * Long running delete request, service returns a 500, then a 202 to the * initial request, with an entity that contains ProvisioningState=’Accepted’. * Polls return this value until the last poll returns a ‘200’ with * ProvisioningState=’Succeeded’ * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object. * See {@link Product} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ LRORetrys.prototype.deleteProvisioning202Accepted200Succeeded = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Send request this.beginDeleteProvisioning202Accepted200Succeeded(options, function (err, parsedResult, httpRequest, response){ if (err) return callback(err); var initialResult = new msRest.HttpOperationResponse(); initialResult.request = httpRequest; initialResult.response = response; initialResult.body = response.body; client.getLongRunningOperationResult(initialResult, options, function (err, pollingResult) { if (err) return callback(err); // Create Result var result = null; httpRequest = pollingResult.request; response = pollingResult.response; var responseBody = pollingResult.body; if (responseBody === '') responseBody = null; // Deserialize Response var parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { var resultMapper = new client.models['Product']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } return callback(null, result, httpRequest, response); }); }); }; /** * * Long running delete request, service returns a 500, then a 202 to the * initial request. Polls return this value until the last poll returns a ‘200’ * with ProvisioningState=’Succeeded’ * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ LRORetrys.prototype.delete202Retry200 = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Send request this.beginDelete202Retry200(options, function (err, parsedResult, httpRequest, response){ if (err) return callback(err); var initialResult = new msRest.HttpOperationResponse(); initialResult.request = httpRequest; initialResult.response = response; initialResult.body = response.body; client.getLongRunningOperationResult(initialResult, options, function (err, pollingResult) { if (err) return callback(err); // Create Result var result = null; httpRequest = pollingResult.request; response = pollingResult.response; var responseBody = pollingResult.body; if (responseBody === '') responseBody = null; // Deserialize Response return callback(null, result, httpRequest, response); }); }); }; /** * * Long running delete request, service returns a 500, then a 202 to the * initial request. Poll the endpoint indicated in the Azure-AsyncOperation * header for operation status * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ LRORetrys.prototype.deleteAsyncRelativeRetrySucceeded = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Send request this.beginDeleteAsyncRelativeRetrySucceeded(options, function (err, parsedResult, httpRequest, response){ if (err) return callback(err); var initialResult = new msRest.HttpOperationResponse(); initialResult.request = httpRequest; initialResult.response = response; initialResult.body = response.body; client.getLongRunningOperationResult(initialResult, options, function (err, pollingResult) { if (err) return callback(err); // Create Result var result = null; httpRequest = pollingResult.request; response = pollingResult.response; var responseBody = pollingResult.body; if (responseBody === '') responseBody = null; // Deserialize Response return callback(null, result, httpRequest, response); }); }); }; /** * * Long running post request, service returns a 500, then a 202 to the initial * request, with 'Location' and 'Retry-After' headers, Polls return a 200 with * a response body after success * * @param {object} [options] Optional Parameters. * * @param {object} [options.product] Product to put * * @param {string} [options.product.provisioningState] * * @param {object} [options.product.tags] * * @param {string} [options.product.location] Resource Location * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ LRORetrys.prototype.post202Retry200 = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Send request this.beginPost202Retry200(options, function (err, parsedResult, httpRequest, response){ if (err) return callback(err); var initialResult = new msRest.HttpOperationResponse(); initialResult.request = httpRequest; initialResult.response = response; initialResult.body = response.body; client.getLongRunningOperationResult(initialResult, options, function (err, pollingResult) { if (err) return callback(err); // Create Result var result = null; httpRequest = pollingResult.request; response = pollingResult.response; var responseBody = pollingResult.body; if (responseBody === '') responseBody = null; // Deserialize Response return callback(null, result, httpRequest, response); }); }); }; /** * * Long running post request, service returns a 500, then a 202 to the initial * request, with an entity that contains ProvisioningState=’Creating’. Poll the * endpoint indicated in the Azure-AsyncOperation header for operation status * * @param {object} [options] Optional Parameters. * * @param {object} [options.product] Product to put * * @param {string} [options.product.provisioningState] * * @param {object} [options.product.tags] * * @param {string} [options.product.location] Resource Location * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ LRORetrys.prototype.postAsyncRelativeRetrySucceeded = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Send request this.beginPostAsyncRelativeRetrySucceeded(options, function (err, parsedResult, httpRequest, response){ if (err) return callback(err); var initialResult = new msRest.HttpOperationResponse(); initialResult.request = httpRequest; initialResult.response = response; initialResult.body = response.body; client.getLongRunningOperationResult(initialResult, options, function (err, pollingResult) { if (err) return callback(err); // Create Result var result = null; httpRequest = pollingResult.request; response = pollingResult.response; var responseBody = pollingResult.body; if (responseBody === '') responseBody = null; // Deserialize Response return callback(null, result, httpRequest, response); }); }); }; /** * Long running put request, service returns a 500, then a 201 to the initial * request, with an entity that contains ProvisioningState=’Creating’. Polls * return this value until the last poll returns a ‘200’ with * ProvisioningState=’Succeeded’ * * @param {object} [options] Optional Parameters. * * @param {object} [options.product] Product to put * * @param {string} [options.product.provisioningState] * * @param {object} [options.product.tags] * * @param {string} [options.product.location] Resource Location * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object. * See {@link Product} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ LRORetrys.prototype.beginPut201CreatingSucceeded200 = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } var product = (options && options.product !== undefined) ? options.product : undefined; // Validate try { if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL var baseUrl = this.client.baseUri; var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'lro/retryerror/put/201/creating/succeeded/200'; var queryParameters = []; if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects var httpRequest = new WebResource(); httpRequest.method = 'PUT'; httpRequest.headers = {}; httpRequest.url = requestUrl; // Set Headers if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(var headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; // Serialize Request var requestContent = null; var requestModel = null; try { if (product !== null && product !== undefined) { var requestModelMapper = new client.models['Product']().mapper(); requestModel = client.serialize(requestModelMapper, product, 'product'); requestContent = JSON.stringify(requestModel); } } catch (error) { var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' + 'payload - "%s"', error.message, util.inspect(product, {depth: null}))); return callback(serializationError); } httpRequest.body = requestContent; // Send Request return client.pipeline(httpRequest, function (err, response, responseBody) { if (err) { return callback(err); } var statusCode = response.statusCode; if (statusCode !== 200 && statusCode !== 201) { var error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; var parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { var resultMapper = new client.models['CloudError']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + '- "%s" for the default response.', defaultError.message, responseBody); return callback(error); } return callback(error); } // Create Result var result = null; if (responseBody === '') responseBody = null; // Deserialize Response if (statusCode === 200) { var parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { var resultMapper = new client.models['Product']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } } // Deserialize Response if (statusCode === 201) { var parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { var resultMapper = new client.models['Product']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { var deserializationError1 = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); deserializationError1.request = msRest.stripRequest(httpRequest); deserializationError1.response = msRest.stripResponse(response); return callback(deserializationError1); } } return callback(null, result, httpRequest, response); }); }; /** * Long running put request, service returns a 500, then a 200 to the initial * request, with an entity that contains ProvisioningState=’Creating’. Poll the * endpoint indicated in the Azure-AsyncOperation header for operation status * * @param {object} [options] Optional Parameters. * * @param {object} [options.product] Product to put * * @param {string} [options.product.provisioningState] * * @param {object} [options.product.tags] * * @param {string} [options.product.location] Resource Location * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object. * See {@link Product} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ LRORetrys.prototype.beginPutAsyncRelativeRetrySucceeded = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } var product = (options && options.product !== undefined) ? options.product : undefined; // Validate try { if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL var baseUrl = this.client.baseUri; var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'lro/retryerror/putasync/retry/succeeded'; var queryParameters = []; if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects var httpRequest = new WebResource(); httpRequest.method = 'PUT'; httpRequest.headers = {}; httpRequest.url = requestUrl; // Set Headers if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(var headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; // Serialize Request var requestContent = null; var requestModel = null; try { if (product !== null && product !== undefined) { var requestModelMapper = new client.models['Product']().mapper(); requestModel = client.serialize(requestModelMapper, product, 'product'); requestContent = JSON.stringify(requestModel); } } catch (error) { var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' + 'payload - "%s"', error.message, util.inspect(product, {depth: null}))); return callback(serializationError); } httpRequest.body = requestContent; // Send Request return client.pipeline(httpRequest, function (err, response, responseBody) { if (err) { return callback(err); } var statusCode = response.statusCode; if (statusCode !== 200) { var error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; var parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { var resultMapper = new client.models['CloudError']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + '- "%s" for the default response.', defaultError.message, responseBody); return callback(error); } return callback(error); } // Create Result var result = null; if (responseBody === '') responseBody = null; // Deserialize Response if (statusCode === 200) { var parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { var resultMapper = new client.models['Product']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } } return callback(null, result, httpRequest, response); }); }; /** * Long running delete request, service returns a 500, then a 202 to the * initial request, with an entity that contains ProvisioningState=’Accepted’. * Polls return this value until the last poll returns a ‘200’ with * ProvisioningState=’Succeeded’ * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object. * See {@link Product} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ LRORetrys.prototype.beginDeleteProvisioning202Accepted200Succeeded = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Validate try { if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL var baseUrl = this.client.baseUri; var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'lro/retryerror/delete/provisioning/202/accepted/200/succeeded'; var queryParameters = []; if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects var httpRequest = new WebResource(); httpRequest.method = 'DELETE'; httpRequest.headers = {}; httpRequest.url = requestUrl; // Set Headers if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(var headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; httpRequest.body = null; // Send Request return client.pipeline(httpRequest, function (err, response, responseBody) { if (err) { return callback(err); } var statusCode = response.statusCode; if (statusCode !== 200 && statusCode !== 202) { var error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; var parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { var resultMapper = new client.models['CloudError']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + '- "%s" for the default response.', defaultError.message, responseBody); return callback(error); } return callback(error); } // Create Result var result = null; if (responseBody === '') responseBody = null; // Deserialize Response if (statusCode === 200) { var parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { var resultMapper = new client.models['Product']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } } // Deserialize Response if (statusCode === 202) { var parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { var resultMapper = new client.models['Product']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { var deserializationError1 = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); deserializationError1.request = msRest.stripRequest(httpRequest); deserializationError1.response = msRest.stripResponse(response); return callback(deserializationError1); } } return callback(null, result, httpRequest, response); }); }; /** * Long running delete request, service returns a 500, then a 202 to the * initial request. Polls return this value until the last poll returns a ‘200’ * with ProvisioningState=’Succeeded’ * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ LRORetrys.prototype.beginDelete202Retry200 = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Validate try { if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL var baseUrl = this.client.baseUri; var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'lro/retryerror/delete/202/retry/200'; var queryParameters = []; if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects var httpRequest = new WebResource(); httpRequest.method = 'DELETE'; httpRequest.headers = {}; httpRequest.url = requestUrl; // Set Headers if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(var headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; httpRequest.body = null; // Send Request return client.pipeline(httpRequest, function (err, response, responseBody) { if (err) { return callback(err); } var statusCode = response.statusCode; if (statusCode !== 202) { var error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; var parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { var resultMapper = new client.models['CloudError']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + '- "%s" for the default response.', defaultError.message, responseBody); return callback(error); } return callback(error); } // Create Result var result = null; if (responseBody === '') responseBody = null; return callback(null, result, httpRequest, response); }); }; /** * Long running delete request, service returns a 500, then a 202 to the * initial request. Poll the endpoint indicated in the Azure-AsyncOperation * header for operation status * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ LRORetrys.prototype.beginDeleteAsyncRelativeRetrySucceeded = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Validate try { if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL var baseUrl = this.client.baseUri; var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'lro/retryerror/deleteasync/retry/succeeded'; var queryParameters = []; if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects var httpRequest = new WebResource(); httpRequest.method = 'DELETE'; httpRequest.headers = {}; httpRequest.url = requestUrl; // Set Headers if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(var headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; httpRequest.body = null; // Send Request return client.pipeline(httpRequest, function (err, response, responseBody) { if (err) { return callback(err); } var statusCode = response.statusCode; if (statusCode !== 202) { var error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; var parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { var resultMapper = new client.models['CloudError']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + '- "%s" for the default response.', defaultError.message, responseBody); return callback(error); } return callback(error); } // Create Result var result = null; if (responseBody === '') responseBody = null; return callback(null, result, httpRequest, response); }); }; /** * Long running post request, service returns a 500, then a 202 to the initial * request, with 'Location' and 'Retry-After' headers, Polls return a 200 with * a response body after success * * @param {object} [options] Optional Parameters. * * @param {object} [options.product] Product to put * * @param {string} [options.product.provisioningState] * * @param {object} [options.product.tags] * * @param {string} [options.product.location] Resource Location * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ LRORetrys.prototype.beginPost202Retry200 = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } var product = (options && options.product !== undefined) ? options.product : undefined; // Validate try { if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL var baseUrl = this.client.baseUri; var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'lro/retryerror/post/202/retry/200'; var queryParameters = []; if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects var httpRequest = new WebResource(); httpRequest.method = 'POST'; httpRequest.headers = {}; httpRequest.url = requestUrl; // Set Headers if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(var headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; // Serialize Request var requestContent = null; var requestModel = null; try { if (product !== null && product !== undefined) { var requestModelMapper = new client.models['Product']().mapper(); requestModel = client.serialize(requestModelMapper, product, 'product'); requestContent = JSON.stringify(requestModel); } } catch (error) { var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' + 'payload - "%s"', error.message, util.inspect(product, {depth: null}))); return callback(serializationError); } httpRequest.body = requestContent; // Send Request return client.pipeline(httpRequest, function (err, response, responseBody) { if (err) { return callback(err); } var statusCode = response.statusCode; if (statusCode !== 202) { var error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; var parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { var resultMapper = new client.models['CloudError']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + '- "%s" for the default response.', defaultError.message, responseBody); return callback(error); } return callback(error); } // Create Result var result = null; if (responseBody === '') responseBody = null; return callback(null, result, httpRequest, response); }); }; /** * Long running post request, service returns a 500, then a 202 to the initial * request, with an entity that contains ProvisioningState=’Creating’. Poll the * endpoint indicated in the Azure-AsyncOperation header for operation status * * @param {object} [options] Optional Parameters. * * @param {object} [options.product] Product to put * * @param {string} [options.product.provisioningState] * * @param {object} [options.product.tags] * * @param {string} [options.product.location] Resource Location * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ LRORetrys.prototype.beginPostAsyncRelativeRetrySucceeded = function (options, callback) { var client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } var product = (options && options.product !== undefined) ? options.product : undefined; // Validate try { if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL var baseUrl = this.client.baseUri; var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'lro/retryerror/postasync/retry/succeeded'; var queryParameters = []; if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects var httpRequest = new WebResource(); httpRequest.method = 'POST'; httpRequest.headers = {}; httpRequest.url = requestUrl; // Set Headers if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(var headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; // Serialize Request var requestContent = null; var requestModel = null; try { if (product !== null && product !== undefined) { var requestModelMapper = new client.models['Product']().mapper(); requestModel = client.serialize(requestModelMapper, product, 'product'); requestContent = JSON.stringify(requestModel); } } catch (error) { var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' + 'payload - "%s"', error.message, util.inspect(product, {depth: null}))); return callback(serializationError); } httpRequest.body = requestContent; // Send Request return client.pipeline(httpRequest, function (err, response, responseBody) { if (err) { return callback(err); } var statusCode = response.statusCode; if (statusCode !== 202) { var error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; var parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { var resultMapper = new client.models['CloudError']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + '- "%s" for the default response.', defaultError.message, responseBody); return callback(error); } return callback(error); } // Create Result var result = null; if (responseBody === '') responseBody = null; return callback(null, result, httpRequest, response); }); }; module.exports = LRORetrys;
/** * @author MPanknin / http://www.redplant.de/ * @author alteredq / http://alteredqualia.com/ */ THREE.AreaLight = function ( color, intensity ) { THREE.Light.call( this, color ); this.type = 'AreaLight'; this.normal = new THREE.Vector3( 0, - 1, 0 ); this.right = new THREE.Vector3( 1, 0, 0 ); this.intensity = ( intensity !== undefined ) ? intensity : 1; this.width = 1.0; this.height = 1.0; this.constantAttenuation = 1.5; this.linearAttenuation = 0.5; this.quadraticAttenuation = 0.1; }; THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
/*! * ui-grid - v4.4.0 - 2018-03-15 * Copyright (c) 2018 ; License: MIT */ (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.treeBase * @description * * # ui.grid.treeBase * * <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div> * * This module provides base tree handling functions that are shared by other features, notably grouping * and treeView. It provides a tree view of the data, with nodes in that * tree and leaves. * * Design information: * ------------------- * * The raw data that is provided must come with a $$treeLevel on any non-leaf node. Grouping will create * these on all the group header rows, treeView will expect these to be set in the raw data by the user. * TreeBase will run a rowsProcessor that: * - builds `treeBase.tree` out of the provided rows * - permits a recursive sort of the tree * - maintains the expand/collapse state of each node * - provides the expand/collapse all button and the expand/collapse buttons * - maintains the count of children for each node * * Each row is updated with a link to the tree node that represents it. Refer {@link ui.grid.treeBase.grid:treeBase.tree tree documentation} * for information. * * TreeBase adds information to the rows * - treeLevel: if present and > -1 tells us the level (level 0 is the top level) * - treeNode: pointer to the node in the grid.treeBase.tree that refers * to this row, allowing us to manipulate the state * * Since the logic is baked into the rowsProcessors, it should get triggered whenever * row order or filtering or anything like that is changed. We recall the expanded state * across invocations of the rowsProcessors by the reference to the treeNode on the individual * rows. We rebuild the tree itself quite frequently, when we do this we use the saved treeNodes to * get the state, but we overwrite the other data in that treeNode. * * By default rows are collapsed, which means all data rows have their visible property * set to false, and only level 0 group rows are set to visible. * * We rely on the rowsProcessors to do the actual expanding and collapsing, so we set the flags we want into * grid.treeBase.tree, then call refresh. This is because we can't easily change the visible * row cache without calling the processors, and once we've built the logic into the rowProcessors we may as * well use it all the time. * * Tree base provides sorting (on non-grouped columns). * * Sorting works in two passes. The standard sorting is performed for any columns that are important to building * the tree (for example, any grouped columns). Then after the tree is built, a recursive tree sort is performed * for the remaining sort columns (including the original sort) - these columns are sorted within each tree level * (so all the level 1 nodes are sorted, then all the level 2 nodes within each level 1 node etc). * * To achieve this we make use of the `ignoreSort` property on the sort configuration. The parent feature (treeView or grouping) * must provide a rowsProcessor that runs with very low priority (typically in the 60-65 range), and that sets * the `ignoreSort`on any sort that it wants to run on the tree. TreeBase will clear the ignoreSort on all sorts - so it * will turn on any sorts that haven't run. It will then call a recursive sort on the tree. * * Tree base provides treeAggregation. It checks the treeAggregation configuration on each column, and aggregates based on * the logic provided as it builds the tree. Footer aggregation from the uiGrid core should not be used with treeBase aggregation, * since it operates on all visible rows, as opposed to to leaf nodes only. Setting `showColumnFooter: true` will show the * treeAggregations in the column footer. Aggregation information will be collected in the format: * * ``` * { * type: 'count', * value: 4, * label: 'count: ', * rendered: 'count: 4' * } * ``` * * A callback is provided to format the value once it is finalised (aka a valueFilter). * * <br/> * <br/> * * <div doc-module-components="ui.grid.treeBase"></div> */ var module = angular.module('ui.grid.treeBase', ['ui.grid']); /** * @ngdoc object * @name ui.grid.treeBase.constant:uiGridTreeBaseConstants * * @description constants available in treeBase module. * * These constants are manually copied into grouping and treeView, * as I haven't found a way to simply include them, and it's not worth * investing time in for something that changes very infrequently. * */ module.constant('uiGridTreeBaseConstants', { featureName: "treeBase", rowHeaderColName: 'treeBaseRowHeaderCol', EXPANDED: 'expanded', COLLAPSED: 'collapsed', aggregation: { COUNT: 'count', SUM: 'sum', MAX: 'max', MIN: 'min', AVG: 'avg' } }); /** * @ngdoc service * @name ui.grid.treeBase.service:uiGridTreeBaseService * * @description Services for treeBase feature */ /** * @ngdoc object * @name ui.grid.treeBase.api:ColumnDef * * @description ColumnDef for tree feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs} */ module.service('uiGridTreeBaseService', ['$q', 'uiGridTreeBaseConstants', 'gridUtil', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants', 'rowSorter', function ($q, uiGridTreeBaseConstants, gridUtil, GridRow, gridClassFactory, i18nService, uiGridConstants, rowSorter) { var service = { initializeGrid: function (grid, $scope) { //add feature namespace and any properties to grid for needed /** * @ngdoc object * @name ui.grid.treeBase.grid:treeBase * * @description Grid properties and functions added for treeBase */ grid.treeBase = {}; /** * @ngdoc property * @propertyOf ui.grid.treeBase.grid:treeBase * @name numberLevels * * @description Total number of tree levels currently used, calculated by the rowsProcessor by * retaining the highest tree level it sees */ grid.treeBase.numberLevels = 0; /** * @ngdoc property * @propertyOf ui.grid.treeBase.grid:treeBase * @name expandAll * * @description Whether or not the expandAll box is selected */ grid.treeBase.expandAll = false; /** * @ngdoc property * @propertyOf ui.grid.treeBase.grid:treeBase * @name tree * * @description Tree represented as a nested array that holds the state of each node, along with a * pointer to the row. The array order is material - we will display the children in the order * they are stored in the array * * Each node stores: * * - the state of this node * - an array of children of this node * - a pointer to the parent of this node (reverse pointer, allowing us to walk up the tree) * - the number of children of this node * - aggregation information calculated from the nodes * * ``` * [{ * state: 'expanded', * row: <reference to row>, * parentRow: null, * aggregations: [{ * type: 'count', * col: <gridCol>, * value: 2, * label: 'count: ', * rendered: 'count: 2' * }], * children: [ * { * state: 'expanded', * row: <reference to row>, * parentRow: <reference to row>, * aggregations: [{ * type: 'count', * col: '<gridCol>, * value: 4, * label: 'count: ', * rendered: 'count: 4' * }], * children: [ * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> }, * { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> }, * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> }, * { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> } * ] * }, * { * state: 'collapsed', * row: <reference to row>, * parentRow: <reference to row>, * aggregations: [{ * type: 'count', * col: <gridCol>, * value: 3, * label: 'count: ', * rendered: 'count: 3' * }], * children: [ * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> }, * { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> }, * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> } * ] * } * ] * }, {<another level 0 node maybe>} ] * ``` * Missing state values are false - meaning they aren't expanded. * * This is used because the rowProcessors run every time the grid is refreshed, so * we'd lose the expanded state every time the grid was refreshed. This instead gives * us a reliable lookup that persists across rowProcessors. * * This tree is rebuilt every time we run the rowsProcessors. Since each row holds a pointer * to it's tree node we can persist expand/collapse state across calls to rowsProcessor, we discard * all transient information on the tree (children, childCount) and recalculate it * */ grid.treeBase.tree = []; service.defaultGridOptions(grid.options); grid.registerRowsProcessor(service.treeRows, 410); grid.registerColumnBuilder( service.treeBaseColumnBuilder ); service.createRowHeader( grid ); /** * @ngdoc object * @name ui.grid.treeBase.api:PublicApi * * @description Public Api for treeBase feature */ var publicApi = { events: { treeBase: { /** * @ngdoc event * @eventOf ui.grid.treeBase.api:PublicApi * @name rowExpanded * @description raised whenever a row is expanded. If you are dynamically * rendering your tree you can listen to this event, and then retrieve * the children of this row and load them into the grid data. * * When the data is loaded the grid will automatically refresh to show these new rows * * <pre> * gridApi.treeBase.on.rowExpanded(scope,function(row){}) * </pre> * @param {gridRow} row the row that was expanded. You can also * retrieve the grid from this row with row.grid */ rowExpanded: {}, /** * @ngdoc event * @eventOf ui.grid.treeBase.api:PublicApi * @name rowCollapsed * @description raised whenever a row is collapsed. Doesn't really have * a purpose at the moment, included for symmetry * * <pre> * gridApi.treeBase.on.rowCollapsed(scope,function(row){}) * </pre> * @param {gridRow} row the row that was collapsed. You can also * retrieve the grid from this row with row.grid */ rowCollapsed: {} } }, methods: { treeBase: { /** * @ngdoc function * @name expandAllRows * @methodOf ui.grid.treeBase.api:PublicApi * @description Expands all tree rows */ expandAllRows: function () { service.expandAllRows(grid); }, /** * @ngdoc function * @name collapseAllRows * @methodOf ui.grid.treeBase.api:PublicApi * @description collapse all tree rows */ collapseAllRows: function () { service.collapseAllRows(grid); }, /** * @ngdoc function * @name toggleRowTreeState * @methodOf ui.grid.treeBase.api:PublicApi * @description call expand if the row is collapsed, collapse if it is expanded * @param {gridRow} row the row you wish to toggle */ toggleRowTreeState: function (row) { service.toggleRowTreeState(grid, row); }, /** * @ngdoc function * @name expandRow * @methodOf ui.grid.treeBase.api:PublicApi * @description expand the immediate children of the specified row * @param {gridRow} row the row you wish to expand * @param {boolean} recursive true if you wish to expand the row's ancients */ expandRow: function (row, recursive) { service.expandRow(grid, row, recursive); }, /** * @ngdoc function * @name expandRowChildren * @methodOf ui.grid.treeBase.api:PublicApi * @description expand all children of the specified row * @param {gridRow} row the row you wish to expand */ expandRowChildren: function (row) { service.expandRowChildren(grid, row); }, /** * @ngdoc function * @name collapseRow * @methodOf ui.grid.treeBase.api:PublicApi * @description collapse the specified row. When * you expand the row again, all grandchildren will retain their state * @param {gridRow} row the row you wish to collapse */ collapseRow: function ( row ) { service.collapseRow(grid, row); }, /** * @ngdoc function * @name collapseRowChildren * @methodOf ui.grid.treeBase.api:PublicApi * @description collapse all children of the specified row. When * you expand the row again, all grandchildren will be collapsed * @param {gridRow} row the row you wish to collapse children for */ collapseRowChildren: function ( row ) { service.collapseRowChildren(grid, row); }, /** * @ngdoc function * @name getTreeState * @methodOf ui.grid.treeBase.api:PublicApi * @description Get the tree state for this grid, * used by the saveState feature * Returned treeState as an object * `{ expandedState: { uid: 'expanded', uid: 'collapsed' } }` * where expandedState is a hash of row uid and the current expanded state * * @returns {object} tree state * * TODO - this needs work - we need an identifier that persists across instantiations, * not uid. This really means we need a row identity defined, but that won't work for * grouping. Perhaps this needs to be moved up to treeView and grouping, rather than * being in base. */ getTreeExpandedState: function () { return { expandedState: service.getTreeState(grid) }; }, /** * @ngdoc function * @name setTreeState * @methodOf ui.grid.treeBase.api:PublicApi * @description Set the expanded states of the tree * @param {object} config the config you want to apply, in the format * provided by getTreeState */ setTreeState: function ( config ) { service.setTreeState( grid, config ); }, /** * @ngdoc function * @name getRowChildren * @methodOf ui.grid.treeBase.api:PublicApi * @description Get the children of the specified row * @param {GridRow} row the row you want the children of * @returns {Array} array of children of this row, the children * are all gridRows */ getRowChildren: function ( row ){ return row.treeNode.children.map( function( childNode ){ return childNode.row; }); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.treeBase.api:GridOptions * * @description GridOptions for treeBase feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name treeRowHeaderBaseWidth * @propertyOf ui.grid.treeBase.api:GridOptions * @description Base width of the tree header, provides for a single level of tree. This * is incremented by `treeIndent` for each extra level * <br/>Defaults to 30 */ gridOptions.treeRowHeaderBaseWidth = gridOptions.treeRowHeaderBaseWidth || 30; /** * @ngdoc object * @name treeIndent * @propertyOf ui.grid.treeBase.api:GridOptions * @description Number of pixels of indent for the icon at each tree level, wider indents are visually more pleasing, * but will make the tree row header wider * <br/>Defaults to 10 */ gridOptions.treeIndent = gridOptions.treeIndent || 10; /** * @ngdoc object * @name showTreeRowHeader * @propertyOf ui.grid.treeBase.api:GridOptions * @description If set to false, don't create the row header. You'll need to programmatically control the expand * states * <br/>Defaults to true */ gridOptions.showTreeRowHeader = gridOptions.showTreeRowHeader !== false; /** * @ngdoc object * @name showTreeExpandNoChildren * @propertyOf ui.grid.treeBase.api:GridOptions * @description If set to true, show the expand/collapse button even if there are no * children of a node. You'd use this if you're planning to dynamically load the children * * <br/>Defaults to true, grouping overrides to false */ gridOptions.showTreeExpandNoChildren = gridOptions.showTreeExpandNoChildren !== false; /** * @ngdoc object * @name treeRowHeaderAlwaysVisible * @propertyOf ui.grid.treeBase.api:GridOptions * @description If set to true, row header even if there are no tree nodes * * <br/>Defaults to true */ gridOptions.treeRowHeaderAlwaysVisible = gridOptions.treeRowHeaderAlwaysVisible !== false; /** * @ngdoc object * @name treeCustomAggregations * @propertyOf ui.grid.treeBase.api:GridOptions * @description Define custom aggregation functions. The properties of this object will be * aggregation types available for use on columnDef with {@link ui.grid.treeBase.api:ColumnDef treeAggregationType} or through the column menu. * If a function defined here uses the same name as one of the native aggregations, this one will take precedence. * The object format is: * * <pre> * { * aggregationName: { * label: (optional) string, * aggregationFn: function( aggregation, fieldValue, numValue, row ){...}, * finalizerFn: (optional) function( aggregation ){...} * }, * mean: { * label: 'mean', * aggregationFn: function( aggregation, fieldValue, numValue ){ * aggregation.count = (aggregation.count || 1) + 1; * aggregation.sum = (aggregation.sum || 0) + numValue; * }, * finalizerFn: function( aggregation ){ * aggregation.value = aggregation.sum / aggregation.count * } * } * } * </pre> * * <br/>The `finalizerFn` may be used to manipulate the value before rendering, or to * apply a custom rendered value. If `aggregation.rendered` is left undefined, the value will be * rendered. Note that the native aggregation functions use an `finalizerFn` to concatenate * the label and the value. * * <br/>Defaults to {} */ gridOptions.treeCustomAggregations = gridOptions.treeCustomAggregations || {}; /** * @ngdoc object * @name enableExpandAll * @propertyOf ui.grid.treeBase.api:GridOptions * @description Enable the expand all button at the top of the row header * * <br/>Defaults to true */ gridOptions.enableExpandAll = gridOptions.enableExpandAll !== false; }, /** * @ngdoc function * @name treeBaseColumnBuilder * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Sets the tree defaults based on the columnDefs * * @param {object} colDef columnDef we're basing on * @param {GridColumn} col the column we're to update * @param {object} gridOptions the options we should use * @returns {promise} promise for the builder - actually we do it all inline so it's immediately resolved */ treeBaseColumnBuilder: function (colDef, col, gridOptions) { /** * @ngdoc object * @name customTreeAggregationFn * @propertyOf ui.grid.treeBase.api:ColumnDef * @description A custom function that aggregates rows into some form of * total. Aggregations run row-by-row, the function needs to be capable of * creating a running total. * * The function will be provided the aggregation item (in which you can store running * totals), the row value that is to be aggregated, and that same row value converted to * a number (most aggregations work on numbers) * @example * <pre> * customTreeAggregationFn = function ( aggregation, fieldValue, numValue, row ){ * // calculates the average of the squares of the values * if ( typeof(aggregation.count) === 'undefined' ){ * aggregation.count = 0; * } * aggregation.count++; * * if ( !isNaN(numValue) ){ * if ( typeof(aggregation.total) === 'undefined' ){ * aggregation.total = 0; * } * aggregation.total = aggregation.total + numValue * numValue; * } * * aggregation.value = aggregation.total / aggregation.count; * } * </pre> * <br/>Defaults to undefined. May be overwritten by treeAggregationType, the two options should not be used together. */ if ( typeof(colDef.customTreeAggregationFn) !== 'undefined' ){ col.treeAggregationFn = colDef.customTreeAggregationFn; } /** * @ngdoc object * @name treeAggregationType * @propertyOf ui.grid.treeBase.api:ColumnDef * @description Use one of the native or grid-level aggregation methods for calculating aggregations on this column. * Native method are in the constants file and include: SUM, COUNT, MIN, MAX, AVG. This may also be the property the * name of an aggregation function defined with {@link ui.grid.treeBase.api:GridOptions treeCustomAggregations}. * * <pre> * treeAggregationType = uiGridTreeBaseConstants.aggregation.SUM, * } * </pre> * * If you are using aggregations you should either: * * - also use grouping, in which case the aggregations are displayed in the group header, OR * - use treeView, in which case you can set `treeAggregationUpdateEntity: true` in the colDef, and * treeBase will store the aggregation information in the entity, or you can set `treeAggregationUpdateEntity: false` * in the colDef, and you need to manual retrieve the calculated aggregations from the row.treeNode.aggregations * * <br/>Takes precendence over a treeAggregationFn, the two options should not be used together. * <br/>Defaults to undefined. */ if ( typeof(colDef.treeAggregationType) !== 'undefined' ){ col.treeAggregation = { type: colDef.treeAggregationType }; if ( typeof(gridOptions.treeCustomAggregations[colDef.treeAggregationType]) !== 'undefined' ){ col.treeAggregationFn = gridOptions.treeCustomAggregations[colDef.treeAggregationType].aggregationFn; col.treeAggregationFinalizerFn = gridOptions.treeCustomAggregations[colDef.treeAggregationType].finalizerFn; col.treeAggregation.label = gridOptions.treeCustomAggregations[colDef.treeAggregationType].label; } else if ( typeof(service.nativeAggregations()[colDef.treeAggregationType]) !== 'undefined' ){ col.treeAggregationFn = service.nativeAggregations()[colDef.treeAggregationType].aggregationFn; col.treeAggregation.label = service.nativeAggregations()[colDef.treeAggregationType].label; } } /** * @ngdoc object * @name treeAggregationLabel * @propertyOf ui.grid.treeBase.api:ColumnDef * @description A custom label to use for this aggregation. If provided we don't use native i18n. */ if ( typeof(colDef.treeAggregationLabel) !== 'undefined' ){ if (typeof(col.treeAggregation) === 'undefined' ){ col.treeAggregation = {}; } col.treeAggregation.label = colDef.treeAggregationLabel; } /** * @ngdoc object * @name treeAggregationUpdateEntity * @propertyOf ui.grid.treeBase.api:ColumnDef * @description Store calculated aggregations into the entity, allowing them * to be displayed in the grid using a standard cellTemplate. This defaults to true, * if you are using grouping then you shouldn't set it to false, as then the aggregations won't * display. * * If you are using treeView in most cases you'll want to set this to true. This will result in * getCellValue returning the aggregation rather than whatever was stored in the cell attribute on * the entity. If you want to render the underlying entity value (and do something else with the aggregation) * then you could use a custom cellTemplate to display `row.entity.myAttribute`, rather than using getCellValue. * * <br/>Defaults to true * * @example * <pre> * gridOptions.columns = [{ * name: 'myCol', * treeAggregation: { type: uiGridTreeBaseConstants.aggregation.SUM }, * treeAggregationUpdateEntity: true * cellTemplate: '<div>{{row.entity.myCol + " " + row.treeNode.aggregations[0].rendered}}</div>' * }]; * </pre> */ col.treeAggregationUpdateEntity = colDef.treeAggregationUpdateEntity !== false; /** * @ngdoc object * @name customTreeAggregationFinalizerFn * @propertyOf ui.grid.treeBase.api:ColumnDef * @description A custom function that populates aggregation.rendered, this is called when * a particular aggregation has been fully calculated, and we want to render the value. * * With the native aggregation options we just concatenate `aggregation.label` and * `aggregation.value`, but if you wanted to apply a filter or otherwise manipulate the label * or the value, you can do so with this function. This function will be called after the * the default `finalizerFn`. * * @example * <pre> * customTreeAggregationFinalizerFn = function ( aggregation ){ * aggregation.rendered = aggregation.label + aggregation.value / 100 + '%'; * } * </pre> * <br/>Defaults to undefined. */ if ( typeof(col.customTreeAggregationFinalizerFn) === 'undefined' ){ col.customTreeAggregationFinalizerFn = colDef.customTreeAggregationFinalizerFn; } }, /** * @ngdoc function * @name createRowHeader * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Create the rowHeader. If treeRowHeaderAlwaysVisible then * set it to visible, otherwise set it to invisible * * @param {Grid} grid grid object */ createRowHeader: function( grid ){ var rowHeaderColumnDef = { name: uiGridTreeBaseConstants.rowHeaderColName, displayName: '', width: grid.options.treeRowHeaderBaseWidth, minWidth: 10, cellTemplate: 'ui-grid/treeBaseRowHeader', headerCellTemplate: 'ui-grid/treeBaseHeaderCell', enableColumnResizing: false, enableColumnMenu: false, exporterSuppressExport: true, allowCellFocus: true }; rowHeaderColumnDef.visible = grid.options.treeRowHeaderAlwaysVisible; grid.addRowHeaderColumn(rowHeaderColumnDef, -100); }, /** * @ngdoc function * @name expandAllRows * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Expands all nodes in the tree * * @param {Grid} grid grid object */ expandAllRows: function (grid) { grid.treeBase.tree.forEach( function( node ) { service.setAllNodes( grid, node, uiGridTreeBaseConstants.EXPANDED); }); grid.treeBase.expandAll = true; grid.queueGridRefresh(); }, /** * @ngdoc function * @name collapseAllRows * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Collapses all nodes in the tree * * @param {Grid} grid grid object */ collapseAllRows: function (grid) { grid.treeBase.tree.forEach( function( node ) { service.setAllNodes( grid, node, uiGridTreeBaseConstants.COLLAPSED); }); grid.treeBase.expandAll = false; grid.queueGridRefresh(); }, /** * @ngdoc function * @name setAllNodes * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Works through a subset of grid.treeBase.rowExpandedStates, setting * all child nodes (and their descendents) of the provided node to the given state. * * Calls itself recursively on all nodes so as to achieve this. * * @param {Grid} grid the grid we're operating on (so we can raise events) * @param {object} treeNode a node in the tree that we want to update * @param {string} targetState the state we want to set it to */ setAllNodes: function (grid, treeNode, targetState) { if ( typeof(treeNode.state) !== 'undefined' && treeNode.state !== targetState ){ treeNode.state = targetState; if ( targetState === uiGridTreeBaseConstants.EXPANDED ){ grid.api.treeBase.raise.rowExpanded(treeNode.row); } else { grid.api.treeBase.raise.rowCollapsed(treeNode.row); } } // set all child nodes if ( treeNode.children ){ treeNode.children.forEach(function( childNode ){ service.setAllNodes(grid, childNode, targetState); }); } }, /** * @ngdoc function * @name toggleRowTreeState * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Toggles the expand or collapse state of this grouped row, if * it's a parent row * * @param {Grid} grid grid object * @param {GridRow} row the row we want to toggle */ toggleRowTreeState: function ( grid, row ){ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){ return; } if (row.treeNode.state === uiGridTreeBaseConstants.EXPANDED){ service.collapseRow(grid, row); } else { service.expandRow(grid, row, false); } grid.queueGridRefresh(); }, /** * @ngdoc function * @name expandRow * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Expands this specific row, showing only immediate children. * * @param {Grid} grid grid object * @param {GridRow} row the row we want to expand * @param {boolean} recursive true if you wish to expand the row's ancients */ expandRow: function ( grid, row, recursive ){ if ( recursive ){ var parents = []; while ( row && typeof(row.treeLevel) !== 'undefined' && row.treeLevel !== null && row.treeLevel >= 0 && row.treeNode.state !== uiGridTreeBaseConstants.EXPANDED ){ parents.push(row); row = row.treeNode.parentRow; } if ( parents.length > 0 ){ row = parents.pop(); while ( row ){ row.treeNode.state = uiGridTreeBaseConstants.EXPANDED; grid.api.treeBase.raise.rowExpanded(row); row = parents.pop(); } grid.treeBase.expandAll = service.allExpanded(grid.treeBase.tree); grid.queueGridRefresh(); } } else { if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){ return; } if ( row.treeNode.state !== uiGridTreeBaseConstants.EXPANDED ){ row.treeNode.state = uiGridTreeBaseConstants.EXPANDED; grid.api.treeBase.raise.rowExpanded(row); grid.treeBase.expandAll = service.allExpanded(grid.treeBase.tree); grid.queueGridRefresh(); } } }, /** * @ngdoc function * @name expandRowChildren * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Expands this specific row, showing all children. * * @param {Grid} grid grid object * @param {GridRow} row the row we want to expand */ expandRowChildren: function ( grid, row ){ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){ return; } service.setAllNodes(grid, row.treeNode, uiGridTreeBaseConstants.EXPANDED); grid.treeBase.expandAll = service.allExpanded(grid.treeBase.tree); grid.queueGridRefresh(); }, /** * @ngdoc function * @name collapseRow * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Collapses this specific row * * @param {Grid} grid grid object * @param {GridRow} row the row we want to collapse */ collapseRow: function( grid, row ){ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){ return; } if ( row.treeNode.state !== uiGridTreeBaseConstants.COLLAPSED ){ row.treeNode.state = uiGridTreeBaseConstants.COLLAPSED; grid.treeBase.expandAll = false; grid.api.treeBase.raise.rowCollapsed(row); grid.queueGridRefresh(); } }, /** * @ngdoc function * @name collapseRowChildren * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Collapses this specific row and all children * * @param {Grid} grid grid object * @param {GridRow} row the row we want to collapse */ collapseRowChildren: function( grid, row ){ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){ return; } service.setAllNodes(grid, row.treeNode, uiGridTreeBaseConstants.COLLAPSED); grid.treeBase.expandAll = false; grid.queueGridRefresh(); }, /** * @ngdoc function * @name allExpanded * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Returns true if all rows are expanded, false * if they're not. Walks the tree to determine this. Used * to set the expandAll state. * * If the node has no children, then return true (it's immaterial * whether it is expanded). If the node has children, then return * false if this node is collapsed, or if any child node is not all expanded * * @param {object} tree the grid to check * @returns {boolean} whether or not the tree is all expanded */ allExpanded: function( tree ){ var allExpanded = true; tree.forEach( function( node ){ if ( !service.allExpandedInternal( node ) ){ allExpanded = false; } }); return allExpanded; }, allExpandedInternal: function( treeNode ){ if ( treeNode.children && treeNode.children.length > 0 ){ if ( treeNode.state === uiGridTreeBaseConstants.COLLAPSED ){ return false; } var allExpanded = true; treeNode.children.forEach( function( node ){ if ( !service.allExpandedInternal( node ) ){ allExpanded = false; } }); return allExpanded; } else { return true; } }, /** * @ngdoc function * @name treeRows * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description The rowProcessor that adds the nodes to the tree, and sets the visible * state of each row based on it's parent state * * Assumes it is always called after the sorting processor, and the grouping processor if there is one. * Performs any tree sorts itself after having built the tree * * Processes all the rows in order, setting the group level based on the $$treeLevel in the associated * entity, and setting the visible state based on the parent's state. * * Calculates the deepest level of tree whilst it goes, and updates that so that the header column can be correctly * sized. * * Aggregates if necessary along the way. * * @param {array} renderableRows the rows we want to process, usually the output from the previous rowProcessor * @returns {array} the updated rows */ treeRows: function( renderableRows ) { if (renderableRows.length === 0){ return renderableRows; } var grid = this; var currentLevel = 0; var currentState = uiGridTreeBaseConstants.EXPANDED; var parents = []; grid.treeBase.tree = service.createTree( grid, renderableRows ); service.updateRowHeaderWidth( grid ); service.sortTree( grid ); service.fixFilter( grid ); return service.renderTree( grid.treeBase.tree ); }, /** * @ngdoc function * @name createOrUpdateRowHeaderWidth * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Calculates the rowHeader width. * * If rowHeader is always present, updates the width. * * If rowHeader is only sometimes present (`treeRowHeaderAlwaysVisible: false`), determines whether there * should be one, then creates or removes it as appropriate, with the created rowHeader having the * right width. * * If there's never a rowHeader then never creates one: `showTreeRowHeader: false` * * @param {Grid} grid the grid we want to set the row header on */ updateRowHeaderWidth: function( grid ){ var rowHeader = grid.getColumn(uiGridTreeBaseConstants.rowHeaderColName); var newWidth = grid.options.treeRowHeaderBaseWidth + grid.options.treeIndent * Math.max(grid.treeBase.numberLevels - 1, 0); if ( rowHeader && newWidth !== rowHeader.width ){ rowHeader.width = newWidth; grid.queueRefresh(); } var newVisibility = true; if ( grid.options.showTreeRowHeader === false ){ newVisibility = false; } if ( grid.options.treeRowHeaderAlwaysVisible === false && grid.treeBase.numberLevels <= 0 ){ newVisibility = false; } if ( rowHeader && rowHeader.visible !== newVisibility ) { rowHeader.visible = newVisibility; rowHeader.colDef.visible = newVisibility; grid.queueGridRefresh(); } }, /** * @ngdoc function * @name renderTree * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Creates an array of rows based on the tree, exporting only * the visible nodes and leaves * * @param {array} nodeList the list of nodes - can be grid.treeBase.tree, or can be node.children when * we're calling recursively * @returns {array} renderable rows */ renderTree: function( nodeList ){ var renderableRows = []; nodeList.forEach( function ( node ){ if ( node.row.visible ){ renderableRows.push( node.row ); } if ( node.state === uiGridTreeBaseConstants.EXPANDED && node.children && node.children.length > 0 ){ renderableRows = renderableRows.concat( service.renderTree( node.children ) ); } }); return renderableRows; }, /** * @ngdoc function * @name createTree * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Creates a tree from the renderableRows * * @param {Grid} grid the grid * @param {array} renderableRows the rows we want to create a tree from * @returns {object} the tree we've build */ createTree: function( grid, renderableRows ) { var currentLevel = -1; var parents = []; var currentState; grid.treeBase.tree = []; grid.treeBase.numberLevels = 0; var aggregations = service.getAggregations( grid ); var createNode = function( row ){ if ( typeof(row.entity.$$treeLevel) !== 'undefined' && row.treeLevel !== row.entity.$$treeLevel ){ row.treeLevel = row.entity.$$treeLevel; } if ( row.treeLevel <= currentLevel ){ // pop any levels that aren't parents of this level, formatting the aggregation at the same time while ( row.treeLevel <= currentLevel ){ var lastParent = parents.pop(); service.finaliseAggregations( lastParent ); currentLevel--; } // reset our current state based on the new parent, set to expanded if this is a level 0 node if ( parents.length > 0 ){ currentState = service.setCurrentState(parents); } else { currentState = uiGridTreeBaseConstants.EXPANDED; } } // aggregate if this is a leaf node if ( ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ) && row.visible ){ service.aggregate( grid, row, parents ); } // add this node to the tree service.addOrUseNode(grid, row, parents, aggregations); if ( typeof(row.treeLevel) !== 'undefined' && row.treeLevel !== null && row.treeLevel >= 0 ){ parents.push(row); currentLevel++; currentState = service.setCurrentState(parents); } // update the tree number of levels, so we can set header width if we need to if ( grid.treeBase.numberLevels < row.treeLevel + 1){ grid.treeBase.numberLevels = row.treeLevel + 1; } }; renderableRows.forEach( createNode ); // finalise remaining aggregations while ( parents.length > 0 ){ var lastParent = parents.pop(); service.finaliseAggregations( lastParent ); } return grid.treeBase.tree; }, /** * @ngdoc function * @name addOrUseNode * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Creates a tree node for this row. If this row already has a treeNode * recorded against it, preserves the state, but otherwise overwrites the data. * * @param {grid} grid the grid we're operating on * @param {gridRow} row the row we want to set * @param {array} parents an array of the parents this row should have * @param {array} aggregationBase empty aggregation information * @returns {undefined} updates the parents array, updates the row to have a treeNode, and updates the * grid.treeBase.tree */ addOrUseNode: function( grid, row, parents, aggregationBase ){ var newAggregations = []; aggregationBase.forEach( function(aggregation){ newAggregations.push(service.buildAggregationObject(aggregation.col)); }); var newNode = { state: uiGridTreeBaseConstants.COLLAPSED, row: row, parentRow: null, aggregations: newAggregations, children: [] }; if ( row.treeNode ){ newNode.state = row.treeNode.state; } if ( parents.length > 0 ){ newNode.parentRow = parents[parents.length - 1]; } row.treeNode = newNode; if ( parents.length === 0 ){ grid.treeBase.tree.push( newNode ); } else { parents[parents.length - 1].treeNode.children.push( newNode ); } }, /** * @ngdoc function * @name setCurrentState * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Looks at the parents array to determine our current state. * If any node in the hierarchy is collapsed, then return collapsed, otherwise return * expanded. * * @param {array} parents an array of the parents this row should have * @returns {string} the state we should be setting to any nodes we see */ setCurrentState: function( parents ){ var currentState = uiGridTreeBaseConstants.EXPANDED; parents.forEach( function(parent){ if ( parent.treeNode.state === uiGridTreeBaseConstants.COLLAPSED ){ currentState = uiGridTreeBaseConstants.COLLAPSED; } }); return currentState; }, /** * @ngdoc function * @name sortTree * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Performs a recursive sort on the tree nodes, sorting the * children of each node and putting them back into the children array. * * Before doing this it turns back on all the sortIgnore - things that were previously * ignored we process now. Since we're sorting within the nodes, presumably anything * that was already sorted is how we derived the nodes, we can keep those sorts too. * * We only sort tree nodes that are expanded - no point in wasting effort sorting collapsed * nodes * * @param {Grid} grid the grid to get the aggregation information from * @returns {array} the aggregation information */ sortTree: function( grid ){ grid.columns.forEach( function( column ) { if ( column.sort && column.sort.ignoreSort ){ delete column.sort.ignoreSort; } }); grid.treeBase.tree = service.sortInternal( grid, grid.treeBase.tree ); }, sortInternal: function( grid, treeList ){ var rows = treeList.map( function( node ){ return node.row; }); rows = rowSorter.sort( grid, rows, grid.columns ); var treeNodes = rows.map( function( row ){ return row.treeNode; }); treeNodes.forEach( function( node ){ if ( node.state === uiGridTreeBaseConstants.EXPANDED && node.children && node.children.length > 0 ){ node.children = service.sortInternal( grid, node.children ); } }); return treeNodes; }, /** * @ngdoc function * @name fixFilter * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description After filtering has run, we need to go back through the tree * and make sure the parent rows are always visible if any of the child rows * are visible (filtering may make a child visible, but the parent may not * match the filter criteria) * * This has a risk of being computationally expensive, we do it by walking * the tree and remembering whether there are any invisible nodes on the * way down. * * @param {Grid} grid the grid to fix filters on */ fixFilter: function( grid ){ var parentsVisible; grid.treeBase.tree.forEach( function( node ){ if ( node.children && node.children.length > 0 ){ parentsVisible = node.row.visible; service.fixFilterInternal( node.children, parentsVisible ); } }); }, fixFilterInternal: function( nodes, parentsVisible) { nodes.forEach( function( node ){ if ( node.row.visible && !parentsVisible ){ service.setParentsVisible( node ); parentsVisible = true; } if ( node.children && node.children.length > 0 ){ if ( service.fixFilterInternal( node.children, ( parentsVisible && node.row.visible ) ) ) { parentsVisible = true; } } }); return parentsVisible; }, setParentsVisible: function( node ){ while ( node.parentRow ){ node.parentRow.visible = true; node = node.parentRow.treeNode; } }, /** * @ngdoc function * @name buildAggregationObject * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Build the object which is stored on the column for holding meta-data about the aggregation. * This method should only be called with columns which have an aggregation. * * @param {Column} the column which this object relates to * @returns {object} {col: Column object, label: string, type: string (optional)} */ buildAggregationObject: function( column ){ var newAggregation = { col: column }; if ( column.treeAggregation && column.treeAggregation.type ){ newAggregation.type = column.treeAggregation.type; } if ( column.treeAggregation && column.treeAggregation.label ){ newAggregation.label = column.treeAggregation.label; } return newAggregation; }, /** * @ngdoc function * @name getAggregations * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Looks through the grid columns to find those with aggregations, * and collates the aggregation information into an array, returns that array * * @param {Grid} grid the grid to get the aggregation information from * @returns {array} the aggregation information */ getAggregations: function( grid ){ var aggregateArray = []; grid.columns.forEach( function(column){ if ( typeof(column.treeAggregationFn) !== 'undefined' ){ aggregateArray.push( service.buildAggregationObject(column) ); if ( grid.options.showColumnFooter && typeof(column.colDef.aggregationType) === 'undefined' && column.treeAggregation ){ // Add aggregation object for footer column.treeFooterAggregation = service.buildAggregationObject(column); column.aggregationType = service.treeFooterAggregationType; } } }); return aggregateArray; }, /** * @ngdoc function * @name aggregate * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Accumulate the data from this row onto the aggregations for each parent * * Iterate over the parents, then iterate over the aggregations for each of those parents, * and perform the aggregation for each individual aggregation * * @param {Grid} grid grid object * @param {GridRow} row the row we want to set grouping visibility on * @param {array} parents the parents that we would want to aggregate onto */ aggregate: function( grid, row, parents ){ if ( parents.length === 0 && row.treeNode && row.treeNode.aggregations ){ row.treeNode.aggregations.forEach(function(aggregation){ // Calculate aggregations for footer even if there are no grouped rows if ( typeof(aggregation.col.treeFooterAggregation) !== 'undefined' ) { var fieldValue = grid.getCellValue(row, aggregation.col); var numValue = Number(fieldValue); aggregation.col.treeAggregationFn(aggregation.col.treeFooterAggregation, fieldValue, numValue, row); } }); } parents.forEach( function( parent, index ){ if ( parent.treeNode.aggregations ){ parent.treeNode.aggregations.forEach( function( aggregation ){ var fieldValue = grid.getCellValue(row, aggregation.col); var numValue = Number(fieldValue); aggregation.col.treeAggregationFn(aggregation, fieldValue, numValue, row); if ( index === 0 && typeof(aggregation.col.treeFooterAggregation) !== 'undefined' ){ aggregation.col.treeAggregationFn(aggregation.col.treeFooterAggregation, fieldValue, numValue, row); } }); } }); }, // Aggregation routines - no doco needed as self evident nativeAggregations: function() { var nativeAggregations = { count: { label: i18nService.get().aggregation.count, menuTitle: i18nService.get().grouping.aggregate_count, aggregationFn: function (aggregation, fieldValue, numValue) { if (typeof(aggregation.value) === 'undefined') { aggregation.value = 1; } else { aggregation.value++; } } }, sum: { label: i18nService.get().aggregation.sum, menuTitle: i18nService.get().grouping.aggregate_sum, aggregationFn: function( aggregation, fieldValue, numValue ) { if (!isNaN(numValue)) { if (typeof(aggregation.value) === 'undefined') { aggregation.value = numValue; } else { aggregation.value += numValue; } } } }, min: { label: i18nService.get().aggregation.min, menuTitle: i18nService.get().grouping.aggregate_min, aggregationFn: function( aggregation, fieldValue, numValue ) { if (typeof(aggregation.value) === 'undefined') { aggregation.value = fieldValue; } else { if (typeof(fieldValue) !== 'undefined' && fieldValue !== null && (fieldValue < aggregation.value || aggregation.value === null)) { aggregation.value = fieldValue; } } } }, max: { label: i18nService.get().aggregation.max, menuTitle: i18nService.get().grouping.aggregate_max, aggregationFn: function( aggregation, fieldValue, numValue ){ if ( typeof(aggregation.value) === 'undefined' ){ aggregation.value = fieldValue; } else { if ( typeof(fieldValue) !== 'undefined' && fieldValue !== null && (fieldValue > aggregation.value || aggregation.value === null)){ aggregation.value = fieldValue; } } } }, avg: { label: i18nService.get().aggregation.avg, menuTitle: i18nService.get().grouping.aggregate_avg, aggregationFn: function( aggregation, fieldValue, numValue ){ if ( typeof(aggregation.count) === 'undefined' ){ aggregation.count = 1; } else { aggregation.count++; } if ( isNaN(numValue) ){ return; } if ( typeof(aggregation.value) === 'undefined' || typeof(aggregation.sum) === 'undefined' ){ aggregation.value = numValue; aggregation.sum = numValue; } else { aggregation.sum += numValue; aggregation.value = aggregation.sum / aggregation.count; } } } }; return nativeAggregations; }, /** * @ngdoc function * @name finaliseAggregation * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Helper function used to finalize aggregation nodes and footer cells * * @param {gridRow} row the parent we're finalising * @param {aggregation} the aggregation object manipulated by the aggregationFn */ finaliseAggregation: function(row, aggregation){ if ( aggregation.col.treeAggregationUpdateEntity && typeof(row) !== 'undefined' && typeof(row.entity[ '$$' + aggregation.col.uid ]) !== 'undefined' ){ angular.extend( aggregation, row.entity[ '$$' + aggregation.col.uid ]); } if ( typeof(aggregation.col.treeAggregationFinalizerFn) === 'function' ){ aggregation.col.treeAggregationFinalizerFn( aggregation ); } if ( typeof(aggregation.col.customTreeAggregationFinalizerFn) === 'function' ){ aggregation.col.customTreeAggregationFinalizerFn( aggregation ); } if ( typeof(aggregation.rendered) === 'undefined' ){ aggregation.rendered = aggregation.label ? aggregation.label + aggregation.value : aggregation.value; } }, /** * @ngdoc function * @name finaliseAggregations * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Format the data from the aggregation into the rendered text * e.g. if we had label: 'sum: ' and value: 25, we'd create 'sum: 25'. * * As part of this we call any formatting callback routines we've been provided. * * We write our aggregation out to the row.entity if treeAggregationUpdateEntity is * set on the column - we don't overwrite any information that's already there, we append * to it so that grouping can have set the groupVal beforehand without us overwriting it. * * We need to copy the data from the row.entity first before we finalise the aggregation, * we need that information for the finaliserFn * * @param {gridRow} row the parent we're finalising */ finaliseAggregations: function( row ){ if ( row == null || typeof(row.treeNode.aggregations) === 'undefined' ){ return; } row.treeNode.aggregations.forEach( function( aggregation ) { service.finaliseAggregation(row, aggregation); if ( aggregation.col.treeAggregationUpdateEntity ){ var aggregationCopy = {}; angular.forEach( aggregation, function( value, key ){ if ( aggregation.hasOwnProperty(key) && key !== 'col' ){ aggregationCopy[key] = value; } }); row.entity[ '$$' + aggregation.col.uid ] = aggregationCopy; } }); }, /** * @ngdoc function * @name treeFooterAggregationType * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Uses the tree aggregation functions and finalizers to set the * column footer aggregations. * * @param {rows} visible rows. not used, but accepted to match signature of GridColumn.aggregationType * @param {GridColumn} column the column we are finalizing */ treeFooterAggregationType: function( rows, column ) { service.finaliseAggregation(undefined, column.treeFooterAggregation); if ( typeof(column.treeFooterAggregation.value) === 'undefined' || column.treeFooterAggregation.rendered === null ){ // The was apparently no aggregation performed (perhaps this is a grouped column return ''; } return column.treeFooterAggregation.rendered; } }; return service; }]); /** * @ngdoc directive * @name ui.grid.treeBase.directive:uiGridTreeRowHeaderButtons * @element div * * @description Provides the expand/collapse button on rows */ module.directive('uiGridTreeBaseRowHeaderButtons', ['$templateCache', 'uiGridTreeBaseService', function ($templateCache, uiGridTreeBaseService) { return { replace: true, restrict: 'E', template: $templateCache.get('ui-grid/treeBaseRowHeaderButtons'), scope: true, require: '^uiGrid', link: function($scope, $elm, $attrs, uiGridCtrl) { var self = uiGridCtrl.grid; $scope.treeButtonClick = function(row, evt) { uiGridTreeBaseService.toggleRowTreeState(self, row, evt); }; } }; }]); /** * @ngdoc directive * @name ui.grid.treeBase.directive:uiGridTreeBaseExpandAllButtons * @element div * * @description Provides the expand/collapse all button */ module.directive('uiGridTreeBaseExpandAllButtons', ['$templateCache', 'uiGridTreeBaseService', function ($templateCache, uiGridTreeBaseService) { return { replace: true, restrict: 'E', template: $templateCache.get('ui-grid/treeBaseExpandAllButtons'), scope: false, link: function($scope, $elm, $attrs, uiGridCtrl) { var self = $scope.col.grid; $scope.headerButtonClick = function(row, evt) { if ( self.treeBase.expandAll ){ uiGridTreeBaseService.collapseAllRows(self, evt); } else { uiGridTreeBaseService.expandAllRows(self, evt); } }; } }; }]); /** * @ngdoc directive * @name ui.grid.treeBase.directive:uiGridViewport * @element div * * @description Stacks on top of ui.grid.uiGridViewport to set formatting on a tree header row */ module.directive('uiGridViewport', ['$compile', 'uiGridConstants', 'gridUtil', '$parse', function ($compile, uiGridConstants, gridUtil, $parse) { return { priority: -200, // run after default directive scope: false, compile: function ($elm, $attrs) { var rowRepeatDiv = angular.element($elm.children().children()[0]); var existingNgClass = rowRepeatDiv.attr("ng-class"); var newNgClass = ''; if ( existingNgClass ) { newNgClass = existingNgClass.slice(0, -1) + ",'ui-grid-tree-header-row': row.treeLevel > -1}"; } else { newNgClass = "{'ui-grid-tree-header-row': row.treeLevel > -1}"; } rowRepeatDiv.attr("ng-class", newNgClass); return { pre: function ($scope, $elm, $attrs, controllers) { }, post: function ($scope, $elm, $attrs, controllers) { } }; } }; }]); })();
'use strict'; const chalk = require('chalk'); module.exports = function(message, test) { if (test) { console.log(chalk.yellow(`DEPRECATION: ${message}`)); } }; module.exports.deprecateUI = function(ui) { return function(message, test) { ui.writeDeprecateLine('The deprecateUI utility has been deprecated in favor of ui.writeDeprecateLine'); test = !test; ui.writeDeprecateLine(message, test); }; };
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; var _excluded = ["children", "align", "controlSize", "mode", "stretched", "before", "className", "style", "getRef", "getRootRef", "onClick"]; import { createScopedElement } from "../../lib/jsxRuntime"; import { getClassName } from "../../helpers/getClassName"; import Button from "../Button/Button"; import { usePlatform } from "../../hooks/usePlatform"; import { useExternRef } from "../../hooks/useExternRef"; import "./File.css"; var File = function File(props) { var children = props.children, align = props.align, controlSize = props.controlSize, mode = props.mode, stretched = props.stretched, before = props.before, className = props.className, style = props.style, getRef = props.getRef, getRootRef = props.getRootRef, _onClick = props.onClick, restProps = _objectWithoutProperties(props, _excluded); var platform = usePlatform(); var inputRef = useExternRef(getRef); return createScopedElement(Button, { align: align, vkuiClass: getClassName('File', platform), className: className, stretched: stretched, mode: mode, size: controlSize, before: before, style: style, getRootRef: getRootRef, disabled: restProps.disabled, type: "button", onClick: function onClick(e) { inputRef.current.click(); _onClick && _onClick(e); } }, createScopedElement("input", _extends({}, restProps, { vkuiClass: "File__input", type: "file", ref: inputRef })), children); }; File.defaultProps = { children: 'Выберите файл', align: 'left' }; export default File; //# sourceMappingURL=File.js.map
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'clipboard', 'bg', { copy: 'Копирай', copyError: 'Настройките за сигурност на вашия бразуър не разрешават на редактора да изпълни запаметяването. За целта използвайте клавиатурата (Ctrl/Cmd+C).', cut: 'Отрежи', cutError: 'Настройките за сигурност на Вашия браузър не позволяват на редактора автоматично да изъплни действията за отрязване. Моля ползвайте клавиатурните команди за целта (ctrl+x).', paste: 'Вмъкни', pasteArea: 'Зона за вмъкване', pasteMsg: 'Вмъкнете тук съдъжанието с клавиатуарата (<STRONG>Ctrl/Cmd+V</STRONG>) и натиснете <STRONG>OK</STRONG>.', securityMsg: 'Заради настройките за сигурност на Вашия браузър, редакторът не може да прочете данните от клипборда коректно.', title: 'Вмъкни' } );
var BrowserBuffer = require('../').Buffer // (this module) var util = require('./util') var suite = util.suite() var LENGTH = 160 var browserBuffer = new BrowserBuffer(LENGTH * 8) var typedarray = new Uint8Array(LENGTH * 8) var dataview = new DataView(typedarray.buffer) var nodeBuffer = new Buffer(LENGTH * 8) ;[browserBuffer, nodeBuffer].forEach(function (buf) { for (var i = 0; i < LENGTH; i++) { buf.writeDoubleBE(97.1919 + i, i * 8) } }) for (var i = 0; i < LENGTH; i++) { dataview.setFloat64(i * 8, 97.1919 + i) } suite .add('BrowserBuffer#readDoubleBE', function () { for (var i = 0; i < LENGTH; i++) { var x = browserBuffer.readDoubleBE(i * 8) } }) .add('DataView#getFloat64', function () { for (var i = 0; i < LENGTH; i++) { var x = dataview.getFloat64(i * 8) } }) if (!process.browser) suite .add('NodeBuffer#readDoubleBE', function () { for (var i = 0; i < LENGTH; i++) { var x = nodeBuffer.readDoubleBE(i * 8) } })
function getTrimmedAttribute(sourceAttribute) { return sourceAttribute.substring(8); }
/* * Copyright 2014-2015 Guy Bedford (http://guybedford.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ require('core-js/es6/string'); var config = require('./config'); var Promise = require('rsvp').Promise; var asp = require('rsvp').denodeify; var pkg = require('./package'); var semver = require('./semver'); var PackageName = require('./config/package-name'); var ui = require('./ui'); var path = require('path'); var link = require('./link'); var globalConfig = require('./global-config'); var rimraf = require('rimraf'); var alphabetize = require('./common').alphabetize; var cascadeDelete = require('./common').cascadeDelete; var hasProperties = require('./common').hasProperties; var fs = require('graceful-fs'); var primaryRanges = {}; var secondaryRanges = {}; var installedResolves = {}; var installingResolves = {}; var installed; var installing = { baseMap: {}, depMap: {} }; // NB remove assertions for release // function assert(statement, name) { // if (!statement) // throw new TypeError('Assertion Failed: ' + name); // } /* * Main install API wrapper * * install('jquery') * install('jquery', {options}) * install('jquery', 'github:components/jquery') * install('jquery', 'github:components/jquery', {options}) * install(true) - from package.json * install(true, {options}) - from package.json * * options.force - skip cache * options.inject * options.link means symlink linked versions in ranges to jspm_packages where available * options.lock - lock existing tree dependencies * options.latest - new install tree has all deps installed to latest - no rollback deduping * options.unlink * options.quick - lock and skip hash checks * options.dev - store in devDependencies * options.update - we're updating the targets * * options.summary - show fork and resolution summary */ exports.install = function(targets, options) { if (typeof targets === 'string') { var name = targets; targets = {}; targets[name] = typeof options === 'string' ? options : ''; options = typeof options === 'object' ? options : arguments[2]; } options = options || {}; return config.load() .then(function() { installed = installed || config.loader; if (options.force) config.force = true; if (options.link || options.quick) options.lock = true; var d, existingTargets = {}; for (d in config.pjson.devDependencies) existingTargets[d] = config.pjson.devDependencies[d]; for (d in config.pjson.dependencies) existingTargets[d] = config.pjson.dependencies[d]; if (targets === true) targets = existingTargets; // check and set targets for update else if (targets && options.update) for (d in targets) { if (!existingTargets[d]) throw '%' + d + '% is not an existing dependency to update.'; targets[d] = existingTargets[d]; } targets = pkg.processDeps(targets, globalConfig.config.defaultRegistry); return Promise.all(Object.keys(targets).map(function(name) { return install(name, targets[name], options); })) .then(function() { return saveInstall(); }) .then(function() { // after every install, show fork and resolution summary if (options.summary !== false) showVersions(true); }); }); }; /* * install('jquery', 'jquery', { latest, lock, parent, inject, link, unlink, override } [, seen]) * * Install modes: * - Default a. The new install tree is set to use exact latest versions of primaries, * including for existing primaries. * Secondaries tend to their latest ideal version. * b. Forks within the new tree are deduped for secondaries by checking for * rollback of the higher version. * c. Forks against the existing tree are handled by upgrading the existing * tree, at both primary and secondary levels, with the secondary fork * potentially rolling back as well. * (this is `jspm install package`) * * - Lock No existing dependencies are altered. * New installs otherwise follow default behaviour for secondary deduping. * (this is reproducible installs, `jspm install` without arguments) * * - Latest Secondaries set exactly to latest. * Forks against existing tree follow default behaviour. * (this is `jspm update`) * * Lock and Latest can be combined, which won't do anything for existing * installs but will give latest secondaries on new installs. * * Secondary installs are those with a parent. * * Seen allows correct completion with circular package installs * */ /* * jspm.install('jquery') * jspm.install('jquery', 'github:components/jquery@^2.0.0') * jspm.install('jquery', '2') * jspm.install('jquery', 'github:components/jquery') * jspm.install('jquery', { force: true }); * jspm.install({ jquery: '1.2.3' }, { force: true }) */ function install(name, target, options, seen) { // we install a target range, to an exact version resolution var resolution; var dependencyDownloads; var existing; return Promise.resolve() .then(function() { if (options.link) return Promise.resolve(target); return pkg.locate(target); }) .then(function(located) { target = located; config.loader.ensureRegistry(located.registry, options.inject); if (options.link) return link.lookup(target, options.edge); // lock if necessary if (options.lock && (resolution = getInstalledMatch(target, options.parent, name))) return Promise.resolve(); // perform a full version lookup return pkg.lookup(target, options.edge); }) .then(function(getLatestMatch) { if (!getLatestMatch) return storeResolution(); // --- version constraint solving --- // a. The new install tree is set to use exact latest versions of primaries, including for existing primaries. // Secondaries tend to their latest ideal version. resolution = getLatestMatch(target.version); if (!resolution) { if (options.parent) throw 'Installing `' + options.parent + '`, no version match for `' + target.exactName + '`'; else throw 'No version match found for `' + target.exactName + '`'; } // if no version range was specified on install, install to semver-compatible with the latest if (!options.parent && !target.version && !options.link) { if (resolution.version.match(semver.semverRegEx)) target.setVersion('^' + resolution.version); else target.setVersion(resolution.version); } else if (options.edge && !options.parent && !options.link) { // use strictest compatible semver range if installing --edge without target, or // with a range that does not include the resolved version if (!target.version || !semver.match(target.version, resolution.version)) { target.setVersion('^' + resolution.version); } } // load our fork ranges to do a resolution return loadExistingForkRanges(resolution, name, options.parent, options.inject) .then(function() { // here, alter means upgrade or rollback // if we've consolidated with another resolution, we don't do altering var consolidated = false; // b. Forks within the new tree are deduped for secondaries by checking for rollback of the higher version if (!options.latest) resolveForks(installing, name, options.parent, resolution, function(forkVersion, forkRanges, allSecondary) { // alter the other secondaries to this primary or secondary if (allSecondary && forkRanges.every(function(forkRange) { return semver.match(forkRange, resolution.version); })) { consolidated = true; return resolution.version; } // alter this secondary install to the other primary or secondary if (!consolidated && options.parent && semver.match(target.version, forkVersion)) { consolidated = true; if (forkVersion !== resolution.version) { var newResolution = resolution.copy().setVersion(forkVersion); logResolution(installingResolves, resolution, newResolution); resolution = newResolution; } } }); // c. Forks against the existing tree are handled by upgrading the existing tree, // at both primary and secondary levels, with the secondary fork potentially rolling back as well. resolveForks(installed, name, options.parent, resolution, function(forkVersion, forkRanges) { if (options.latest && semver.compare(forkVersion, resolution.version) === 1) return; if (forkRanges.every(function(forkRange) { return semver.match(forkRange, resolution.version); })) { consolidated = true; return resolution.version; } // find the best upgrade of all the fork ranges for rollback of secondaries if (!consolidated && options.parent && !options.latest) { var bestSecondaryRollback = resolution; forkRanges.forEach(function(forkRange) { var forkLatest = getLatestMatch(forkRange); if (semver.compare(bestSecondaryRollback.version, forkLatest.version) === 1) bestSecondaryRollback = forkLatest; }); if (semver.compare(bestSecondaryRollback.version, forkVersion) === -1) bestSecondaryRollback = getLatestMatch(forkVersion); if (semver.match(target.version, bestSecondaryRollback.version)) { consolidated = true; logResolution(installingResolves, resolution, bestSecondaryRollback); resolution = bestSecondaryRollback; return bestSecondaryRollback.version; } } }); // solve and save resolution solution synchronously - this lock avoids solution conflicts storeResolution(); }); }) .then(function() { // -- handle circular installs -- seen = seen || []; if (seen.indexOf(resolution.exactName) !== -1) return; seen.push(resolution.exactName); // -- download -- return Promise.resolve() .then(function() { if (options.link) return link.symlink(resolution, downloadDeps); if (options.inject) return pkg.inject(resolution, downloadDeps); // override, quick, unlink options passed return pkg.download(resolution, options, downloadDeps); }) .then(function(fresh) { resolution.fresh = fresh; // log sub-dependencies before child completion for nicer output if (options.parent) logInstall(name, target, resolution, options); return dependencyDownloads; }) .then(function() { if (!options.parent) logInstall(name, target, resolution, options); }); }); // store resolution in config function storeResolution() { var curMap; if (options.parent) { curMap = (existing ? installed : installing).depMap; curMap[options.parent] = curMap[options.parent] || {}; curMap[options.parent][name] = resolution.copy(); } else { curMap = (existing ? installed : installing).baseMap; curMap[name] = resolution.copy(); } // update the dependency range tree if (!options.parent) { if (!primaryRanges[name] || primaryRanges[name].exactName !== target.exactName) primaryRanges[name] = target.copy(); // store in package.json if (!options.link) { if (name in config.pjson.dependencies) config.pjson.dependencies[name] = primaryRanges[name]; else if (name in config.pjson.devDependencies) config.pjson.devDependencies[name] = primaryRanges[name]; else if (!options.dev) { config.pjson.dependencies[name] = primaryRanges[name]; } else { config.pjson.devDependencies[name] = primaryRanges[name]; } if (options.override) config.pjson.overrides[resolution.exactName] = options.override; } } else { // update the secondary ranges secondaryRanges[options.parent] = secondaryRanges[options.parent] || {}; if (!secondaryRanges[options.parent][name]) secondaryRanges[options.parent][name] = target.copy(); else if (secondaryRanges[options.parent][name] && secondaryRanges[options.parent][name].exactName !== target.exactName) ui.log('warn', 'Currently installed dependency ranges of `' + options.parent + '` are not consistent ( %' + secondaryRanges[options.parent][name].exactName + '% should be %' + target.exactName + '%)'); } } // trigger dependency downloads // this can be triggered twice // - once by initial preload, and once post-build if additional dependencies are discovered function downloadDeps(depMap) { // clear existing dependencies on first run for existing installs if (!dependencyDownloads && existing) installed.depMap[resolution.exactName] = {}; dependencyDownloads = (dependencyDownloads || Promise.resolve()).then(function() { return Promise.all(Object.keys(depMap).map(function(dep) { return install(dep, depMap[dep], { latest: options.latest, lock: options.lock, parent: resolution.exactName, inject: options.inject, quick: options.quick }, seen); })); }); } } function getInstalledMatch(target, parent, name) { // use the config lock if provided if (parent) { if (installed.depMap[parent] && installed.depMap[parent][name]) return installed.depMap[parent][name]; } else { if (installed.baseMap[name]) return installed.baseMap[name]; } // otherwise seek an installed match var match; function checkMatch(pkg) { if (pkg.name !== target.name) return; if (semver.match(target.version, pkg.version)) { if (!match || match && semver.compare(pkg.version, match.version) === 1) match = pkg.copy(); } } Object.keys(installed.baseMap).forEach(function(name) { checkMatch(installed.baseMap[name]); }); Object.keys(installed.depMap).forEach(function(parent) { var depMap = installed.depMap[parent]; Object.keys(depMap).forEach(function(name) { checkMatch(depMap[name]); }); }); return match; } function saveInstall() { return Promise.resolve() .then(function() { // merge the installing tree into the installed Object.keys(installing.baseMap).forEach(function(p) { installed.baseMap[p] = installing.baseMap[p]; }); Object.keys(installing.depMap).forEach(function(p) { installed.depMap[p] = installing.depMap[p]; }); return clean(); }) .then(function() { if (hasProperties(installedResolves)) { ui.log(''); ui.log('info', 'The following existing package versions were altered by install deduping:'); ui.log(''); Object.keys(installedResolves).forEach(function(pkg) { var pkgName = new PackageName(pkg); ui.log('info', ' %' + pkgName.package + '% ' + getUpdateRangeText(pkgName, new PackageName(installedResolves[pkg]))); }); ui.log(''); installedResolves = {}; ui.log('info', 'To keep existing dependencies locked during install, use the %--lock% option.'); } if (hasProperties(installingResolves)) { ui.log(''); ui.log('info', 'The following new package versions were substituted by install deduping:'); ui.log(''); Object.keys(installingResolves).forEach(function(pkg) { var pkgName = new PackageName(pkg); ui.log('info', ' %' + pkgName.package + '% ' + getUpdateRangeText(pkgName, new PackageName(installingResolves[pkg]))); }); ui.log('') ; installingResolves = {}; } // then save return config.save(); }); } var logged = {}; function logInstall(name, target, resolution, options) { if (logged[target.exactName + '=' + resolution.exactName]) return; // don't log secondary fresh if (options.parent && resolution.fresh) return; logged[target.exactName + '=' + resolution.exactName] = true; var verb; if (options.inject) verb = 'Injected'; else if (!resolution.fresh) { if (!options.link) verb = 'Installed'; else verb = 'Linked'; } else { if (options.quick) return; if (!options.link) verb = 'Up to date -'; else verb = 'Already linked -'; } if (options.parent) ui.log('ok', verb + ' `' + target.exactName + '` (' + resolution.version + ')'); else ui.log('ok', verb + ' %' + name + '% as `' + target.exactName + '` (' + resolution.version + ')'); } function getUpdateRangeText(existing, update) { if (existing.name === update.name) return '`' + existing.version + '` -> `' + update.version + '`'; else return '`' + existing.exactName + '` -> `' + update.exactName + '`'; } // go through the baseMap and depMap, changing FROM to TO // keep a log of what we did in resolveLog function doResolution(tree, from, to) { if (from.exactName === to.exactName) return; // add this to the resolve log, including deep-updating resolution chains logResolution(tree === installed ? installedResolves : installingResolves, from, to); Object.keys(tree.baseMap).forEach(function(dep) { if (tree.baseMap[dep].exactName === from.exactName) tree.baseMap[dep] = to.copy(); }); Object.keys(tree.depMap).forEach(function(parent) { var curMap = tree.depMap[parent]; Object.keys(curMap).forEach(function(dep) { if (curMap[dep].exactName === from.exactName) curMap[dep] = to.copy(); }); }); } function logResolution(resolveLog, from, to) { resolveLog[from.exactName] = to.exactName; Object.keys(resolveLog).forEach(function(resolveFrom) { if (resolveLog[resolveFrom] === from.exactName) resolveLog[resolveFrom] = to.exactName; }); } // name and parentName are the existing resolution target // so we only look up forks and not the original as well function loadExistingForkRanges(resolution, name, parentName, inject) { var tree = installed; return Promise.all(Object.keys(tree.baseMap).map(function(dep) { if (!parentName && dep === name) return; var primary = tree.baseMap[dep]; if (primary.name !== resolution.name) return; return loadExistingRange(dep, null, inject); })) .then(function() { return Promise.all(Object.keys(tree.depMap).map(function(parent) { var curDepMap = tree.depMap[parent]; return Promise.all(Object.keys(curDepMap).map(function(dep) { if (parent === parentName && dep === name) return; var secondary = curDepMap[dep]; if (secondary.name !== resolution.name) return; return loadExistingRange(dep, parent, inject); })); })); }); } function visitForkRanges(tree, resolution, name, parentName, visit) { // now that we've got all the version ranges we need for consideration, // go through and run resolutions against the fork list Object.keys(tree.baseMap).forEach(function(dep) { var primary = tree.baseMap[dep]; if (primary.name !== resolution.name) return; visit(dep, null, primary, primaryRanges[dep]); }); Object.keys(tree.depMap).forEach(function(parent) { var curDepMap = tree.depMap[parent]; Object.keys(curDepMap).forEach(function(dep) { var secondary = curDepMap[dep]; if (secondary.name !== resolution.name) return; // its not a fork of itself if (dep === name && parent === parentName) return; // skip if we don't have a range if (!secondaryRanges[parent]) return; visit(dep, parent, secondary, secondaryRanges[parent][dep]); }); }); } // find all forks of this resolution in the tree // calling resolve(forkVersion, forkRanges, allSecondary) // for each unique fork version // sync resolution to avoid conflicts function resolveForks(tree, name, parentName, resolution, resolve) { // forks is a map from fork versions to an object, { ranges, hasPrimary } // hasPrimary indicates whether any of these ranges are primary ranges var forks = {}; var forkVersions = []; visitForkRanges(tree, resolution, name, parentName, function(dep, parent, resolved, range) { if (!range) return; // we only work with stuff within it's own matching range // not user overrides if (range.name !== resolved.name || !semver.match(range.version, resolved.version)) return; var forkObj = forks[resolved.version]; if (!forkObj) { forkObj = forks[resolved.version] = { ranges: [], allSecondary: true }; forkVersions.push(resolved.version); } if (!parent) forkObj.allSecondary = false; forkObj.ranges.push(range.version); }); // now run through and resolve the forks forkVersions.sort(semver.compare).reverse().forEach(function(forkVersion) { var forkObj = forks[forkVersion]; var newVersion = resolve(forkVersion, forkObj.ranges, forkObj.allSecondary); if (!newVersion || newVersion === forkVersion) return; var from = resolution.copy().setVersion(forkVersion); var to = resolution.copy().setVersion(newVersion); doResolution(tree, from, to); }); } var secondaryDepsPromises = {}; function loadExistingRange(name, parent, inject) { if (parent && secondaryRanges[parent] && secondaryRanges[parent][name]) return; else if (!parent && primaryRanges[name]) return; var _target; return Promise.resolve() .then(function() { if (!parent) return config.pjson.dependencies[name] || config.pjson.devDependencies[name]; return Promise.resolve() .then(function() { if (secondaryDepsPromises[parent]) return secondaryDepsPromises[parent]; return Promise.resolve() .then(function() { var parentPkg = new PackageName(parent); // if the package is installed but not in jspm_packages // then we wait on the getPackageConfig or download of the package here return (secondaryDepsPromises[parent] = new Promise(function(resolve, reject) { if (inject) return pkg.inject(parentPkg, resolve).catch(reject); if (config.deps[parentPkg.exactName]) return resolve(); pkg.download(parentPkg, {}, resolve).then(resolve, reject); }) .then(function(depMap) { if (depMap) return depMap; return config.deps; })); }); }) .then(function(deps) { return deps[name]; }); }) .then(function(target) { if (!target) { if (parent && installed.depMap[parent] && installed.depMap[parent].name) { delete installed.depMap[parent].name; ui.log('warn', '%' + parent + '% dependency %' + name + '% was removed from the config file to reflect the installed package.'); } else if (!parent) { ui.log('warn', '%' + name + '% is installed in the config file, but is not a dependency in the package.json. It is advisable to add it to the package.json file.'); } return; } _target = target.copy(); // locate the target return pkg.locate(_target) .then(function(located) { if (parent) { secondaryRanges[parent] = secondaryRanges[parent] || {}; secondaryRanges[parent][name] = located; } else { primaryRanges[name] = located; } }); }); } // given an exact package, find all the forks, and display the ranges function showInstallGraph(pkg) { installed = installed || config.loader; pkg = new PackageName(pkg); var lastParent; var found; return loadExistingForkRanges(pkg, config.loader.local) .then(function() { ui.log('info', '\nInstalled versions of %' + pkg.name + '%'); visitForkRanges(installed, pkg, null, null, function(name, parent, resolved, range) { found = true; if (range.version === '') range.version = '*'; var rangeVersion = range.name === resolved.name ? range.version : range.exactName; if (range.version === '*') range.version = ''; if (!parent) ui.log('info', '\n %' + name + '% `' + resolved.version + '` (' + rangeVersion + ')'); else { if (lastParent !== parent) { ui.log('info', '\n ' + parent); lastParent = parent; } ui.log('info', ' ' + name + ' `' + resolved.version + '` (' + rangeVersion + ')'); } }); if (!found) ui.log('warn', 'Package `' + pkg.name + '` not found.'); ui.log(''); }); } exports.showInstallGraph = showInstallGraph; function showVersions(forks) { installed = installed || config.loader; var versions = {}; var haveLinked = false; var linkedVersions = {}; function addDep(dep) { var vList = versions[dep.name] = versions[dep.name] || []; var version = dep.version; try { if (fs.readlinkSync(dep.getPath())) linkedVersions[dep.exactName] = true; } catch(e) {} if (vList.indexOf(version) === -1) vList.push(version); } Object.keys(installed.baseMap).forEach(function(dep) { addDep(installed.baseMap[dep]); }); Object.keys(installed.depMap).forEach(function(parent) { var curMap = installed.depMap[parent]; Object.keys(curMap).forEach(function(dep) { addDep(curMap[dep]); }); }); versions = alphabetize(versions); var vLen = Object.keys(versions).map(function(dep) { return dep.length; }).reduce(function(a, b) { return Math.max(a, b); }, 0); var shownIntro = false; Object.keys(versions).forEach(function(dep) { var vList = versions[dep].sort(semver.compare).map(function(version) { if (linkedVersions[dep + '@' + version]) { haveLinked = true; return '%' + version + '%'; } else return '`' + version + '`'; }); if (forks && vList.length === 1) return; if (!shownIntro) { ui.log('info', 'Installed ' + (forks ? 'Forks' : 'Versions') + '\n'); shownIntro = true; } var padding = vLen - dep.length; var paddingString = ''; while(padding--) paddingString += ' '; ui.log('info', ' ' + paddingString + '%' + dep + '% ' + vList.join(' ')); }); if (haveLinked) { ui.log('info', '\nBold versions are linked. To unlink use %jspm install --unlink [name]%.'); } if (shownIntro) { ui.log('info', '\nTo inspect individual package constraints, use %jspm inspect registry:name%.\n'); } else if (forks) { ui.log('ok', 'Install tree has no forks.'); } } exports.showVersions = showVersions; /* * Configuration cleaning * * 1. Construct list of all packages in main tree tracing from package.json primary installs * 2. Remove all orphaned dependencies not in this list * 3. Remove any package.json overrides that will never match this list * 4. Remove packages in .dependencies.json that aren't used at all * 5. Remove anything from jspm_packages not in this list * */ function clean() { var packageList = []; return config.load() .then(function() { // 1. getDependentPackages for each of baseMap Object.keys(config.loader.baseMap).forEach(function(dep) { getDependentPackages(config.loader.baseMap[dep].exactName, packageList); }); // 2. now that we have the package list, remove everything not in it Object.keys(config.loader.depMap).forEach(function(dep) { if (packageList.indexOf(dep) === -1) { ui.log('info', 'Clearing configuration for `' + dep + '`'); delete config.loader.depMap[dep]; } }); // 3. remove package.json overrides which will never match any packages var usedOverrides = []; packageList.forEach(function(pkgName) { var pkgVersion = pkgName.split('@').pop(); pkgName = pkgName.substr(0, pkgName.length - pkgVersion.length - 1); var overrideVersion = Object.keys(config.pjson.overrides) .filter(function(overrideName) { return overrideName.startsWith(pkgName + '@'); }) .map(function(overrideName) { return overrideName.split('@').pop(); }) .filter(function(overrideVersion) { return semver.match('^' + overrideVersion, pkgVersion); }) .sort(semver.compare).pop(); if (overrideVersion) usedOverrides.push(pkgName + '@' + overrideVersion); }); Object.keys(config.pjson.overrides).forEach(function(overrideName) { if (usedOverrides.indexOf(overrideName) == -1) { ui.log('info', 'Removing unused package.json override `' + overrideName + '`'); delete config.pjson.overrides[overrideName]; } }); }) .then(function() { return asp(fs.lstat)(config.pjson.packages).then(function(stats) { // Skip if jspm_packages is symlinked if (stats.isSymbolicLink()) return; // 4. Remove packages in .dependencies.json that aren't used at all Object.keys(config.deps).forEach(function(dep) { if (packageList.indexOf(dep) == -1) delete config.deps[dep]; }); // 5. Remove anything from jspm_packages not in this list return readDirWithDepth(config.pjson.packages, function(dirname) { if (dirname.split(path.sep).pop().indexOf('@') <= 0) return true; }) .then(function(packageDirs) { return Promise.all( packageDirs .filter(function(dir) { var exactName = path.relative(config.pjson.packages, dir).replace(path.sep, ':').replace(/\\/g, '/'); // (win) var remove = packageList.indexOf(exactName) === -1; if (remove) ui.log('info', 'Removing package files for `' + exactName + '`'); return remove; }) .map(function(dir) { return asp(rimraf)(dir) .then(function() { var filename = dir + '.js'; return new Promise(function(resolve) { fs.exists(filename, resolve); }).then(function(exists) { if (exists) return asp(fs.unlink)(filename); }); }) .then(function() { return cascadeDelete(dir); }); })); }); }); }) .then(function() { return config.save(); }); } exports.clean = clean; // depthCheck returns true to keep going (files being ignored), false to add the dir to the flat list function readDirWithDepth(dir, depthCheck) { var flatDirs = []; return asp(fs.readdir)(dir) .then(function(files) { if (!files) return []; return Promise.all(files.map(function(file) { var filepath = path.resolve(dir, file); // ensure it is a directory return asp(fs.lstat)(filepath) .then(function(fileInfo) { if (!fileInfo.isDirectory()) return; if (!depthCheck(filepath)) return flatDirs.push(filepath); // keep going return readDirWithDepth(filepath, depthCheck) .then(function(items) { items.forEach(function(item) { flatDirs.push(item); }); }); }); })); }) .then(function() { return flatDirs; }); } function getDependentPackages(pkg, packages) { packages.push(pkg); // get all immediate children of this package // for those children not already seen (in packages list), // run getDependentPackages in turn on those var depMap = config.loader.depMap[pkg]; if (!depMap) return; Object.keys(depMap).forEach(function(dep) { var curPkg = depMap[dep].exactName; if (packages.indexOf(curPkg) !== -1) return; getDependentPackages(curPkg, packages); }); return packages; } exports.uninstall = function(names) { if (!(names instanceof Array)) names = [names]; return config.load() .then(function() { installed = installed || config.loader; names.forEach(function(name) { if (!config.pjson.dependencies[name] && !config.pjson.devDependencies[name]) ui.log('warn', 'Dependency %' + name + '% is not an existing primary install.'); delete config.pjson.dependencies[name]; delete config.pjson.devDependencies[name]; delete installed.baseMap[name]; }); return clean(); }); }; /* * Resolve all installs of the given package to a specific version */ exports.resolveOnly = function(pkg) { pkg = new PackageName(pkg); if (!pkg.version || !pkg.registry) { ui.log('warn', 'Resolve --only must take an exact package of the form `registry:pkg@version`.'); return Promise.reject(); } var didSomething = false; return config.load() .then(function() { Object.keys(config.loader.baseMap).forEach(function(name) { var curPkg = config.loader.baseMap[name]; if (curPkg.registry === pkg.registry && curPkg.package === pkg.package && curPkg.version !== pkg.version) { didSomething = true; ui.log('info', 'Primary install ' + getUpdateRangeText(curPkg, pkg)); config.loader.baseMap[name] = pkg.copy(); } }); Object.keys(config.loader.depMap).forEach(function(parent) { var curMap = config.loader.depMap[parent]; Object.keys(curMap).forEach(function(name) { var curPkg = curMap[name]; if (curPkg.registry === pkg.registry && curPkg.package === pkg.package && curPkg.version !== pkg.version) { didSomething = true; ui.log('info', 'In %' + parent + '% ' + getUpdateRangeText(curPkg, pkg)); curMap[name] = pkg.copy(); } }); }); return config.save(); }) .then(function() { if (didSomething) ui.log('ok', 'Resolution to only use `' + pkg.exactName + '` completed successfully.'); else ui.log('ok', '`' + pkg.exactName + '` is already the only version of the package in use.'); }); };
/* flatpickr v4.2.0, @license MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.mn = {}))); }(this, (function (exports) { 'use strict'; var fp = typeof window !== "undefined" && window.flatpickr !== undefined ? window.flatpickr : { l10ns: {}, }; var Mongolian = { firstDayOfWeek: 1, weekdays: { shorthand: ["Да", "Мя", "Лх", "Пү", "Ба", "Бя", "Ня"], longhand: ["Даваа", "Мягмар", "Лхагва", "Пүрэв", "Баасан", "Бямба", "Ням"], }, months: { shorthand: [ "1-р сар", "2-р сар", "3-р сар", "4-р сар", "5-р сар", "6-р сар", "7-р сар", "8-р сар", "9-р сар", "10-р сар", "11-р сар", "12-р сар", ], longhand: [ "Нэгдүгээр сар", "Хоёрдугаар сар", "Гуравдугаар сар", "Дөрөвдүгээр сар", "Тавдугаар сар", "Зургаадугаар сар", "Долдугаар сар", "Наймдугаар сар", "Есдүгээр сар", "Аравдугаар сар", "Арваннэгдүгээр сар", "Арванхоёрдугаар сар", ], }, rangeSeparator: "-с ", }; fp.l10ns.mn = Mongolian; var mn = fp.l10ns; exports.Mongolian = Mongolian; exports['default'] = mn; Object.defineProperty(exports, '__esModule', { value: true }); })));
QUnit.test( 'pixel rounding', function( assert ) { var container = document.querySelector('#pixel-rounding'); var msnry = new Masonry( container, { gutter: '.gutter-sizer', itemSelector: '.item', transitionDuration: 0 }); var lastItem = msnry.items[2]; var containerWidth = 170; while ( containerWidth < 210 ) { container.style.width = containerWidth + 'px'; msnry.layout(); assert.equal( lastItem.position.y, 0,'3rd item on top row, container width = ' + containerWidth ); containerWidth++; } });
var specify = require('specify') , helpers = require('../helpers') , timeout = helpers.timeout , nano = helpers.nano , nock = helpers.nock ; var mock = nock(helpers.couch, "shared/headers") , db = nano.use("shared_headers") ; specify("shared_headers:setup", timeout, function (assert) { nano.db.create("shared_headers", function (err) { assert.equal(err, undefined, "Failed to create database"); }); }); specify("shared_headers:test", timeout, function (assert) { db.attachment.insert("new", "att", "Hello", "text/plain", function(error, hello) { assert.equal(error, undefined, "Should store hello"); assert.equal(hello.ok, true, "Response should be ok"); assert.ok(hello.rev, "Should have a revision number"); nano.request({ db: "shared_headers", doc: "new", headers: { "If-None-Match": JSON.stringify(hello.rev) } }, function (error, helloWorld, rh) { assert.equal(error, undefined, "Should get the hello"); assert.equal(rh["status-code"], 304, "status is 'not modified'"); }); nano.request({ db: "shared_headers", doc: "new", att: "att" }, function (error, helloWorld, rh) { assert.equal(error, undefined, "Should get the hello"); assert.equal(rh["status-code"], 200, "status is 'ok'"); }); }); }); specify("shared_headers:teardown", timeout, function (assert) { nano.db.destroy("shared_headers", function (err) { assert.equal(err, undefined, "Failed to destroy database"); assert.ok(mock.isDone(), "Some mocks didn't run"); }); }); specify.run(process.argv.slice(2));
/* AngularJS v1.3.1 (c) 2010-2014 Google, Inc. http://angularjs.org License: MIT */ (function(N,U,t){'use strict';function w(b){return function(){var a=arguments[0],c;c="["+(b?b+":":"")+a+"] http://errors.angularjs.org/1.3.1/"+(b?b+"/":"")+a;for(a=1;a<arguments.length;a++){c=c+(1==a?"?":"&")+"p"+(a-1)+"=";var d=encodeURIComponent,e;e=arguments[a];e="function"==typeof e?e.toString().replace(/ \{[\s\S]*$/,""):"undefined"==typeof e?"undefined":"string"!=typeof e?JSON.stringify(e):e;c+=d(e)}return Error(c)}}function Qa(b){if(null==b||Ra(b))return!1;var a=b.length;return b.nodeType=== ka&&a?!0:J(b)||H(b)||0===a||"number"===typeof a&&0<a&&a-1 in b}function s(b,a,c){var d,e;if(b)if(A(b))for(d in b)"prototype"==d||"length"==d||"name"==d||b.hasOwnProperty&&!b.hasOwnProperty(d)||a.call(c,b[d],d,b);else if(H(b)||Qa(b)){var f="object"!==typeof b;d=0;for(e=b.length;d<e;d++)(f||d in b)&&a.call(c,b[d],d,b)}else if(b.forEach&&b.forEach!==s)b.forEach(a,c,b);else for(d in b)b.hasOwnProperty(d)&&a.call(c,b[d],d,b);return b}function Cd(b,a,c){for(var d=Object.keys(b).sort(),e=0;e<d.length;e++)a.call(c, b[d[e]],d[e]);return d}function jc(b){return function(a,c){b(c,a)}}function Dd(){return++gb}function kc(b,a){a?b.$$hashKey=a:delete b.$$hashKey}function F(b){for(var a=b.$$hashKey,c=1,d=arguments.length;c<d;c++){var e=arguments[c];if(e)for(var f=Object.keys(e),g=0,k=f.length;g<k;g++){var h=f[g];b[h]=e[h]}}kc(b,a);return b}function aa(b){return parseInt(b,10)}function lc(b,a){return F(new (F(function(){},{prototype:b})),a)}function y(){}function Sa(b){return b}function da(b){return function(){return b}} function x(b){return"undefined"===typeof b}function z(b){return"undefined"!==typeof b}function P(b){return null!==b&&"object"===typeof b}function J(b){return"string"===typeof b}function X(b){return"number"===typeof b}function ea(b){return"[object Date]"===Ja.call(b)}function A(b){return"function"===typeof b}function hb(b){return"[object RegExp]"===Ja.call(b)}function Ra(b){return b&&b.window===b}function Ta(b){return b&&b.$evalAsync&&b.$watch}function Ua(b){return"boolean"===typeof b}function mc(b){return!(!b|| !(b.nodeName||b.prop&&b.attr&&b.find))}function Ed(b){var a={};b=b.split(",");var c;for(c=0;c<b.length;c++)a[b[c]]=!0;return a}function pa(b){return S(b.nodeName||b[0].nodeName)}function Va(b,a){var c=b.indexOf(a);0<=c&&b.splice(c,1);return a}function Ca(b,a,c,d){if(Ra(b)||Ta(b))throw Wa("cpws");if(a){if(b===a)throw Wa("cpi");c=c||[];d=d||[];if(P(b)){var e=c.indexOf(b);if(-1!==e)return d[e];c.push(b);d.push(a)}if(H(b))for(var f=a.length=0;f<b.length;f++)e=Ca(b[f],null,c,d),P(b[f])&&(c.push(b[f]), d.push(e)),a.push(e);else{var g=a.$$hashKey;H(a)?a.length=0:s(a,function(b,c){delete a[c]});for(f in b)b.hasOwnProperty(f)&&(e=Ca(b[f],null,c,d),P(b[f])&&(c.push(b[f]),d.push(e)),a[f]=e);kc(a,g)}}else if(a=b)H(b)?a=Ca(b,[],c,d):ea(b)?a=new Date(b.getTime()):hb(b)?(a=new RegExp(b.source,b.toString().match(/[^\/]*$/)[0]),a.lastIndex=b.lastIndex):P(b)&&(e=Object.create(Object.getPrototypeOf(b)),a=Ca(b,e,c,d));return a}function qa(b,a){if(H(b)){a=a||[];for(var c=0,d=b.length;c<d;c++)a[c]=b[c]}else if(P(b))for(c in a= a||{},b)if("$"!==c.charAt(0)||"$"!==c.charAt(1))a[c]=b[c];return a||b}function la(b,a){if(b===a)return!0;if(null===b||null===a)return!1;if(b!==b&&a!==a)return!0;var c=typeof b,d;if(c==typeof a&&"object"==c)if(H(b)){if(!H(a))return!1;if((c=b.length)==a.length){for(d=0;d<c;d++)if(!la(b[d],a[d]))return!1;return!0}}else{if(ea(b))return ea(a)?la(b.getTime(),a.getTime()):!1;if(hb(b)&&hb(a))return b.toString()==a.toString();if(Ta(b)||Ta(a)||Ra(b)||Ra(a)||H(a))return!1;c={};for(d in b)if("$"!==d.charAt(0)&& !A(b[d])){if(!la(b[d],a[d]))return!1;c[d]=!0}for(d in a)if(!c.hasOwnProperty(d)&&"$"!==d.charAt(0)&&a[d]!==t&&!A(a[d]))return!1;return!0}return!1}function ib(b,a,c){return b.concat(Xa.call(a,c))}function nc(b,a){var c=2<arguments.length?Xa.call(arguments,2):[];return!A(a)||a instanceof RegExp?a:c.length?function(){return arguments.length?a.apply(b,c.concat(Xa.call(arguments,0))):a.apply(b,c)}:function(){return arguments.length?a.apply(b,arguments):a.call(b)}}function Fd(b,a){var c=a;"string"===typeof b&& "$"===b.charAt(0)&&"$"===b.charAt(1)?c=t:Ra(a)?c="$WINDOW":a&&U===a?c="$DOCUMENT":Ta(a)&&(c="$SCOPE");return c}function ra(b,a){return"undefined"===typeof b?t:JSON.stringify(b,Fd,a?" ":null)}function oc(b){return J(b)?JSON.parse(b):b}function sa(b){b=v(b).clone();try{b.empty()}catch(a){}var c=v("<div>").append(b).html();try{return b[0].nodeType===jb?S(c):c.match(/^(<[^>]+>)/)[1].replace(/^<([\w\-]+)/,function(a,b){return"<"+S(b)})}catch(d){return S(c)}}function pc(b){try{return decodeURIComponent(b)}catch(a){}} function qc(b){var a={},c,d;s((b||"").split("&"),function(b){b&&(c=b.replace(/\+/g,"%20").split("="),d=pc(c[0]),z(d)&&(b=z(c[1])?pc(c[1]):!0,Hb.call(a,d)?H(a[d])?a[d].push(b):a[d]=[a[d],b]:a[d]=b))});return a}function Ib(b){var a=[];s(b,function(b,d){H(b)?s(b,function(b){a.push(Da(d,!0)+(!0===b?"":"="+Da(b,!0)))}):a.push(Da(d,!0)+(!0===b?"":"="+Da(b,!0)))});return a.length?a.join("&"):""}function kb(b){return Da(b,!0).replace(/%26/gi,"&").replace(/%3D/gi,"=").replace(/%2B/gi,"+")}function Da(b,a){return encodeURIComponent(b).replace(/%40/gi, "@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%3B/gi,";").replace(/%20/g,a?"%20":"+")}function Gd(b,a){var c,d,e=lb.length;b=v(b);for(d=0;d<e;++d)if(c=lb[d]+a,J(c=b.attr(c)))return c;return null}function Hd(b,a){var c,d,e={};s(lb,function(a){a+="app";!c&&b.hasAttribute&&b.hasAttribute(a)&&(c=b,d=b.getAttribute(a))});s(lb,function(a){a+="app";var e;!c&&(e=b.querySelector("["+a.replace(":","\\:")+"]"))&&(c=e,d=e.getAttribute(a))});c&&(e.strictDi=null!==Gd(c,"strict-di"), a(c,d?[d]:[],e))}function rc(b,a,c){P(c)||(c={});c=F({strictDi:!1},c);var d=function(){b=v(b);if(b.injector()){var d=b[0]===U?"document":sa(b);throw Wa("btstrpd",d.replace(/</,"&lt;").replace(/>/,"&gt;"));}a=a||[];a.unshift(["$provide",function(a){a.value("$rootElement",b)}]);c.debugInfoEnabled&&a.push(["$compileProvider",function(a){a.debugInfoEnabled(!0)}]);a.unshift("ng");d=Jb(a,c.strictDi);d.invoke(["$rootScope","$rootElement","$compile","$injector",function(a,b,c,d){a.$apply(function(){b.data("$injector", d);c(b)(a)})}]);return d},e=/^NG_ENABLE_DEBUG_INFO!/,f=/^NG_DEFER_BOOTSTRAP!/;N&&e.test(N.name)&&(c.debugInfoEnabled=!0,N.name=N.name.replace(e,""));if(N&&!f.test(N.name))return d();N.name=N.name.replace(f,"");ta.resumeBootstrap=function(b){s(b,function(b){a.push(b)});d()}}function Id(){N.name="NG_ENABLE_DEBUG_INFO!"+N.name;N.location.reload()}function Jd(b){return ta.element(b).injector().get("$$testability")}function Kb(b,a){a=a||"_";return b.replace(Kd,function(b,d){return(d?a:"")+b.toLowerCase()})} function Ld(){var b;sc||((ma=N.jQuery)&&ma.fn.on?(v=ma,F(ma.fn,{scope:Ka.scope,isolateScope:Ka.isolateScope,controller:Ka.controller,injector:Ka.injector,inheritedData:Ka.inheritedData}),b=ma.cleanData,ma.cleanData=function(a){var c;if(Lb)Lb=!1;else for(var d=0,e;null!=(e=a[d]);d++)(c=ma._data(e,"events"))&&c.$destroy&&ma(e).triggerHandler("$destroy");b(a)}):v=Q,ta.element=v,sc=!0)}function Mb(b,a,c){if(!b)throw Wa("areq",a||"?",c||"required");return b}function mb(b,a,c){c&&H(b)&&(b=b[b.length-1]); Mb(A(b),a,"not a function, got "+(b&&"object"===typeof b?b.constructor.name||"Object":typeof b));return b}function La(b,a){if("hasOwnProperty"===b)throw Wa("badname",a);}function tc(b,a,c){if(!a)return b;a=a.split(".");for(var d,e=b,f=a.length,g=0;g<f;g++)d=a[g],b&&(b=(e=b)[d]);return!c&&A(b)?nc(e,b):b}function nb(b){var a=b[0];b=b[b.length-1];var c=[a];do{a=a.nextSibling;if(!a)break;c.push(a)}while(a!==b);return v(c)}function wa(){return Object.create(null)}function Md(b){function a(a,b,c){return a[b]|| (a[b]=c())}var c=w("$injector"),d=w("ng");b=a(b,"angular",Object);b.$$minErr=b.$$minErr||w;return a(b,"module",function(){var b={};return function(f,g,k){if("hasOwnProperty"===f)throw d("badname","module");g&&b.hasOwnProperty(f)&&(b[f]=null);return a(b,f,function(){function a(c,d,e,f){f||(f=b);return function(){f[e||"push"]([c,d,arguments]);return n}}if(!g)throw c("nomod",f);var b=[],d=[],e=[],q=a("$injector","invoke","push",d),n={_invokeQueue:b,_configBlocks:d,_runBlocks:e,requires:g,name:f,provider:a("$provide", "provider"),factory:a("$provide","factory"),service:a("$provide","service"),value:a("$provide","value"),constant:a("$provide","constant","unshift"),animation:a("$animateProvider","register"),filter:a("$filterProvider","register"),controller:a("$controllerProvider","register"),directive:a("$compileProvider","directive"),config:q,run:function(a){e.push(a);return this}};k&&q(k);return n})}})}function Nd(b){F(b,{bootstrap:rc,copy:Ca,extend:F,equals:la,element:v,forEach:s,injector:Jb,noop:y,bind:nc,toJson:ra, fromJson:oc,identity:Sa,isUndefined:x,isDefined:z,isString:J,isFunction:A,isObject:P,isNumber:X,isElement:mc,isArray:H,version:Od,isDate:ea,lowercase:S,uppercase:ob,callbacks:{counter:0},getTestability:Jd,$$minErr:w,$$csp:Ya,reloadWithDebugInfo:Id});Za=Md(N);try{Za("ngLocale")}catch(a){Za("ngLocale",[]).provider("$locale",Pd)}Za("ng",["ngLocale"],["$provide",function(a){a.provider({$$sanitizeUri:Qd});a.provider("$compile",uc).directive({a:Rd,input:vc,textarea:vc,form:Sd,script:Td,select:Ud,style:Vd, option:Wd,ngBind:Xd,ngBindHtml:Yd,ngBindTemplate:Zd,ngClass:$d,ngClassEven:ae,ngClassOdd:be,ngCloak:ce,ngController:de,ngForm:ee,ngHide:fe,ngIf:ge,ngInclude:he,ngInit:ie,ngNonBindable:je,ngPluralize:ke,ngRepeat:le,ngShow:me,ngStyle:ne,ngSwitch:oe,ngSwitchWhen:pe,ngSwitchDefault:qe,ngOptions:re,ngTransclude:se,ngModel:te,ngList:ue,ngChange:ve,pattern:wc,ngPattern:wc,required:xc,ngRequired:xc,minlength:yc,ngMinlength:yc,maxlength:zc,ngMaxlength:zc,ngValue:we,ngModelOptions:xe}).directive({ngInclude:ye}).directive(pb).directive(Ac); a.provider({$anchorScroll:ze,$animate:Ae,$browser:Be,$cacheFactory:Ce,$controller:De,$document:Ee,$exceptionHandler:Fe,$filter:Bc,$interpolate:Ge,$interval:He,$http:Ie,$httpBackend:Je,$location:Ke,$log:Le,$parse:Me,$rootScope:Ne,$q:Oe,$$q:Pe,$sce:Qe,$sceDelegate:Re,$sniffer:Se,$templateCache:Te,$templateRequest:Ue,$$testability:Ve,$timeout:We,$window:Xe,$$rAF:Ye,$$asyncCallback:Ze})}])}function $a(b){return b.replace($e,function(a,b,d,e){return e?d.toUpperCase():d}).replace(af,"Moz$1")}function Cc(b){b= b.nodeType;return b===ka||!b||9===b}function Dc(b,a){var c,d,e=a.createDocumentFragment(),f=[];if(Nb.test(b)){c=c||e.appendChild(a.createElement("div"));d=(bf.exec(b)||["",""])[1].toLowerCase();d=ha[d]||ha._default;c.innerHTML=d[1]+b.replace(cf,"<$1></$2>")+d[2];for(d=d[0];d--;)c=c.lastChild;f=ib(f,c.childNodes);c=e.firstChild;c.textContent=""}else f.push(a.createTextNode(b));e.textContent="";e.innerHTML="";s(f,function(a){e.appendChild(a)});return e}function Q(b){if(b instanceof Q)return b;var a; J(b)&&(b=T(b),a=!0);if(!(this instanceof Q)){if(a&&"<"!=b.charAt(0))throw Ob("nosel");return new Q(b)}if(a){a=U;var c;b=(c=df.exec(b))?[a.createElement(c[1])]:(c=Dc(b,a))?c.childNodes:[]}Ec(this,b)}function Pb(b){return b.cloneNode(!0)}function qb(b,a){a||rb(b);if(b.querySelectorAll)for(var c=b.querySelectorAll("*"),d=0,e=c.length;d<e;d++)rb(c[d])}function Fc(b,a,c,d){if(z(d))throw Ob("offargs");var e=(d=sb(b))&&d.events,f=d&&d.handle;if(f)if(a)s(a.split(" "),function(a){if(z(c)){var d=e[a];Va(d|| [],c);if(d&&0<d.length)return}b.removeEventListener(a,f,!1);delete e[a]});else for(a in e)"$destroy"!==a&&b.removeEventListener(a,f,!1),delete e[a]}function rb(b,a){var c=b.ng339,d=c&&tb[c];d&&(a?delete d.data[a]:(d.handle&&(d.events.$destroy&&d.handle({},"$destroy"),Fc(b)),delete tb[c],b.ng339=t))}function sb(b,a){var c=b.ng339,c=c&&tb[c];a&&!c&&(b.ng339=c=++ef,c=tb[c]={events:{},data:{},handle:t});return c}function Qb(b,a,c){if(Cc(b)){var d=z(c),e=!d&&a&&!P(a),f=!a;b=(b=sb(b,!e))&&b.data;if(d)b[a]= c;else{if(f)return b;if(e)return b&&b[a];F(b,a)}}}function Rb(b,a){return b.getAttribute?-1<(" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ").indexOf(" "+a+" "):!1}function Sb(b,a){a&&b.setAttribute&&s(a.split(" "),function(a){b.setAttribute("class",T((" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ").replace(" "+T(a)+" "," ")))})}function Tb(b,a){if(a&&b.setAttribute){var c=(" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ");s(a.split(" "),function(a){a=T(a);-1=== c.indexOf(" "+a+" ")&&(c+=a+" ")});b.setAttribute("class",T(c))}}function Ec(b,a){if(a)if(a.nodeType)b[b.length++]=a;else{var c=a.length;if("number"===typeof c&&a.window!==a){if(c)for(var d=0;d<c;d++)b[b.length++]=a[d]}else b[b.length++]=a}}function Gc(b,a){return ub(b,"$"+(a||"ngController")+"Controller")}function ub(b,a,c){9==b.nodeType&&(b=b.documentElement);for(a=H(a)?a:[a];b;){for(var d=0,e=a.length;d<e;d++)if((c=v.data(b,a[d]))!==t)return c;b=b.parentNode||11===b.nodeType&&b.host}}function Hc(b){for(qb(b, !0);b.firstChild;)b.removeChild(b.firstChild)}function Ic(b,a){a||qb(b);var c=b.parentNode;c&&c.removeChild(b)}function ff(b,a){a=a||N;if("complete"===a.document.readyState)a.setTimeout(b);else v(a).on("load",b)}function Jc(b,a){var c=vb[a.toLowerCase()];return c&&Kc[pa(b)]&&c}function gf(b,a){var c=b.nodeName;return("INPUT"===c||"TEXTAREA"===c)&&Lc[a]}function hf(b,a){var c=function(c,e){c.isDefaultPrevented=function(){return c.defaultPrevented};var f=a[e||c.type],g=f?f.length:0;if(g){if(x(c.immediatePropagationStopped)){var k= c.stopImmediatePropagation;c.stopImmediatePropagation=function(){c.immediatePropagationStopped=!0;c.stopPropagation&&c.stopPropagation();k&&k.call(c)}}c.isImmediatePropagationStopped=function(){return!0===c.immediatePropagationStopped};1<g&&(f=qa(f));for(var h=0;h<g;h++)c.isImmediatePropagationStopped()||f[h].call(b,c)}};c.elem=b;return c}function Ma(b,a){var c=b&&b.$$hashKey;if(c)return"function"===typeof c&&(c=b.$$hashKey()),c;c=typeof b;return c="function"==c||"object"==c&&null!==b?b.$$hashKey= c+":"+(a||Dd)():c+":"+b}function ab(b,a){if(a){var c=0;this.nextUid=function(){return++c}}s(b,this.put,this)}function jf(b){return(b=b.toString().replace(Mc,"").match(Nc))?"function("+(b[1]||"").replace(/[\s\r\n]+/," ")+")":"fn"}function Ub(b,a,c){var d;if("function"===typeof b){if(!(d=b.$inject)){d=[];if(b.length){if(a)throw J(c)&&c||(c=b.name||jf(b)),Ea("strictdi",c);a=b.toString().replace(Mc,"");a=a.match(Nc);s(a[1].split(kf),function(a){a.replace(lf,function(a,b,c){d.push(c)})})}b.$inject=d}}else H(b)? (a=b.length-1,mb(b[a],"fn"),d=b.slice(0,a)):mb(b,"fn",!0);return d}function Jb(b,a){function c(a){return function(b,c){if(P(b))s(b,jc(a));else return a(b,c)}}function d(a,b){La(a,"service");if(A(b)||H(b))b=q.instantiate(b);if(!b.$get)throw Ea("pget",a);return p[a+"Provider"]=b}function e(a,b){return function(){var c=r.invoke(b,this,t,a);if(x(c))throw Ea("undef",a);return c}}function f(a,b,c){return d(a,{$get:!1!==c?e(a,b):b})}function g(a){var b=[],c;s(a,function(a){function d(a){var b,c;b=0;for(c= a.length;b<c;b++){var e=a[b],f=q.get(e[0]);f[e[1]].apply(f,e[2])}}if(!m.get(a)){m.put(a,!0);try{J(a)?(c=Za(a),b=b.concat(g(c.requires)).concat(c._runBlocks),d(c._invokeQueue),d(c._configBlocks)):A(a)?b.push(q.invoke(a)):H(a)?b.push(q.invoke(a)):mb(a,"module")}catch(e){throw H(a)&&(a=a[a.length-1]),e.message&&e.stack&&-1==e.stack.indexOf(e.message)&&(e=e.message+"\n"+e.stack),Ea("modulerr",a,e.stack||e.message||e);}}});return b}function k(b,c){function d(a){if(b.hasOwnProperty(a)){if(b[a]===h)throw Ea("cdep", a+" <- "+l.join(" <- "));return b[a]}try{return l.unshift(a),b[a]=h,b[a]=c(a)}catch(e){throw b[a]===h&&delete b[a],e;}finally{l.shift()}}function e(b,c,f,g){"string"===typeof f&&(g=f,f=null);var h=[];g=Ub(b,a,g);var k,l,n;l=0;for(k=g.length;l<k;l++){n=g[l];if("string"!==typeof n)throw Ea("itkn",n);h.push(f&&f.hasOwnProperty(n)?f[n]:d(n))}H(b)&&(b=b[k]);return b.apply(c,h)}return{invoke:e,instantiate:function(a,b,c){var d=function(){};d.prototype=(H(a)?a[a.length-1]:a).prototype;d=new d;a=e(a,d,b, c);return P(a)||A(a)?a:d},get:d,annotate:Ub,has:function(a){return p.hasOwnProperty(a+"Provider")||b.hasOwnProperty(a)}}}a=!0===a;var h={},l=[],m=new ab([],!0),p={$provide:{provider:c(d),factory:c(f),service:c(function(a,b){return f(a,["$injector",function(a){return a.instantiate(b)}])}),value:c(function(a,b){return f(a,da(b),!1)}),constant:c(function(a,b){La(a,"constant");p[a]=b;n[a]=b}),decorator:function(a,b){var c=q.get(a+"Provider"),d=c.$get;c.$get=function(){var a=r.invoke(d,c);return r.invoke(b, null,{$delegate:a})}}}},q=p.$injector=k(p,function(){throw Ea("unpr",l.join(" <- "));}),n={},r=n.$injector=k(n,function(a){var b=q.get(a+"Provider");return r.invoke(b.$get,b,t,a)});s(g(b),function(a){r.invoke(a||y)});return r}function ze(){var b=!0;this.disableAutoScrolling=function(){b=!1};this.$get=["$window","$location","$rootScope",function(a,c,d){function e(a){var b=null;Array.prototype.some.call(a,function(a){if("a"===pa(a))return b=a,!0});return b}function f(b){if(b){b.scrollIntoView();var c; c=g.yOffset;A(c)?c=c():mc(c)?(c=c[0],c="fixed"!==a.getComputedStyle(c).position?0:c.getBoundingClientRect().bottom):X(c)||(c=0);c&&(b=b.getBoundingClientRect().top,a.scrollBy(0,b-c))}else a.scrollTo(0,0)}function g(){var a=c.hash(),b;a?(b=k.getElementById(a))?f(b):(b=e(k.getElementsByName(a)))?f(b):"top"===a&&f(null):f(null)}var k=a.document;b&&d.$watch(function(){return c.hash()},function(a,b){a===b&&""===a||ff(function(){d.$evalAsync(g)})});return g}]}function Ze(){this.$get=["$$rAF","$timeout", function(b,a){return b.supported?function(a){return b(a)}:function(b){return a(b,0,!1)}}]}function mf(b,a,c,d){function e(a){try{a.apply(null,Xa.call(arguments,1))}finally{if(C--,0===C)for(;D.length;)try{D.pop()()}catch(b){c.error(b)}}}function f(a,b){(function xa(){s(G,function(a){a()});u=b(xa,a)})()}function g(){k();h()}function k(){I=b.history.state;I=x(I)?null:I;la(I,R)&&(I=R);R=I}function h(){if(E!==m.url()||K!==I)E=m.url(),K=I,s(V,function(a){a(m.url(),I)})}function l(a){try{return decodeURIComponent(a)}catch(b){return a}} var m=this,p=a[0],q=b.location,n=b.history,r=b.setTimeout,O=b.clearTimeout,B={};m.isMock=!1;var C=0,D=[];m.$$completeOutstandingRequest=e;m.$$incOutstandingRequestCount=function(){C++};m.notifyWhenNoOutstandingRequests=function(a){s(G,function(a){a()});0===C?a():D.push(a)};var G=[],u;m.addPollFn=function(a){x(u)&&f(100,r);G.push(a);return a};var I,K,E=q.href,ca=a.find("base"),M=null;k();K=I;m.url=function(a,c,e){x(e)&&(e=null);q!==b.location&&(q=b.location);n!==b.history&&(n=b.history);if(a){var f= K===e;if(E!==a||d.history&&!f){var g=E&&Fa(E)===Fa(a);E=a;K=e;!d.history||g&&f?(g||(M=a),c?q.replace(a):q.href=a):(n[c?"replaceState":"pushState"](e,"",a),k(),K=I);return m}}else return M||q.href.replace(/%27/g,"'")};m.state=function(){return I};var V=[],W=!1,R=null;m.onUrlChange=function(a){if(!W){if(d.history)v(b).on("popstate",g);v(b).on("hashchange",g);W=!0}V.push(a);return a};m.$$checkUrlChange=h;m.baseHref=function(){var a=ca.attr("href");return a?a.replace(/^(https?\:)?\/\/[^\/]*/,""):""}; var ba={},z="",fa=m.baseHref();m.cookies=function(a,b){var d,e,f,g;if(a)b===t?p.cookie=encodeURIComponent(a)+"=;path="+fa+";expires=Thu, 01 Jan 1970 00:00:00 GMT":J(b)&&(d=(p.cookie=encodeURIComponent(a)+"="+encodeURIComponent(b)+";path="+fa).length+1,4096<d&&c.warn("Cookie '"+a+"' possibly not set or overflowed because it was too large ("+d+" > 4096 bytes)!"));else{if(p.cookie!==z)for(z=p.cookie,d=z.split("; "),ba={},f=0;f<d.length;f++)e=d[f],g=e.indexOf("="),0<g&&(a=l(e.substring(0,g)),ba[a]=== t&&(ba[a]=l(e.substring(g+1))));return ba}};m.defer=function(a,b){var c;C++;c=r(function(){delete B[c];e(a)},b||0);B[c]=!0;return c};m.defer.cancel=function(a){return B[a]?(delete B[a],O(a),e(y),!0):!1}}function Be(){this.$get=["$window","$log","$sniffer","$document",function(b,a,c,d){return new mf(b,d,a,c)}]}function Ce(){this.$get=function(){function b(b,d){function e(a){a!=p&&(q?q==a&&(q=a.n):q=a,f(a.n,a.p),f(a,p),p=a,p.n=null)}function f(a,b){a!=b&&(a&&(a.p=b),b&&(b.n=a))}if(b in a)throw w("$cacheFactory")("iid", b);var g=0,k=F({},d,{id:b}),h={},l=d&&d.capacity||Number.MAX_VALUE,m={},p=null,q=null;return a[b]={put:function(a,b){if(l<Number.MAX_VALUE){var c=m[a]||(m[a]={key:a});e(c)}if(!x(b))return a in h||g++,h[a]=b,g>l&&this.remove(q.key),b},get:function(a){if(l<Number.MAX_VALUE){var b=m[a];if(!b)return;e(b)}return h[a]},remove:function(a){if(l<Number.MAX_VALUE){var b=m[a];if(!b)return;b==p&&(p=b.p);b==q&&(q=b.n);f(b.n,b.p);delete m[a]}delete h[a];g--},removeAll:function(){h={};g=0;m={};p=q=null},destroy:function(){m= k=h=null;delete a[b]},info:function(){return F({},k,{size:g})}}}var a={};b.info=function(){var b={};s(a,function(a,e){b[e]=a.info()});return b};b.get=function(b){return a[b]};return b}}function Te(){this.$get=["$cacheFactory",function(b){return b("templates")}]}function uc(b,a){function c(a,b){var c=/^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/,d={};s(a,function(a,e){var f=a.match(c);if(!f)throw ia("iscp",b,e,a);d[e]={mode:f[1][0],collection:"*"===f[2],optional:"?"===f[3],attrName:f[4]||e}});return d}var d= {},e=/^\s*directive\:\s*([\w\-]+)\s+(.*)$/,f=/(([\w\-]+)(?:\:([^;]+))?;?)/,g=Ed("ngSrc,ngSrcset,src,srcset"),k=/^(?:(\^\^?)?(\?)?(\^\^?)?)?/,h=/^(on[a-z]+|formaction)$/;this.directive=function p(a,e){La(a,"directive");J(a)?(Mb(e,"directiveFactory"),d.hasOwnProperty(a)||(d[a]=[],b.factory(a+"Directive",["$injector","$exceptionHandler",function(b,e){var f=[];s(d[a],function(d,g){try{var h=b.invoke(d);A(h)?h={compile:da(h)}:!h.compile&&h.link&&(h.compile=da(h.link));h.priority=h.priority||0;h.index= g;h.name=h.name||a;h.require=h.require||h.controller&&h.name;h.restrict=h.restrict||"EA";P(h.scope)&&(h.$$isolateBindings=c(h.scope,h.name));f.push(h)}catch(k){e(k)}});return f}])),d[a].push(e)):s(a,jc(p));return this};this.aHrefSanitizationWhitelist=function(b){return z(b)?(a.aHrefSanitizationWhitelist(b),this):a.aHrefSanitizationWhitelist()};this.imgSrcSanitizationWhitelist=function(b){return z(b)?(a.imgSrcSanitizationWhitelist(b),this):a.imgSrcSanitizationWhitelist()};var l=!0;this.debugInfoEnabled= function(a){return z(a)?(l=a,this):l};this.$get=["$injector","$interpolate","$exceptionHandler","$templateRequest","$parse","$controller","$rootScope","$document","$sce","$animate","$$sanitizeUri",function(a,b,c,r,O,B,C,D,G,u,I){function K(a,b){try{a.addClass(b)}catch(c){}}function E(a,b,c,d,e){a instanceof v||(a=v(a));s(a,function(b,c){b.nodeType==jb&&b.nodeValue.match(/\S+/)&&(a[c]=v(b).wrap("<span></span>").parent()[0])});var f=ca(a,b,a,c,d,e);E.$$addScopeClass(a);var g=null;return function(b, c,d,e,h){Mb(b,"scope");g||(g=(h=h&&h[0])?"foreignobject"!==pa(h)&&h.toString().match(/SVG/)?"svg":"html":"html");h="html"!==g?v(N(g,v("<div>").append(a).html())):c?Ka.clone.call(a):a;if(d)for(var k in d)h.data("$"+k+"Controller",d[k].instance);E.$$addScopeInfo(h,b);c&&c(h,b);f&&f(b,h,h,e);return h}}function ca(a,b,c,d,e,f){function g(a,c,d,e){var f,k,l,q,n,r,D;if(p)for(D=Array(c.length),q=0;q<h.length;q+=3)f=h[q],D[f]=c[f];else D=c;q=0;for(n=h.length;q<n;)k=D[h[q++]],c=h[q++],f=h[q++],c?(c.scope? (l=a.$new(),E.$$addScopeInfo(v(k),l)):l=a,r=c.transcludeOnThisElement?M(a,c.transclude,e,c.elementTranscludeOnThisElement):!c.templateOnThisElement&&e?e:!e&&b?M(a,b):null,c(f,l,k,d,r)):f&&f(a,k.childNodes,t,e)}for(var h=[],k,l,q,n,p,r=0;r<a.length;r++){k=new X;l=V(a[r],[],k,0===r?d:t,e);(f=l.length?ba(l,a[r],k,b,c,null,[],[],f):null)&&f.scope&&E.$$addScopeClass(k.$$element);k=f&&f.terminal||!(q=a[r].childNodes)||!q.length?null:ca(q,f?(f.transcludeOnThisElement||!f.templateOnThisElement)&&f.transclude: b);if(f||k)h.push(r,f,k),n=!0,p=p||f;f=null}return n?g:null}function M(a,b,c,d){return function(d,e,f,g,h){d||(d=a.$new(!1,h),d.$$transcluded=!0);return b(d,e,f,c,g)}}function V(b,c,g,h,k){var l=g.$attr,q;switch(b.nodeType){case ka:fa(c,ua(pa(b)),"E",h,k);for(var n,r,D,B=b.attributes,O=0,G=B&&B.length;O<G;O++){var I=!1,E=!1;n=B[O];q=n.name;n=T(n.value);r=ua(q);if(D=ya.test(r))q=Kb(r.substr(6),"-");var K=r.replace(/(Start|End)$/,""),u;a:{var C=K;if(d.hasOwnProperty(C)){u=void 0;for(var C=a.get(C+"Directive"), s=0,ca=C.length;s<ca;s++)if(u=C[s],u.multiElement){u=!0;break a}}u=!1}u&&r===K+"Start"&&(I=q,E=q.substr(0,q.length-5)+"end",q=q.substr(0,q.length-6));r=ua(q.toLowerCase());l[r]=q;if(D||!g.hasOwnProperty(r))g[r]=n,Jc(b,r)&&(g[r]=!0);Q(b,c,n,r,D);fa(c,r,"A",h,k,I,E)}b=b.className;if(J(b)&&""!==b)for(;q=f.exec(b);)r=ua(q[2]),fa(c,r,"C",h,k)&&(g[r]=T(q[3])),b=b.substr(q.index+q[0].length);break;case jb:Y(c,b.nodeValue);break;case 8:try{if(q=e.exec(b.nodeValue))r=ua(q[1]),fa(c,r,"M",h,k)&&(g[r]=T(q[2]))}catch(V){}}c.sort(w); return c}function W(a,b,c){var d=[],e=0;if(b&&a.hasAttribute&&a.hasAttribute(b)){do{if(!a)throw ia("uterdir",b,c);a.nodeType==ka&&(a.hasAttribute(b)&&e++,a.hasAttribute(c)&&e--);d.push(a);a=a.nextSibling}while(0<e)}else d.push(a);return v(d)}function R(a,b,c){return function(d,e,f,g,h){e=W(e[0],b,c);return a(d,e,f,g,h)}}function ba(a,d,e,f,g,h,l,r,p){function D(a,b,c,d){if(a){c&&(a=R(a,c,d));a.require=L.require;a.directiveName=ga;if(M===L||L.$$isolateScope)a=Z(a,{isolateScope:!0});l.push(a)}if(b){c&& (b=R(b,c,d));b.require=L.require;b.directiveName=ga;if(M===L||L.$$isolateScope)b=Z(b,{isolateScope:!0});r.push(b)}}function I(a,b,c,d){var e,f="data",g=!1,h=c,l;if(J(b)){l=b.match(k);b=b.substring(l[0].length);l[3]&&(l[1]?l[3]=null:l[1]=l[3]);"^"===l[1]?f="inheritedData":"^^"===l[1]&&(f="inheritedData",h=c.parent());"?"===l[2]&&(g=!0);e=null;d&&"data"===f&&(e=d[b])&&(e=e.instance);e=e||h[f]("$"+b+"Controller");if(!e&&!g)throw ia("ctreq",b,a);return e||null}H(b)&&(e=[],s(b,function(b){e.push(I(a,b, c,d))}));return e}function G(a,c,f,g,h){function k(a,b,c){var d;Ta(a)||(c=b,b=a,a=t);F&&(d=u);c||(c=F?V.parent():V);return h(a,b,d,c,Vb)}var n,p,D,K,u,xb,V,R;d===f?(R=e,V=e.$$element):(V=v(f),R=new X(V,e));M&&(K=c.$new(!0));xb=h&&k;C&&(ca={},u={},s(C,function(a){var b={$scope:a===M||a.$$isolateScope?K:c,$element:V,$attrs:R,$transclude:xb};D=a.controller;"@"==D&&(D=R[a.name]);b=B(D,b,!0,a.controllerAs);u[a.name]=b;F||V.data("$"+a.name+"Controller",b.instance);ca[a.name]=b}));if(M){E.$$addScopeInfo(V, K,!0,!(ba&&(ba===M||ba===M.$$originalDirective)));E.$$addScopeClass(V,!0);g=ca&&ca[M.name];var W=K;g&&g.identifier&&!0===M.bindToController&&(W=g.instance);s(K.$$isolateBindings=M.$$isolateBindings,function(a,d){var e=a.attrName,f=a.optional,g,h,k,l;switch(a.mode){case "@":R.$observe(e,function(a){W[d]=a});R.$$observers[e].$$scope=c;R[e]&&(W[d]=b(R[e])(c));break;case "=":if(f&&!R[e])break;h=O(R[e]);l=h.literal?la:function(a,b){return a===b||a!==a&&b!==b};k=h.assign||function(){g=W[d]=h(c);throw ia("nonassign", R[e],M.name);};g=W[d]=h(c);f=function(a){l(a,W[d])||(l(a,g)?k(c,a=W[d]):W[d]=a);return g=a};f.$stateful=!0;f=a.collection?c.$watchCollection(R[e],f):c.$watch(O(R[e],f),null,h.literal);K.$on("$destroy",f);break;case "&":h=O(R[e]),W[d]=function(a){return h(c,a)}}})}ca&&(s(ca,function(a){a()}),ca=null);g=0;for(n=l.length;g<n;g++)p=l[g],$(p,p.isolateScope?K:c,V,R,p.require&&I(p.directiveName,p.require,V,u),xb);var Vb=c;M&&(M.template||null===M.templateUrl)&&(Vb=K);a&&a(Vb,f.childNodes,t,h);for(g=r.length- 1;0<=g;g--)p=r[g],$(p,p.isolateScope?K:c,V,R,p.require&&I(p.directiveName,p.require,V,u),xb)}p=p||{};for(var K=-Number.MAX_VALUE,u,C=p.controllerDirectives,ca,M=p.newIsolateScopeDirective,ba=p.templateDirective,fa=p.nonTlbTranscludeDirective,y=!1,Na=!1,F=p.hasElementTranscludeDirective,Y=e.$$element=v(d),L,ga,w,Ga=f,S,Q=0,ya=a.length;Q<ya;Q++){L=a[Q];var wb=L.$$start,aa=L.$$end;wb&&(Y=W(d,wb,aa));w=t;if(K>L.priority)break;if(w=L.scope)L.templateUrl||(P(w)?(xa("new/isolated scope",M||u,L,Y),M=L):xa("new/isolated scope", M,L,Y)),u=u||L;ga=L.name;!L.templateUrl&&L.controller&&(w=L.controller,C=C||{},xa("'"+ga+"' controller",C[ga],L,Y),C[ga]=L);if(w=L.transclude)y=!0,L.$$tlb||(xa("transclusion",fa,L,Y),fa=L),"element"==w?(F=!0,K=L.priority,w=Y,Y=e.$$element=v(U.createComment(" "+ga+": "+e[ga]+" ")),d=Y[0],yb(g,Xa.call(w,0),d),Ga=E(w,f,K,h&&h.name,{nonTlbTranscludeDirective:fa})):(w=v(Pb(d)).contents(),Y.empty(),Ga=E(w,f));if(L.template)if(Na=!0,xa("template",ba,L,Y),ba=L,w=A(L.template)?L.template(Y,e):L.template,w= Pc(w),L.replace){h=L;w=Nb.test(w)?Qc(N(L.templateNamespace,T(w))):[];d=w[0];if(1!=w.length||d.nodeType!==ka)throw ia("tplrt",ga,"");yb(g,Y,d);ya={$attr:{}};w=V(d,[],ya);var nf=a.splice(Q+1,a.length-(Q+1));M&&z(w);a=a.concat(w).concat(nf);Oc(e,ya);ya=a.length}else Y.html(w);if(L.templateUrl)Na=!0,xa("template",ba,L,Y),ba=L,L.replace&&(h=L),G=x(a.splice(Q,a.length-Q),Y,e,g,y&&Ga,l,r,{controllerDirectives:C,newIsolateScopeDirective:M,templateDirective:ba,nonTlbTranscludeDirective:fa}),ya=a.length;else if(L.compile)try{S= L.compile(Y,e,Ga),A(S)?D(null,S,wb,aa):S&&D(S.pre,S.post,wb,aa)}catch(da){c(da,sa(Y))}L.terminal&&(G.terminal=!0,K=Math.max(K,L.priority))}G.scope=u&&!0===u.scope;G.transcludeOnThisElement=y;G.elementTranscludeOnThisElement=F;G.templateOnThisElement=Na;G.transclude=Ga;p.hasElementTranscludeDirective=F;return G}function z(a){for(var b=0,c=a.length;b<c;b++)a[b]=lc(a[b],{$$isolateScope:!0})}function fa(b,e,f,g,h,k,l){if(e===h)return null;h=null;if(d.hasOwnProperty(e)){var q;e=a.get(e+"Directive");for(var r= 0,D=e.length;r<D;r++)try{q=e[r],(g===t||g>q.priority)&&-1!=q.restrict.indexOf(f)&&(k&&(q=lc(q,{$$start:k,$$end:l})),b.push(q),h=q)}catch(B){c(B)}}return h}function Oc(a,b){var c=b.$attr,d=a.$attr,e=a.$$element;s(a,function(d,e){"$"!=e.charAt(0)&&(b[e]&&b[e]!==d&&(d+=("style"===e?";":" ")+b[e]),a.$set(e,d,!0,c[e]))});s(b,function(b,f){"class"==f?(K(e,b),a["class"]=(a["class"]?a["class"]+" ":"")+b):"style"==f?(e.attr("style",e.attr("style")+";"+b),a.style=(a.style?a.style+";":"")+b):"$"==f.charAt(0)|| a.hasOwnProperty(f)||(a[f]=b,d[f]=c[f])})}function x(a,b,c,d,e,f,g,h){var k=[],l,q,n=b[0],p=a.shift(),D=F({},p,{templateUrl:null,transclude:null,replace:null,$$originalDirective:p}),B=A(p.templateUrl)?p.templateUrl(b,c):p.templateUrl,O=p.templateNamespace;b.empty();r(G.getTrustedResourceUrl(B)).then(function(r){var G,I;r=Pc(r);if(p.replace){r=Nb.test(r)?Qc(N(O,T(r))):[];G=r[0];if(1!=r.length||G.nodeType!==ka)throw ia("tplrt",p.name,B);r={$attr:{}};yb(d,b,G);var u=V(G,[],r);P(p.scope)&&z(u);a=u.concat(a); Oc(c,r)}else G=n,b.html(r);a.unshift(D);l=ba(a,G,c,e,b,p,f,g,h);s(d,function(a,c){a==G&&(d[c]=b[0])});for(q=ca(b[0].childNodes,e);k.length;){r=k.shift();I=k.shift();var E=k.shift(),C=k.shift(),u=b[0];if(!r.$$destroyed){if(I!==n){var R=I.className;h.hasElementTranscludeDirective&&p.replace||(u=Pb(G));yb(E,v(I),u);K(v(u),R)}I=l.transcludeOnThisElement?M(r,l.transclude,C):C;l(q,r,u,d,I)}}k=null});return function(a,b,c,d,e){a=e;b.$$destroyed||(k?(k.push(b),k.push(c),k.push(d),k.push(a)):(l.transcludeOnThisElement&& (a=M(b,l.transclude,e)),l(q,b,c,d,a)))}}function w(a,b){var c=b.priority-a.priority;return 0!==c?c:a.name!==b.name?a.name<b.name?-1:1:a.index-b.index}function xa(a,b,c,d){if(b)throw ia("multidir",b.name,c.name,a,sa(d));}function Y(a,c){var d=b(c,!0);d&&a.push({priority:0,compile:function(a){a=a.parent();var b=!!a.length;b&&E.$$addBindingClass(a);return function(a,c){var e=c.parent();b||E.$$addBindingClass(e);E.$$addBindingInfo(e,d.expressions);a.$watch(d,function(a){c[0].nodeValue=a})}}})}function N(a, b){a=S(a||"html");switch(a){case "svg":case "math":var c=U.createElement("div");c.innerHTML="<"+a+">"+b+"</"+a+">";return c.childNodes[0].childNodes;default:return b}}function Ga(a,b){if("srcdoc"==b)return G.HTML;var c=pa(a);if("xlinkHref"==b||"form"==c&&"action"==b||"img"!=c&&("src"==b||"ngSrc"==b))return G.RESOURCE_URL}function Q(a,c,d,e,f){var k=b(d,!0);if(k){if("multiple"===e&&"select"===pa(a))throw ia("selmulti",sa(a));c.push({priority:100,compile:function(){return{pre:function(c,d,l){d=l.$$observers|| (l.$$observers={});if(h.test(e))throw ia("nodomevents");l[e]&&(k=b(l[e],!0,Ga(a,e),g[e]||f))&&(l[e]=k(c),(d[e]||(d[e]=[])).$$inter=!0,(l.$$observers&&l.$$observers[e].$$scope||c).$watch(k,function(a,b){"class"===e&&a!=b?l.$updateClass(a,b):l.$set(e,a)}))}}}})}}function yb(a,b,c){var d=b[0],e=b.length,f=d.parentNode,g,h;if(a)for(g=0,h=a.length;g<h;g++)if(a[g]==d){a[g++]=c;h=g+e-1;for(var k=a.length;g<k;g++,h++)h<k?a[g]=a[h]:delete a[g];a.length-=e-1;a.context===d&&(a.context=c);break}f&&f.replaceChild(c, d);a=U.createDocumentFragment();a.appendChild(d);v(c).data(v(d).data());ma?(Lb=!0,ma.cleanData([d])):delete v.cache[d[v.expando]];d=1;for(e=b.length;d<e;d++)f=b[d],v(f).remove(),a.appendChild(f),delete b[d];b[0]=c;b.length=1}function Z(a,b){return F(function(){return a.apply(null,arguments)},a,b)}function $(a,b,d,e,f,g){try{a(b,d,e,f,g)}catch(h){c(h,sa(d))}}var X=function(a,b){if(b){var c=Object.keys(b),d,e,f;d=0;for(e=c.length;d<e;d++)f=c[d],this[f]=b[f]}else this.$attr={};this.$$element=a};X.prototype= {$normalize:ua,$addClass:function(a){a&&0<a.length&&u.addClass(this.$$element,a)},$removeClass:function(a){a&&0<a.length&&u.removeClass(this.$$element,a)},$updateClass:function(a,b){var c=Rc(a,b);c&&c.length&&u.addClass(this.$$element,c);(c=Rc(b,a))&&c.length&&u.removeClass(this.$$element,c)},$set:function(a,b,d,e){var f=this.$$element[0],g=Jc(f,a),h=gf(f,a),f=a;g?(this.$$element.prop(a,b),e=g):h&&(this[h]=b,f=h);this[a]=b;e?this.$attr[a]=e:(e=this.$attr[a])||(this.$attr[a]=e=Kb(a,"-"));g=pa(this.$$element); if("a"===g&&"href"===a||"img"===g&&"src"===a)this[a]=b=I(b,"src"===a);else if("img"===g&&"srcset"===a){for(var g="",h=T(b),k=/(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/,k=/\s/.test(h)?k:/(,)/,h=h.split(k),k=Math.floor(h.length/2),l=0;l<k;l++)var q=2*l,g=g+I(T(h[q]),!0),g=g+(" "+T(h[q+1]));h=T(h[2*l]).split(/\s/);g+=I(T(h[0]),!0);2===h.length&&(g+=" "+T(h[1]));this[a]=b=g}!1!==d&&(null===b||b===t?this.$$element.removeAttr(e):this.$$element.attr(e,b));(a=this.$$observers)&&s(a[f],function(a){try{a(b)}catch(d){c(d)}})}, $observe:function(a,b){var c=this,d=c.$$observers||(c.$$observers=wa()),e=d[a]||(d[a]=[]);e.push(b);C.$evalAsync(function(){!e.$$inter&&c.hasOwnProperty(a)&&b(c[a])});return function(){Va(e,b)}}};var Na=b.startSymbol(),ga=b.endSymbol(),Pc="{{"==Na||"}}"==ga?Sa:function(a){return a.replace(/\{\{/g,Na).replace(/}}/g,ga)},ya=/^ngAttr[A-Z]/;E.$$addBindingInfo=l?function(a,b){var c=a.data("$binding")||[];H(b)?c=c.concat(b):c.push(b);a.data("$binding",c)}:y;E.$$addBindingClass=l?function(a){K(a,"ng-binding")}: y;E.$$addScopeInfo=l?function(a,b,c,d){a.data(c?d?"$isolateScopeNoTemplate":"$isolateScope":"$scope",b)}:y;E.$$addScopeClass=l?function(a,b){K(a,b?"ng-isolate-scope":"ng-scope")}:y;return E}]}function ua(b){return $a(b.replace(of,""))}function Rc(b,a){var c="",d=b.split(/\s+/),e=a.split(/\s+/),f=0;a:for(;f<d.length;f++){for(var g=d[f],k=0;k<e.length;k++)if(g==e[k])continue a;c+=(0<c.length?" ":"")+g}return c}function Qc(b){b=v(b);var a=b.length;if(1>=a)return b;for(;a--;)8===b[a].nodeType&&pf.call(b, a,1);return b}function De(){var b={},a=!1,c=/^(\S+)(\s+as\s+(\w+))?$/;this.register=function(a,c){La(a,"controller");P(a)?F(b,a):b[a]=c};this.allowGlobals=function(){a=!0};this.$get=["$injector","$window",function(d,e){function f(a,b,c,d){if(!a||!P(a.$scope))throw w("$controller")("noscp",d,b);a.$scope[b]=c}return function(g,k,h,l){var m,p,q;h=!0===h;l&&J(l)&&(q=l);J(g)&&(l=g.match(c),p=l[1],q=q||l[3],g=b.hasOwnProperty(p)?b[p]:tc(k.$scope,p,!0)||(a?tc(e,p,!0):t),mb(g,p,!0));if(h)return h=function(){}, h.prototype=(H(g)?g[g.length-1]:g).prototype,m=new h,q&&f(k,q,m,p||g.name),F(function(){d.invoke(g,m,k,p);return m},{instance:m,identifier:q});m=d.instantiate(g,k,p);q&&f(k,q,m,p||g.name);return m}}]}function Ee(){this.$get=["$window",function(b){return v(b.document)}]}function Fe(){this.$get=["$log",function(b){return function(a,c){b.error.apply(b,arguments)}}]}function Wb(b,a){if(J(b)){b=b.replace(qf,"");var c=a("Content-Type");if(c&&0===c.indexOf(Sc)||rf.test(b)&&sf.test(b))b=oc(b)}return b}function Tc(b){var a= {},c,d,e;if(!b)return a;s(b.split("\n"),function(b){e=b.indexOf(":");c=S(T(b.substr(0,e)));d=T(b.substr(e+1));c&&(a[c]=a[c]?a[c]+", "+d:d)});return a}function Uc(b){var a=P(b)?b:t;return function(c){a||(a=Tc(b));return c?a[S(c)]||null:a}}function Vc(b,a,c){if(A(c))return c(b,a);s(c,function(c){b=c(b,a)});return b}function Ie(){var b=this.defaults={transformResponse:[Wb],transformRequest:[function(a){return P(a)&&"[object File]"!==Ja.call(a)&&"[object Blob]"!==Ja.call(a)?ra(a):a}],headers:{common:{Accept:"application/json, text/plain, */*"}, post:qa(Xb),put:qa(Xb),patch:qa(Xb)},xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN"},a=!1;this.useApplyAsync=function(b){return z(b)?(a=!!b,this):a};var c=this.interceptors=[];this.$get=["$httpBackend","$browser","$cacheFactory","$rootScope","$q","$injector",function(d,e,f,g,k,h){function l(a){function c(a){var b=F({},a);b.data=a.data?Vc(a.data,a.headers,d.transformResponse):a.data;a=a.status;return 200<=a&&300>a?b:k.reject(b)}var d={method:"get",transformRequest:b.transformRequest,transformResponse:b.transformResponse}, e=function(a){var c=b.headers,d=F({},a.headers),e,f,c=F({},c.common,c[S(a.method)]);a:for(e in c){a=S(e);for(f in d)if(S(f)===a)continue a;d[e]=c[e]}(function(a){var b;s(a,function(c,d){A(c)&&(b=c(),null!=b?a[d]=b:delete a[d])})})(d);return d}(a);F(d,a);d.headers=e;d.method=ob(d.method);var f=[function(a){e=a.headers;var d=Vc(a.data,Uc(e),a.transformRequest);x(d)&&s(e,function(a,b){"content-type"===S(b)&&delete e[b]});x(a.withCredentials)&&!x(b.withCredentials)&&(a.withCredentials=b.withCredentials); return m(a,d,e).then(c,c)},t],g=k.when(d);for(s(n,function(a){(a.request||a.requestError)&&f.unshift(a.request,a.requestError);(a.response||a.responseError)&&f.push(a.response,a.responseError)});f.length;){a=f.shift();var h=f.shift(),g=g.then(a,h)}g.success=function(a){g.then(function(b){a(b.data,b.status,b.headers,d)});return g};g.error=function(a){g.then(null,function(b){a(b.data,b.status,b.headers,d)});return g};return g}function m(c,f,h){function n(b,c,d,e){function f(){m(c,b,d,e)}K&&(200<=b&& 300>b?K.put(s,[b,c,Tc(d),e]):K.remove(s));a?g.$applyAsync(f):(f(),g.$$phase||g.$apply())}function m(a,b,d,e){b=Math.max(b,0);(200<=b&&300>b?u.resolve:u.reject)({data:a,status:b,headers:Uc(d),config:c,statusText:e})}function G(){var a=l.pendingRequests.indexOf(c);-1!==a&&l.pendingRequests.splice(a,1)}var u=k.defer(),I=u.promise,K,E,s=p(c.url,c.params);l.pendingRequests.push(c);I.then(G,G);!c.cache&&!b.cache||!1===c.cache||"GET"!==c.method&&"JSONP"!==c.method||(K=P(c.cache)?c.cache:P(b.cache)?b.cache: q);if(K)if(E=K.get(s),z(E)){if(E&&A(E.then))return E.then(G,G),E;H(E)?m(E[1],E[0],qa(E[2]),E[3]):m(E,200,{},"OK")}else K.put(s,I);x(E)&&((E=Wc(c.url)?e.cookies()[c.xsrfCookieName||b.xsrfCookieName]:t)&&(h[c.xsrfHeaderName||b.xsrfHeaderName]=E),d(c.method,s,f,n,h,c.timeout,c.withCredentials,c.responseType));return I}function p(a,b){if(!b)return a;var c=[];Cd(b,function(a,b){null===a||x(a)||(H(a)||(a=[a]),s(a,function(a){P(a)&&(a=ea(a)?a.toISOString():ra(a));c.push(Da(b)+"="+Da(a))}))});0<c.length&& (a+=(-1==a.indexOf("?")?"?":"&")+c.join("&"));return a}var q=f("$http"),n=[];s(c,function(a){n.unshift(J(a)?h.get(a):h.invoke(a))});l.pendingRequests=[];(function(a){s(arguments,function(a){l[a]=function(b,c){return l(F(c||{},{method:a,url:b}))}})})("get","delete","head","jsonp");(function(a){s(arguments,function(a){l[a]=function(b,c,d){return l(F(d||{},{method:a,url:b,data:c}))}})})("post","put","patch");l.defaults=b;return l}]}function tf(){return new N.XMLHttpRequest}function Je(){this.$get=["$browser", "$window","$document",function(b,a,c){return uf(b,tf,b.defer,a.angular.callbacks,c[0])}]}function uf(b,a,c,d,e){function f(a,b,c){var f=e.createElement("script"),m=null;f.type="text/javascript";f.src=a;f.async=!0;m=function(a){f.removeEventListener("load",m,!1);f.removeEventListener("error",m,!1);e.body.removeChild(f);f=null;var g=-1,n="unknown";a&&("load"!==a.type||d[b].called||(a={type:"error"}),n=a.type,g="error"===a.type?404:200);c&&c(g,n)};f.addEventListener("load",m,!1);f.addEventListener("error", m,!1);e.body.appendChild(f);return m}return function(e,k,h,l,m,p,q,n){function r(){C&&C();D&&D.abort()}function O(a,d,e,f,g){u&&c.cancel(u);C=D=null;a(d,e,f,g);b.$$completeOutstandingRequest(y)}b.$$incOutstandingRequestCount();k=k||b.url();if("jsonp"==S(e)){var B="_"+(d.counter++).toString(36);d[B]=function(a){d[B].data=a;d[B].called=!0};var C=f(k.replace("JSON_CALLBACK","angular.callbacks."+B),B,function(a,b){O(l,a,d[B].data,"",b);d[B]=y})}else{var D=a();D.open(e,k,!0);s(m,function(a,b){z(a)&&D.setRequestHeader(b, a)});D.onload=function(){var a=D.statusText||"",b="response"in D?D.response:D.responseText,c=1223===D.status?204:D.status;0===c&&(c=b?200:"file"==za(k).protocol?404:0);O(l,c,b,D.getAllResponseHeaders(),a)};e=function(){O(l,-1,null,null,"")};D.onerror=e;D.onabort=e;q&&(D.withCredentials=!0);if(n)try{D.responseType=n}catch(G){if("json"!==n)throw G;}D.send(h||null)}if(0<p)var u=c(r,p);else p&&A(p.then)&&p.then(r)}}function Ge(){var b="{{",a="}}";this.startSymbol=function(a){return a?(b=a,this):b};this.endSymbol= function(b){return b?(a=b,this):a};this.$get=["$parse","$exceptionHandler","$sce",function(c,d,e){function f(a){return"\\\\\\"+a}function g(f,g,n,r){function O(c){return c.replace(l,b).replace(m,a)}function B(a){try{var b;var c=n?e.getTrusted(n,a):e.valueOf(a);if(null==c)b="";else{switch(typeof c){case "string":break;case "number":c=""+c;break;default:c=ra(c)}b=c}return b}catch(g){a=Yb("interr",f,g.toString()),d(a)}}r=!!r;for(var C,D,G=0,u=[],I=[],K=f.length,E=[],s=[];G<K;)if(-1!=(C=f.indexOf(b,G))&& -1!=(D=f.indexOf(a,C+k)))G!==C&&E.push(O(f.substring(G,C))),G=f.substring(C+k,D),u.push(G),I.push(c(G,B)),G=D+h,s.push(E.length),E.push("");else{G!==K&&E.push(O(f.substring(G)));break}if(n&&1<E.length)throw Yb("noconcat",f);if(!g||u.length){var M=function(a){for(var b=0,c=u.length;b<c;b++){if(r&&x(a[b]))return;E[s[b]]=a[b]}return E.join("")};return F(function(a){var b=0,c=u.length,e=Array(c);try{for(;b<c;b++)e[b]=I[b](a);return M(e)}catch(g){a=Yb("interr",f,g.toString()),d(a)}},{exp:f,expressions:u, $$watchDelegate:function(a,b,c){var d;return a.$watchGroup(I,function(c,e){var f=M(c);A(b)&&b.call(this,f,c!==e?d:f,a);d=f},c)}})}}var k=b.length,h=a.length,l=new RegExp(b.replace(/./g,f),"g"),m=new RegExp(a.replace(/./g,f),"g");g.startSymbol=function(){return b};g.endSymbol=function(){return a};return g}]}function He(){this.$get=["$rootScope","$window","$q","$$q",function(b,a,c,d){function e(e,k,h,l){var m=a.setInterval,p=a.clearInterval,q=0,n=z(l)&&!l,r=(n?d:c).defer(),O=r.promise;h=z(h)?h:0;O.then(null, null,e);O.$$intervalId=m(function(){r.notify(q++);0<h&&q>=h&&(r.resolve(q),p(O.$$intervalId),delete f[O.$$intervalId]);n||b.$apply()},k);f[O.$$intervalId]=r;return O}var f={};e.cancel=function(b){return b&&b.$$intervalId in f?(f[b.$$intervalId].reject("canceled"),a.clearInterval(b.$$intervalId),delete f[b.$$intervalId],!0):!1};return e}]}function Pd(){this.$get=function(){return{id:"en-us",NUMBER_FORMATS:{DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{minInt:1,minFrac:0,maxFrac:3,posPre:"",posSuf:"",negPre:"-", negSuf:"",gSize:3,lgSize:3},{minInt:1,minFrac:2,maxFrac:2,posPre:"\u00a4",posSuf:"",negPre:"(\u00a4",negSuf:")",gSize:3,lgSize:3}],CURRENCY_SYM:"$"},DATETIME_FORMATS:{MONTH:"January February March April May June July August September October November December".split(" "),SHORTMONTH:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),DAY:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),SHORTDAY:"Sun Mon Tue Wed Thu Fri Sat".split(" "),AMPMS:["AM","PM"],medium:"MMM d, y h:mm:ss a", "short":"M/d/yy h:mm a",fullDate:"EEEE, MMMM d, y",longDate:"MMMM d, y",mediumDate:"MMM d, y",shortDate:"M/d/yy",mediumTime:"h:mm:ss a",shortTime:"h:mm a"},pluralCat:function(b){return 1===b?"one":"other"}}}}function Zb(b){b=b.split("/");for(var a=b.length;a--;)b[a]=kb(b[a]);return b.join("/")}function Xc(b,a,c){b=za(b,c);a.$$protocol=b.protocol;a.$$host=b.hostname;a.$$port=aa(b.port)||vf[b.protocol]||null}function Yc(b,a,c){var d="/"!==b.charAt(0);d&&(b="/"+b);b=za(b,c);a.$$path=decodeURIComponent(d&& "/"===b.pathname.charAt(0)?b.pathname.substring(1):b.pathname);a.$$search=qc(b.search);a.$$hash=decodeURIComponent(b.hash);a.$$path&&"/"!=a.$$path.charAt(0)&&(a.$$path="/"+a.$$path)}function va(b,a){if(0===a.indexOf(b))return a.substr(b.length)}function Fa(b){var a=b.indexOf("#");return-1==a?b:b.substr(0,a)}function $b(b){return b.substr(0,Fa(b).lastIndexOf("/")+1)}function ac(b,a){this.$$html5=!0;a=a||"";var c=$b(b);Xc(b,this,b);this.$$parse=function(a){var e=va(c,a);if(!J(e))throw bb("ipthprfx", a,c);Yc(e,this,b);this.$$path||(this.$$path="/");this.$$compose()};this.$$compose=function(){var a=Ib(this.$$search),b=this.$$hash?"#"+kb(this.$$hash):"";this.$$url=Zb(this.$$path)+(a?"?"+a:"")+b;this.$$absUrl=c+this.$$url.substr(1)};this.$$parseLinkUrl=function(d,e){if(e&&"#"===e[0])return this.hash(e.slice(1)),!0;var f,g;(f=va(b,d))!==t?(g=f,g=(f=va(a,f))!==t?c+(va("/",f)||f):b+g):(f=va(c,d))!==t?g=c+f:c==d+"/"&&(g=c);g&&this.$$parse(g);return!!g}}function bc(b,a){var c=$b(b);Xc(b,this,b);this.$$parse= function(d){var e=va(b,d)||va(c,d),e="#"==e.charAt(0)?va(a,e):this.$$html5?e:"";if(!J(e))throw bb("ihshprfx",d,a);Yc(e,this,b);d=this.$$path;var f=/^\/[A-Z]:(\/.*)/;0===e.indexOf(b)&&(e=e.replace(b,""));f.exec(e)||(d=(e=f.exec(d))?e[1]:d);this.$$path=d;this.$$compose()};this.$$compose=function(){var c=Ib(this.$$search),e=this.$$hash?"#"+kb(this.$$hash):"";this.$$url=Zb(this.$$path)+(c?"?"+c:"")+e;this.$$absUrl=b+(this.$$url?a+this.$$url:"")};this.$$parseLinkUrl=function(a,c){return Fa(b)==Fa(a)?(this.$$parse(a), !0):!1}}function Zc(b,a){this.$$html5=!0;bc.apply(this,arguments);var c=$b(b);this.$$parseLinkUrl=function(d,e){if(e&&"#"===e[0])return this.hash(e.slice(1)),!0;var f,g;b==Fa(d)?f=d:(g=va(c,d))?f=b+a+g:c===d+"/"&&(f=c);f&&this.$$parse(f);return!!f};this.$$compose=function(){var c=Ib(this.$$search),e=this.$$hash?"#"+kb(this.$$hash):"";this.$$url=Zb(this.$$path)+(c?"?"+c:"")+e;this.$$absUrl=b+a+this.$$url}}function zb(b){return function(){return this[b]}}function $c(b,a){return function(c){if(x(c))return this[b]; this[b]=a(c);this.$$compose();return this}}function Ke(){var b="",a={enabled:!1,requireBase:!0,rewriteLinks:!0};this.hashPrefix=function(a){return z(a)?(b=a,this):b};this.html5Mode=function(b){return Ua(b)?(a.enabled=b,this):P(b)?(Ua(b.enabled)&&(a.enabled=b.enabled),Ua(b.requireBase)&&(a.requireBase=b.requireBase),Ua(b.rewriteLinks)&&(a.rewriteLinks=b.rewriteLinks),this):a};this.$get=["$rootScope","$browser","$sniffer","$rootElement",function(c,d,e,f){function g(a,b,c){var e=h.url(),f=h.$$state; try{d.url(a,b,c),h.$$state=d.state()}catch(g){throw h.url(e),h.$$state=f,g;}}function k(a,b){c.$broadcast("$locationChangeSuccess",h.absUrl(),a,h.$$state,b)}var h,l;l=d.baseHref();var m=d.url(),p;if(a.enabled){if(!l&&a.requireBase)throw bb("nobase");p=m.substring(0,m.indexOf("/",m.indexOf("//")+2))+(l||"/");l=e.history?ac:Zc}else p=Fa(m),l=bc;h=new l(p,"#"+b);h.$$parseLinkUrl(m,m);h.$$state=d.state();var q=/^\s*(javascript|mailto):/i;f.on("click",function(b){if(a.rewriteLinks&&!b.ctrlKey&&!b.metaKey&& 2!=b.which){for(var e=v(b.target);"a"!==pa(e[0]);)if(e[0]===f[0]||!(e=e.parent())[0])return;var g=e.prop("href"),k=e.attr("href")||e.attr("xlink:href");P(g)&&"[object SVGAnimatedString]"===g.toString()&&(g=za(g.animVal).href);q.test(g)||!g||e.attr("target")||b.isDefaultPrevented()||!h.$$parseLinkUrl(g,k)||(b.preventDefault(),h.absUrl()!=d.url()&&(c.$apply(),N.angular["ff-684208-preventDefault"]=!0))}});h.absUrl()!=m&&d.url(h.absUrl(),!0);var n=!0;d.onUrlChange(function(a,b){c.$evalAsync(function(){var d= h.absUrl(),e=h.$$state;h.$$parse(a);h.$$state=b;c.$broadcast("$locationChangeStart",a,d,b,e).defaultPrevented?(h.$$parse(d),h.$$state=e,g(d,!1,e)):(n=!1,k(d,e))});c.$$phase||c.$digest()});c.$watch(function(){var a=d.url(),b=d.state(),f=h.$$replace,l=a!==h.absUrl()||h.$$html5&&e.history&&b!==h.$$state;if(n||l)n=!1,c.$evalAsync(function(){c.$broadcast("$locationChangeStart",h.absUrl(),a,h.$$state,b).defaultPrevented?(h.$$parse(a),h.$$state=b):(l&&g(h.absUrl(),f,b===h.$$state?null:h.$$state),k(a,b))}); h.$$replace=!1});return h}]}function Le(){var b=!0,a=this;this.debugEnabled=function(a){return z(a)?(b=a,this):b};this.$get=["$window",function(c){function d(a){a instanceof Error&&(a.stack?a=a.message&&-1===a.stack.indexOf(a.message)?"Error: "+a.message+"\n"+a.stack:a.stack:a.sourceURL&&(a=a.message+"\n"+a.sourceURL+":"+a.line));return a}function e(a){var b=c.console||{},e=b[a]||b.log||y;a=!1;try{a=!!e.apply}catch(h){}return a?function(){var a=[];s(arguments,function(b){a.push(d(b))});return e.apply(b, a)}:function(a,b){e(a,null==b?"":b)}}return{log:e("log"),info:e("info"),warn:e("warn"),error:e("error"),debug:function(){var c=e("debug");return function(){b&&c.apply(a,arguments)}}()}}]}function na(b,a){if("__defineGetter__"===b||"__defineSetter__"===b||"__lookupGetter__"===b||"__lookupSetter__"===b||"__proto__"===b)throw oa("isecfld",a);return b}function Aa(b,a){if(b){if(b.constructor===b)throw oa("isecfn",a);if(b.window===b)throw oa("isecwindow",a);if(b.children&&(b.nodeName||b.prop&&b.attr&&b.find))throw oa("isecdom", a);if(b===Object)throw oa("isecobj",a);}return b}function cc(b){return b.constant}function Oa(b,a,c,d){Aa(b,d);a=a.split(".");for(var e,f=0;1<a.length;f++){e=na(a.shift(),d);var g=Aa(b[e],d);g||(g={},b[e]=g);b=g}e=na(a.shift(),d);Aa(b[e],d);return b[e]=c}function ad(b,a,c,d,e,f){na(b,f);na(a,f);na(c,f);na(d,f);na(e,f);return function(f,k){var h=k&&k.hasOwnProperty(b)?k:f;if(null==h)return h;h=h[b];if(!a)return h;if(null==h)return t;h=h[a];if(!c)return h;if(null==h)return t;h=h[c];if(!d)return h;if(null== h)return t;h=h[d];return e?null==h?t:h=h[e]:h}}function bd(b,a,c){var d=cd[b];if(d)return d;var e=b.split("."),f=e.length;if(a.csp)d=6>f?ad(e[0],e[1],e[2],e[3],e[4],c):function(a,b){var d=0,g;do g=ad(e[d++],e[d++],e[d++],e[d++],e[d++],c)(a,b),b=t,a=g;while(d<f);return g};else{var g="";s(e,function(a,b){na(a,c);g+="if(s == null) return undefined;\ns="+(b?"s":'((l&&l.hasOwnProperty("'+a+'"))?l:s)')+"."+a+";\n"});g+="return s;";a=new Function("s","l",g);a.toString=da(g);d=a}d.sharedGetter=!0;d.assign= function(a,c){return Oa(a,b,c,b)};return cd[b]=d}function dc(b){return A(b.valueOf)?b.valueOf():wf.call(b)}function Me(){var b=wa(),a={csp:!1};this.$get=["$filter","$sniffer",function(c,d){function e(a){var b=a;a.sharedGetter&&(b=function(b,c){return a(b,c)},b.literal=a.literal,b.constant=a.constant,b.assign=a.assign);return b}function f(a,b){for(var c=0,d=a.length;c<d;c++){var e=a[c];e.constant||(e.inputs?f(e.inputs,b):-1===b.indexOf(e)&&b.push(e))}return b}function g(a,b){return null==a||null== b?a===b:"object"===typeof a&&(a=dc(a),"object"===typeof a)?!1:a===b||a!==a&&b!==b}function k(a,b,c,d){var e=d.$$inputs||(d.$$inputs=f(d.inputs,[])),h;if(1===e.length){var k=g,e=e[0];return a.$watch(function(a){var b=e(a);g(b,k)||(h=d(a),k=b&&dc(b));return h},b,c)}for(var l=[],m=0,p=e.length;m<p;m++)l[m]=g;return a.$watch(function(a){for(var b=!1,c=0,f=e.length;c<f;c++){var k=e[c](a);if(b||(b=!g(k,l[c])))l[c]=k&&dc(k)}b&&(h=d(a));return h},b,c)}function h(a,b,c,d){var e,f;return e=a.$watch(function(a){return d(a)}, function(a,c,d){f=a;A(b)&&b.apply(this,arguments);z(a)&&d.$$postDigest(function(){z(f)&&e()})},c)}function l(a,b,c,d){function e(a){var b=!0;s(a,function(a){z(a)||(b=!1)});return b}var f,g;return f=a.$watch(function(a){return d(a)},function(a,c,d){g=a;A(b)&&b.call(this,a,c,d);e(a)&&d.$$postDigest(function(){e(g)&&f()})},c)}function m(a,b,c,d){var e;return e=a.$watch(function(a){return d(a)},function(a,c,d){A(b)&&b.apply(this,arguments);e()},c)}function p(a,b){if(!b)return a;var c=function(c,d){var e= a(c,d),f=b(e,c,d);return z(e)?f:e};a.$$watchDelegate&&a.$$watchDelegate!==k?c.$$watchDelegate=a.$$watchDelegate:b.$stateful||(c.$$watchDelegate=k,c.inputs=[a]);return c}a.csp=d.csp;return function(d,f){var g,O,B;switch(typeof d){case "string":return B=d=d.trim(),g=b[B],g||(":"===d.charAt(0)&&":"===d.charAt(1)&&(O=!0,d=d.substring(2)),g=new ec(a),g=(new cb(g,c,a)).parse(d),g.constant?g.$$watchDelegate=m:O?(g=e(g),g.$$watchDelegate=g.literal?l:h):g.inputs&&(g.$$watchDelegate=k),b[B]=g),p(g,f);case "function":return p(d, f);default:return p(y,f)}}}]}function Oe(){this.$get=["$rootScope","$exceptionHandler",function(b,a){return dd(function(a){b.$evalAsync(a)},a)}]}function Pe(){this.$get=["$browser","$exceptionHandler",function(b,a){return dd(function(a){b.defer(a)},a)}]}function dd(b,a){function c(a,b,c){function d(b){return function(c){e||(e=!0,b.call(a,c))}}var e=!1;return[d(b),d(c)]}function d(){this.$$state={status:0}}function e(a,b){return function(c){b.call(a,c)}}function f(c){!c.processScheduled&&c.pending&& (c.processScheduled=!0,b(function(){var b,d,e;e=c.pending;c.processScheduled=!1;c.pending=t;for(var f=0,g=e.length;f<g;++f){d=e[f][0];b=e[f][c.status];try{A(b)?d.resolve(b(c.value)):1===c.status?d.resolve(c.value):d.reject(c.value)}catch(h){d.reject(h),a(h)}}}))}function g(){this.promise=new d;this.resolve=e(this,this.resolve);this.reject=e(this,this.reject);this.notify=e(this,this.notify)}var k=w("$q",TypeError);d.prototype={then:function(a,b,c){var d=new g;this.$$state.pending=this.$$state.pending|| [];this.$$state.pending.push([d,a,b,c]);0<this.$$state.status&&f(this.$$state);return d.promise},"catch":function(a){return this.then(null,a)},"finally":function(a,b){return this.then(function(b){return l(b,!0,a)},function(b){return l(b,!1,a)},b)}};g.prototype={resolve:function(a){this.promise.$$state.status||(a===this.promise?this.$$reject(k("qcycle",a)):this.$$resolve(a))},$$resolve:function(b){var d,e;e=c(this,this.$$resolve,this.$$reject);try{if(P(b)||A(b))d=b&&b.then;A(d)?(this.promise.$$state.status= -1,d.call(b,e[0],e[1],this.notify)):(this.promise.$$state.value=b,this.promise.$$state.status=1,f(this.promise.$$state))}catch(g){e[1](g),a(g)}},reject:function(a){this.promise.$$state.status||this.$$reject(a)},$$reject:function(a){this.promise.$$state.value=a;this.promise.$$state.status=2;f(this.promise.$$state)},notify:function(c){var d=this.promise.$$state.pending;0>=this.promise.$$state.status&&d&&d.length&&b(function(){for(var b,e,f=0,g=d.length;f<g;f++){e=d[f][0];b=d[f][3];try{e.notify(A(b)? b(c):c)}catch(h){a(h)}}})}};var h=function(a,b){var c=new g;b?c.resolve(a):c.reject(a);return c.promise},l=function(a,b,c){var d=null;try{A(c)&&(d=c())}catch(e){return h(e,!1)}return d&&A(d.then)?d.then(function(){return h(a,b)},function(a){return h(a,!1)}):h(a,b)},m=function(a,b,c,d){var e=new g;e.resolve(a);return e.promise.then(b,c,d)},p=function n(a){if(!A(a))throw k("norslvr",a);if(!(this instanceof n))return new n(a);var b=new g;a(function(a){b.resolve(a)},function(a){b.reject(a)});return b.promise}; p.defer=function(){return new g};p.reject=function(a){var b=new g;b.reject(a);return b.promise};p.when=m;p.all=function(a){var b=new g,c=0,d=H(a)?[]:{};s(a,function(a,e){c++;m(a).then(function(a){d.hasOwnProperty(e)||(d[e]=a,--c||b.resolve(d))},function(a){d.hasOwnProperty(e)||b.reject(a)})});0===c&&b.resolve(d);return b.promise};return p}function Ye(){this.$get=["$window","$timeout",function(b,a){var c=b.requestAnimationFrame||b.webkitRequestAnimationFrame||b.mozRequestAnimationFrame,d=b.cancelAnimationFrame|| b.webkitCancelAnimationFrame||b.mozCancelAnimationFrame||b.webkitCancelRequestAnimationFrame,e=!!c,f=e?function(a){var b=c(a);return function(){d(b)}}:function(b){var c=a(b,16.66,!1);return function(){a.cancel(c)}};f.supported=e;return f}]}function Ne(){var b=10,a=w("$rootScope"),c=null,d=null;this.digestTtl=function(a){arguments.length&&(b=a);return b};this.$get=["$injector","$exceptionHandler","$parse","$browser",function(e,f,g,k){function h(){this.$id=++gb;this.$$phase=this.$parent=this.$$watchers= this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail=null;this.$root=this;this.$$destroyed=!1;this.$$listeners={};this.$$listenerCount={};this.$$isolateBindings=null}function l(b){if(r.$$phase)throw a("inprog",r.$$phase);r.$$phase=b}function m(a,b,c){do a.$$listenerCount[c]-=b,0===a.$$listenerCount[c]&&delete a.$$listenerCount[c];while(a=a.$parent)}function p(){}function q(){for(;C.length;)try{C.shift()()}catch(a){f(a)}d=null}function n(){null===d&&(d=k.defer(function(){r.$apply(q)}))} h.prototype={constructor:h,$new:function(a,b){function c(){d.$$destroyed=!0}var d;b=b||this;a?(d=new h,d.$root=this.$root):(this.$$ChildScope||(this.$$ChildScope=function(){this.$$watchers=this.$$nextSibling=this.$$childHead=this.$$childTail=null;this.$$listeners={};this.$$listenerCount={};this.$id=++gb;this.$$ChildScope=null},this.$$ChildScope.prototype=this),d=new this.$$ChildScope);d.$parent=b;d.$$prevSibling=b.$$childTail;b.$$childHead?(b.$$childTail.$$nextSibling=d,b.$$childTail=d):b.$$childHead= b.$$childTail=d;(a||b!=this)&&d.$on("$destroy",c);return d},$watch:function(a,b,d){var e=g(a);if(e.$$watchDelegate)return e.$$watchDelegate(this,b,d,e);var f=this.$$watchers,h={fn:b,last:p,get:e,exp:a,eq:!!d};c=null;A(b)||(h.fn=y);f||(f=this.$$watchers=[]);f.unshift(h);return function(){Va(f,h);c=null}},$watchGroup:function(a,b){function c(){h=!1;k?(k=!1,b(e,e,g)):b(e,d,g)}var d=Array(a.length),e=Array(a.length),f=[],g=this,h=!1,k=!0;if(!a.length){var l=!0;g.$evalAsync(function(){l&&b(e,e,g)});return function(){l= !1}}if(1===a.length)return this.$watch(a[0],function(a,c,f){e[0]=a;d[0]=c;b(e,a===c?e:d,f)});s(a,function(a,b){var k=g.$watch(a,function(a,f){e[b]=a;d[b]=f;h||(h=!0,g.$evalAsync(c))});f.push(k)});return function(){for(;f.length;)f.shift()()}},$watchCollection:function(a,b){function c(a){e=a;var b,d,g,h;if(P(e))if(Qa(e))for(f!==p&&(f=p,r=f.length=0,l++),a=e.length,r!==a&&(l++,f.length=r=a),b=0;b<a;b++)h=f[b],g=e[b],d=h!==h&&g!==g,d||h===g||(l++,f[b]=g);else{f!==q&&(f=q={},r=0,l++);a=0;for(b in e)e.hasOwnProperty(b)&& (a++,g=e[b],h=f[b],b in f?(d=h!==h&&g!==g,d||h===g||(l++,f[b]=g)):(r++,f[b]=g,l++));if(r>a)for(b in l++,f)e.hasOwnProperty(b)||(r--,delete f[b])}else f!==e&&(f=e,l++);return l}c.$stateful=!0;var d=this,e,f,h,k=1<b.length,l=0,m=g(a,c),p=[],q={},n=!0,r=0;return this.$watch(m,function(){n?(n=!1,b(e,e,d)):b(e,h,d);if(k)if(P(e))if(Qa(e)){h=Array(e.length);for(var a=0;a<e.length;a++)h[a]=e[a]}else for(a in h={},e)Hb.call(e,a)&&(h[a]=e[a]);else h=e})},$digest:function(){var e,g,h,m,n,s,C=b,M,t=[],W,R,z; l("$digest");k.$$checkUrlChange();this===r&&null!==d&&(k.defer.cancel(d),q());c=null;do{s=!1;for(M=this;O.length;){try{z=O.shift(),z.scope.$eval(z.expression)}catch(w){f(w)}c=null}a:do{if(m=M.$$watchers)for(n=m.length;n--;)try{if(e=m[n])if((g=e.get(M))!==(h=e.last)&&!(e.eq?la(g,h):"number"===typeof g&&"number"===typeof h&&isNaN(g)&&isNaN(h)))s=!0,c=e,e.last=e.eq?Ca(g,null):g,e.fn(g,h===p?g:h,M),5>C&&(W=4-C,t[W]||(t[W]=[]),R=A(e.exp)?"fn: "+(e.exp.name||e.exp.toString()):e.exp,R+="; newVal: "+ra(g)+ "; oldVal: "+ra(h),t[W].push(R));else if(e===c){s=!1;break a}}catch(v){f(v)}if(!(m=M.$$childHead||M!==this&&M.$$nextSibling))for(;M!==this&&!(m=M.$$nextSibling);)M=M.$parent}while(M=m);if((s||O.length)&&!C--)throw r.$$phase=null,a("infdig",b,ra(t));}while(s||O.length);for(r.$$phase=null;B.length;)try{B.shift()()}catch(y){f(y)}},$destroy:function(){if(!this.$$destroyed){var a=this.$parent;this.$broadcast("$destroy");this.$$destroyed=!0;if(this!==r){for(var b in this.$$listenerCount)m(this,this.$$listenerCount[b], b);a.$$childHead==this&&(a.$$childHead=this.$$nextSibling);a.$$childTail==this&&(a.$$childTail=this.$$prevSibling);this.$$prevSibling&&(this.$$prevSibling.$$nextSibling=this.$$nextSibling);this.$$nextSibling&&(this.$$nextSibling.$$prevSibling=this.$$prevSibling);this.$destroy=this.$digest=this.$apply=this.$evalAsync=this.$applyAsync=y;this.$on=this.$watch=this.$watchGroup=function(){return y};this.$$listeners={};this.$parent=this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail= this.$root=this.$$watchers=null}}},$eval:function(a,b){return g(a)(this,b)},$evalAsync:function(a){r.$$phase||O.length||k.defer(function(){O.length&&r.$digest()});O.push({scope:this,expression:a})},$$postDigest:function(a){B.push(a)},$apply:function(a){try{return l("$apply"),this.$eval(a)}catch(b){f(b)}finally{r.$$phase=null;try{r.$digest()}catch(c){throw f(c),c;}}},$applyAsync:function(a){function b(){c.$eval(a)}var c=this;a&&C.push(b);n()},$on:function(a,b){var c=this.$$listeners[a];c||(this.$$listeners[a]= c=[]);c.push(b);var d=this;do d.$$listenerCount[a]||(d.$$listenerCount[a]=0),d.$$listenerCount[a]++;while(d=d.$parent);var e=this;return function(){var d=c.indexOf(b);-1!==d&&(c[d]=null,m(e,1,a))}},$emit:function(a,b){var c=[],d,e=this,g=!1,h={name:a,targetScope:e,stopPropagation:function(){g=!0},preventDefault:function(){h.defaultPrevented=!0},defaultPrevented:!1},k=ib([h],arguments,1),l,m;do{d=e.$$listeners[a]||c;h.currentScope=e;l=0;for(m=d.length;l<m;l++)if(d[l])try{d[l].apply(null,k)}catch(p){f(p)}else d.splice(l, 1),l--,m--;if(g)return h.currentScope=null,h;e=e.$parent}while(e);h.currentScope=null;return h},$broadcast:function(a,b){var c=this,d=this,e={name:a,targetScope:this,preventDefault:function(){e.defaultPrevented=!0},defaultPrevented:!1};if(!this.$$listenerCount[a])return e;for(var g=ib([e],arguments,1),h,k;c=d;){e.currentScope=c;d=c.$$listeners[a]||[];h=0;for(k=d.length;h<k;h++)if(d[h])try{d[h].apply(null,g)}catch(l){f(l)}else d.splice(h,1),h--,k--;if(!(d=c.$$listenerCount[a]&&c.$$childHead||c!==this&& c.$$nextSibling))for(;c!==this&&!(d=c.$$nextSibling);)c=c.$parent}e.currentScope=null;return e}};var r=new h,O=r.$$asyncQueue=[],B=r.$$postDigestQueue=[],C=r.$$applyAsyncQueue=[];return r}]}function Qd(){var b=/^\s*(https?|ftp|mailto|tel|file):/,a=/^\s*((https?|ftp|file|blob):|data:image\/)/;this.aHrefSanitizationWhitelist=function(a){return z(a)?(b=a,this):b};this.imgSrcSanitizationWhitelist=function(b){return z(b)?(a=b,this):a};this.$get=function(){return function(c,d){var e=d?a:b,f;f=za(c).href; return""===f||f.match(e)?c:"unsafe:"+f}}}function xf(b){if("self"===b)return b;if(J(b)){if(-1<b.indexOf("***"))throw Ba("iwcard",b);b=ed(b).replace("\\*\\*",".*").replace("\\*","[^:/.?&;]*");return new RegExp("^"+b+"$")}if(hb(b))return new RegExp("^"+b.source+"$");throw Ba("imatcher");}function fd(b){var a=[];z(b)&&s(b,function(b){a.push(xf(b))});return a}function Re(){this.SCE_CONTEXTS=ja;var b=["self"],a=[];this.resourceUrlWhitelist=function(a){arguments.length&&(b=fd(a));return b};this.resourceUrlBlacklist= function(b){arguments.length&&(a=fd(b));return a};this.$get=["$injector",function(c){function d(a,b){return"self"===a?Wc(b):!!a.exec(b.href)}function e(a){var b=function(a){this.$$unwrapTrustedValue=function(){return a}};a&&(b.prototype=new a);b.prototype.valueOf=function(){return this.$$unwrapTrustedValue()};b.prototype.toString=function(){return this.$$unwrapTrustedValue().toString()};return b}var f=function(a){throw Ba("unsafe");};c.has("$sanitize")&&(f=c.get("$sanitize"));var g=e(),k={};k[ja.HTML]= e(g);k[ja.CSS]=e(g);k[ja.URL]=e(g);k[ja.JS]=e(g);k[ja.RESOURCE_URL]=e(k[ja.URL]);return{trustAs:function(a,b){var c=k.hasOwnProperty(a)?k[a]:null;if(!c)throw Ba("icontext",a,b);if(null===b||b===t||""===b)return b;if("string"!==typeof b)throw Ba("itype",a);return new c(b)},getTrusted:function(c,e){if(null===e||e===t||""===e)return e;var g=k.hasOwnProperty(c)?k[c]:null;if(g&&e instanceof g)return e.$$unwrapTrustedValue();if(c===ja.RESOURCE_URL){var g=za(e.toString()),p,q,n=!1;p=0;for(q=b.length;p<q;p++)if(d(b[p], g)){n=!0;break}if(n)for(p=0,q=a.length;p<q;p++)if(d(a[p],g)){n=!1;break}if(n)return e;throw Ba("insecurl",e.toString());}if(c===ja.HTML)return f(e);throw Ba("unsafe");},valueOf:function(a){return a instanceof g?a.$$unwrapTrustedValue():a}}}]}function Qe(){var b=!0;this.enabled=function(a){arguments.length&&(b=!!a);return b};this.$get=["$parse","$sceDelegate",function(a,c){if(b&&8>Ha)throw Ba("iequirks");var d=qa(ja);d.isEnabled=function(){return b};d.trustAs=c.trustAs;d.getTrusted=c.getTrusted;d.valueOf= c.valueOf;b||(d.trustAs=d.getTrusted=function(a,b){return b},d.valueOf=Sa);d.parseAs=function(b,c){var e=a(c);return e.literal&&e.constant?e:a(c,function(a){return d.getTrusted(b,a)})};var e=d.parseAs,f=d.getTrusted,g=d.trustAs;s(ja,function(a,b){var c=S(b);d[$a("parse_as_"+c)]=function(b){return e(a,b)};d[$a("get_trusted_"+c)]=function(b){return f(a,b)};d[$a("trust_as_"+c)]=function(b){return g(a,b)}});return d}]}function Se(){this.$get=["$window","$document",function(b,a){var c={},d=aa((/android (\d+)/.exec(S((b.navigator|| {}).userAgent))||[])[1]),e=/Boxee/i.test((b.navigator||{}).userAgent),f=a[0]||{},g,k=/^(Moz|webkit|ms)(?=[A-Z])/,h=f.body&&f.body.style,l=!1,m=!1;if(h){for(var p in h)if(l=k.exec(p)){g=l[0];g=g.substr(0,1).toUpperCase()+g.substr(1);break}g||(g="WebkitOpacity"in h&&"webkit");l=!!("transition"in h||g+"Transition"in h);m=!!("animation"in h||g+"Animation"in h);!d||l&&m||(l=J(f.body.style.webkitTransition),m=J(f.body.style.webkitAnimation))}return{history:!(!b.history||!b.history.pushState||4>d||e),hasEvent:function(a){if("input"== a&&9==Ha)return!1;if(x(c[a])){var b=f.createElement("div");c[a]="on"+a in b}return c[a]},csp:Ya(),vendorPrefix:g,transitions:l,animations:m,android:d}}]}function Ue(){this.$get=["$templateCache","$http","$q",function(b,a,c){function d(e,f){d.totalPendingRequests++;var g=a.defaults&&a.defaults.transformResponse;if(H(g))for(var k=g,g=[],h=0;h<k.length;++h){var l=k[h];l!==Wb&&g.push(l)}else g===Wb&&(g=null);return a.get(e,{cache:b,transformResponse:g}).then(function(a){a=a.data;d.totalPendingRequests--; b.put(e,a);return a},function(){d.totalPendingRequests--;if(!f)throw ia("tpload",e);return c.reject()})}d.totalPendingRequests=0;return d}]}function Ve(){this.$get=["$rootScope","$browser","$location",function(b,a,c){return{findBindings:function(a,b,c){a=a.getElementsByClassName("ng-binding");var g=[];s(a,function(a){var d=ta.element(a).data("$binding");d&&s(d,function(d){c?(new RegExp("(^|\\s)"+ed(b)+"(\\s|\\||$)")).test(d)&&g.push(a):-1!=d.indexOf(b)&&g.push(a)})});return g},findModels:function(a, b,c){for(var g=["ng-","data-ng-","ng\\:"],k=0;k<g.length;++k){var h=a.querySelectorAll("["+g[k]+"model"+(c?"=":"*=")+'"'+b+'"]');if(h.length)return h}},getLocation:function(){return c.url()},setLocation:function(a){a!==c.url()&&(c.url(a),b.$digest())},whenStable:function(b){a.notifyWhenNoOutstandingRequests(b)}}}]}function We(){this.$get=["$rootScope","$browser","$q","$$q","$exceptionHandler",function(b,a,c,d,e){function f(f,h,l){var m=z(l)&&!l,p=(m?d:c).defer(),q=p.promise;h=a.defer(function(){try{p.resolve(f())}catch(a){p.reject(a), e(a)}finally{delete g[q.$$timeoutId]}m||b.$apply()},h);q.$$timeoutId=h;g[h]=p;return q}var g={};f.cancel=function(b){return b&&b.$$timeoutId in g?(g[b.$$timeoutId].reject("canceled"),delete g[b.$$timeoutId],a.defer.cancel(b.$$timeoutId)):!1};return f}]}function za(b,a){var c=b;Ha&&(Z.setAttribute("href",c),c=Z.href);Z.setAttribute("href",c);return{href:Z.href,protocol:Z.protocol?Z.protocol.replace(/:$/,""):"",host:Z.host,search:Z.search?Z.search.replace(/^\?/,""):"",hash:Z.hash?Z.hash.replace(/^#/, ""):"",hostname:Z.hostname,port:Z.port,pathname:"/"===Z.pathname.charAt(0)?Z.pathname:"/"+Z.pathname}}function Wc(b){b=J(b)?za(b):b;return b.protocol===gd.protocol&&b.host===gd.host}function Xe(){this.$get=da(N)}function Bc(b){function a(c,d){if(P(c)){var e={};s(c,function(b,c){e[c]=a(c,b)});return e}return b.factory(c+"Filter",d)}this.register=a;this.$get=["$injector",function(a){return function(b){return a.get(b+"Filter")}}];a("currency",hd);a("date",id);a("filter",yf);a("json",zf);a("limitTo", Af);a("lowercase",Bf);a("number",jd);a("orderBy",kd);a("uppercase",Cf)}function yf(){return function(b,a,c){if(!H(b))return b;var d=typeof c,e=[];e.check=function(a,b){for(var c=0;c<e.length;c++)if(!e[c](a,b))return!1;return!0};"function"!==d&&(c="boolean"===d&&c?function(a,b){return ta.equals(a,b)}:function(a,b){if(a&&b&&"object"===typeof a&&"object"===typeof b){for(var d in a)if("$"!==d.charAt(0)&&Hb.call(a,d)&&c(a[d],b[d]))return!0;return!1}b=(""+b).toLowerCase();return-1<(""+a).toLowerCase().indexOf(b)}); var f=function(a,b){if("string"===typeof b&&"!"===b.charAt(0))return!f(a,b.substr(1));switch(typeof a){case "boolean":case "number":case "string":return c(a,b);case "object":switch(typeof b){case "object":return c(a,b);default:for(var d in a)if("$"!==d.charAt(0)&&f(a[d],b))return!0}return!1;case "array":for(d=0;d<a.length;d++)if(f(a[d],b))return!0;return!1;default:return!1}};switch(typeof a){case "boolean":case "number":case "string":a={$:a};case "object":for(var g in a)(function(b){"undefined"!== typeof a[b]&&e.push(function(c){return f("$"==b?c:c&&c[b],a[b])})})(g);break;case "function":e.push(a);break;default:return b}d=[];for(g=0;g<b.length;g++){var k=b[g];e.check(k,g)&&d.push(k)}return d}}function hd(b){var a=b.NUMBER_FORMATS;return function(b,d,e){x(d)&&(d=a.CURRENCY_SYM);x(e)&&(e=2);return null==b?b:ld(b,a.PATTERNS[1],a.GROUP_SEP,a.DECIMAL_SEP,e).replace(/\u00A4/g,d)}}function jd(b){var a=b.NUMBER_FORMATS;return function(b,d){return null==b?b:ld(b,a.PATTERNS[0],a.GROUP_SEP,a.DECIMAL_SEP, d)}}function ld(b,a,c,d,e){if(!isFinite(b)||P(b))return"";var f=0>b;b=Math.abs(b);var g=b+"",k="",h=[],l=!1;if(-1!==g.indexOf("e")){var m=g.match(/([\d\.]+)e(-?)(\d+)/);m&&"-"==m[2]&&m[3]>e+1?(g="0",b=0):(k=g,l=!0)}if(l)0<e&&-1<b&&1>b&&(k=b.toFixed(e));else{g=(g.split(md)[1]||"").length;x(e)&&(e=Math.min(Math.max(a.minFrac,g),a.maxFrac));b=+(Math.round(+(b.toString()+"e"+e)).toString()+"e"+-e);0===b&&(f=!1);b=(""+b).split(md);g=b[0];b=b[1]||"";var m=0,p=a.lgSize,q=a.gSize;if(g.length>=p+q)for(m=g.length- p,l=0;l<m;l++)0===(m-l)%q&&0!==l&&(k+=c),k+=g.charAt(l);for(l=m;l<g.length;l++)0===(g.length-l)%p&&0!==l&&(k+=c),k+=g.charAt(l);for(;b.length<e;)b+="0";e&&"0"!==e&&(k+=d+b.substr(0,e))}h.push(f?a.negPre:a.posPre);h.push(k);h.push(f?a.negSuf:a.posSuf);return h.join("")}function Ab(b,a,c){var d="";0>b&&(d="-",b=-b);for(b=""+b;b.length<a;)b="0"+b;c&&(b=b.substr(b.length-a));return d+b}function $(b,a,c,d){c=c||0;return function(e){e=e["get"+b]();if(0<c||e>-c)e+=c;0===e&&-12==c&&(e=12);return Ab(e,a,d)}} function Bb(b,a){return function(c,d){var e=c["get"+b](),f=ob(a?"SHORT"+b:b);return d[f][e]}}function nd(b){var a=(new Date(b,0,1)).getDay();return new Date(b,0,(4>=a?5:12)-a)}function od(b){return function(a){var c=nd(a.getFullYear());a=+new Date(a.getFullYear(),a.getMonth(),a.getDate()+(4-a.getDay()))-+c;a=1+Math.round(a/6048E5);return Ab(a,b)}}function id(b){function a(a){var b;if(b=a.match(c)){a=new Date(0);var f=0,g=0,k=b[8]?a.setUTCFullYear:a.setFullYear,h=b[8]?a.setUTCHours:a.setHours;b[9]&& (f=aa(b[9]+b[10]),g=aa(b[9]+b[11]));k.call(a,aa(b[1]),aa(b[2])-1,aa(b[3]));f=aa(b[4]||0)-f;g=aa(b[5]||0)-g;k=aa(b[6]||0);b=Math.round(1E3*parseFloat("0."+(b[7]||0)));h.call(a,f,g,k,b)}return a}var c=/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;return function(c,e,f){var g="",k=[],h,l;e=e||"mediumDate";e=b.DATETIME_FORMATS[e]||e;J(c)&&(c=Df.test(c)?aa(c):a(c));X(c)&&(c=new Date(c));if(!ea(c))return c;for(;e;)(l=Ef.exec(e))?(k=ib(k,l,1),e=k.pop()): (k.push(e),e=null);f&&"UTC"===f&&(c=new Date(c.getTime()),c.setMinutes(c.getMinutes()+c.getTimezoneOffset()));s(k,function(a){h=Ff[a];g+=h?h(c,b.DATETIME_FORMATS):a.replace(/(^'|'$)/g,"").replace(/''/g,"'")});return g}}function zf(){return function(b){return ra(b,!0)}}function Af(){return function(b,a){X(b)&&(b=b.toString());if(!H(b)&&!J(b))return b;a=Infinity===Math.abs(Number(a))?Number(a):aa(a);if(J(b))return a?0<=a?b.slice(0,a):b.slice(a,b.length):"";var c=[],d,e;a>b.length?a=b.length:a<-b.length&& (a=-b.length);0<a?(d=0,e=a):(d=b.length+a,e=b.length);for(;d<e;d++)c.push(b[d]);return c}}function kd(b){return function(a,c,d){function e(a,b){return b?function(b,c){return a(c,b)}:a}function f(a,b){var c=typeof a,d=typeof b;return c==d?(ea(a)&&ea(b)&&(a=a.valueOf(),b=b.valueOf()),"string"==c&&(a=a.toLowerCase(),b=b.toLowerCase()),a===b?0:a<b?-1:1):c<d?-1:1}if(!Qa(a))return a;c=H(c)?c:[c];0===c.length&&(c=["+"]);c=c.map(function(a){var c=!1,d=a||Sa;if(J(a)){if("+"==a.charAt(0)||"-"==a.charAt(0))c= "-"==a.charAt(0),a=a.substring(1);if(""===a)return e(function(a,b){return f(a,b)},c);d=b(a);if(d.constant){var g=d();return e(function(a,b){return f(a[g],b[g])},c)}}return e(function(a,b){return f(d(a),d(b))},c)});for(var g=[],k=0;k<a.length;k++)g.push(a[k]);return g.sort(e(function(a,b){for(var d=0;d<c.length;d++){var e=c[d](a,b);if(0!==e)return e}return 0},d))}}function Ia(b){A(b)&&(b={link:b});b.restrict=b.restrict||"AC";return da(b)}function pd(b,a,c,d,e){var f=this,g=[],k=f.$$parentForm=b.parent().controller("form")|| Cb;f.$error={};f.$$success={};f.$pending=t;f.$name=e(a.name||a.ngForm||"")(c);f.$dirty=!1;f.$pristine=!0;f.$valid=!0;f.$invalid=!1;f.$submitted=!1;k.$addControl(f);f.$rollbackViewValue=function(){s(g,function(a){a.$rollbackViewValue()})};f.$commitViewValue=function(){s(g,function(a){a.$commitViewValue()})};f.$addControl=function(a){La(a.$name,"input");g.push(a);a.$name&&(f[a.$name]=a)};f.$$renameControl=function(a,b){var c=a.$name;f[c]===a&&delete f[c];f[b]=a;a.$name=b};f.$removeControl=function(a){a.$name&& f[a.$name]===a&&delete f[a.$name];s(f.$pending,function(b,c){f.$setValidity(c,null,a)});s(f.$error,function(b,c){f.$setValidity(c,null,a)});Va(g,a)};qd({ctrl:this,$element:b,set:function(a,b,c){var d=a[b];d?-1===d.indexOf(c)&&d.push(c):a[b]=[c]},unset:function(a,b,c){var d=a[b];d&&(Va(d,c),0===d.length&&delete a[b])},parentForm:k,$animate:d});f.$setDirty=function(){d.removeClass(b,Pa);d.addClass(b,Db);f.$dirty=!0;f.$pristine=!1;k.$setDirty()};f.$setPristine=function(){d.setClass(b,Pa,Db+" ng-submitted"); f.$dirty=!1;f.$pristine=!0;f.$submitted=!1;s(g,function(a){a.$setPristine()})};f.$setUntouched=function(){s(g,function(a){a.$setUntouched()})};f.$setSubmitted=function(){d.addClass(b,"ng-submitted");f.$submitted=!0;k.$setSubmitted()}}function fc(b){b.$formatters.push(function(a){return b.$isEmpty(a)?a:a.toString()})}function db(b,a,c,d,e,f){var g=a[0].placeholder,k={},h=S(a[0].type);if(!e.android){var l=!1;a.on("compositionstart",function(a){l=!0});a.on("compositionend",function(){l=!1;m()})}var m= function(b){if(!l){var e=a.val(),f=b&&b.type;Ha&&"input"===(b||k).type&&a[0].placeholder!==g?g=a[0].placeholder:("password"===h||c.ngTrim&&"false"===c.ngTrim||(e=T(e)),(d.$viewValue!==e||""===e&&d.$$hasNativeValidators)&&d.$setViewValue(e,f))}};if(e.hasEvent("input"))a.on("input",m);else{var p,q=function(a){p||(p=f.defer(function(){m(a);p=null}))};a.on("keydown",function(a){var b=a.keyCode;91===b||15<b&&19>b||37<=b&&40>=b||q(a)});if(e.hasEvent("paste"))a.on("paste cut",q)}a.on("change",m);d.$render= function(){a.val(d.$isEmpty(d.$modelValue)?"":d.$viewValue)}}function Eb(b,a){return function(c,d){var e,f;if(ea(c))return c;if(J(c)){'"'==c.charAt(0)&&'"'==c.charAt(c.length-1)&&(c=c.substring(1,c.length-1));if(Gf.test(c))return new Date(c);b.lastIndex=0;if(e=b.exec(c))return e.shift(),f=d?{yyyy:d.getFullYear(),MM:d.getMonth()+1,dd:d.getDate(),HH:d.getHours(),mm:d.getMinutes(),ss:d.getSeconds(),sss:d.getMilliseconds()/1E3}:{yyyy:1970,MM:1,dd:1,HH:0,mm:0,ss:0,sss:0},s(e,function(b,c){c<a.length&& (f[a[c]]=+b)}),new Date(f.yyyy,f.MM-1,f.dd,f.HH,f.mm,f.ss||0,1E3*f.sss||0)}return NaN}}function eb(b,a,c,d){return function(e,f,g,k,h,l,m){function p(a){return z(a)?ea(a)?a:c(a):t}rd(e,f,g,k);db(e,f,g,k,h,l);var q=k&&k.$options&&k.$options.timezone,n;k.$$parserName=b;k.$parsers.push(function(b){return k.$isEmpty(b)?null:a.test(b)?(b=c(b,n),"UTC"===q&&b.setMinutes(b.getMinutes()-b.getTimezoneOffset()),b):t});k.$formatters.push(function(a){if(k.$isEmpty(a))n=null;else{if(!ea(a))throw Fb("datefmt",a); if((n=a)&&"UTC"===q){var b=6E4*n.getTimezoneOffset();n=new Date(n.getTime()+b)}return m("date")(a,d,q)}return""});if(z(g.min)||g.ngMin){var r;k.$validators.min=function(a){return k.$isEmpty(a)||x(r)||c(a)>=r};g.$observe("min",function(a){r=p(a);k.$validate()})}if(z(g.max)||g.ngMax){var s;k.$validators.max=function(a){return k.$isEmpty(a)||x(s)||c(a)<=s};g.$observe("max",function(a){s=p(a);k.$validate()})}k.$isEmpty=function(a){return!a||a.getTime&&a.getTime()!==a.getTime()}}}function rd(b,a,c,d){(d.$$hasNativeValidators= P(a[0].validity))&&d.$parsers.push(function(b){var c=a.prop("validity")||{};return c.badInput&&!c.typeMismatch?t:b})}function sd(b,a,c,d,e){if(z(d)){b=b(d);if(!b.constant)throw w("ngModel")("constexpr",c,d);return b(a)}return e}function qd(b){function a(a,b){b&&!f[a]?(l.addClass(e,a),f[a]=!0):!b&&f[a]&&(l.removeClass(e,a),f[a]=!1)}function c(b,c){b=b?"-"+Kb(b,"-"):"";a(fb+b,!0===c);a(td+b,!1===c)}var d=b.ctrl,e=b.$element,f={},g=b.set,k=b.unset,h=b.parentForm,l=b.$animate;f[td]=!(f[fb]=e.hasClass(fb)); d.$setValidity=function(b,e,f){e===t?(d.$pending||(d.$pending={}),g(d.$pending,b,f)):(d.$pending&&k(d.$pending,b,f),ud(d.$pending)&&(d.$pending=t));Ua(e)?e?(k(d.$error,b,f),g(d.$$success,b,f)):(g(d.$error,b,f),k(d.$$success,b,f)):(k(d.$error,b,f),k(d.$$success,b,f));d.$pending?(a(vd,!0),d.$valid=d.$invalid=t,c("",null)):(a(vd,!1),d.$valid=ud(d.$error),d.$invalid=!d.$valid,c("",d.$valid));e=d.$pending&&d.$pending[b]?t:d.$error[b]?!1:d.$$success[b]?!0:null;c(b,e);h.$setValidity(b,e,d)}}function ud(b){if(b)for(var a in b)return!1; return!0}function gc(b,a){b="ngClass"+b;return["$animate",function(c){function d(a,b){var c=[],d=0;a:for(;d<a.length;d++){for(var e=a[d],m=0;m<b.length;m++)if(e==b[m])continue a;c.push(e)}return c}function e(a){if(!H(a)){if(J(a))return a.split(" ");if(P(a)){var b=[];s(a,function(a,c){a&&(b=b.concat(c.split(" ")))});return b}}return a}return{restrict:"AC",link:function(f,g,k){function h(a,b){var c=g.data("$classCounts")||{},d=[];s(a,function(a){if(0<b||c[a])c[a]=(c[a]||0)+b,c[a]===+(0<b)&&d.push(a)}); g.data("$classCounts",c);return d.join(" ")}function l(b){if(!0===a||f.$index%2===a){var l=e(b||[]);if(!m){var n=h(l,1);k.$addClass(n)}else if(!la(b,m)){var r=e(m),n=d(l,r),l=d(r,l),n=h(n,1),l=h(l,-1);n&&n.length&&c.addClass(g,n);l&&l.length&&c.removeClass(g,l)}}m=qa(b)}var m;f.$watch(k[b],l,!0);k.$observe("class",function(a){l(f.$eval(k[b]))});"ngClass"!==b&&f.$watch("$index",function(c,d){var g=c&1;if(g!==(d&1)){var l=e(f.$eval(k[b]));g===a?(g=h(l,1),k.$addClass(g)):(g=h(l,-1),k.$removeClass(g))}})}}}]} var Hf=/^\/(.+)\/([a-z]*)$/,S=function(b){return J(b)?b.toLowerCase():b},Hb=Object.prototype.hasOwnProperty,ob=function(b){return J(b)?b.toUpperCase():b},Ha,v,ma,Xa=[].slice,pf=[].splice,If=[].push,Ja=Object.prototype.toString,Wa=w("ng"),ta=N.angular||(N.angular={}),Za,gb=0;Ha=U.documentMode;y.$inject=[];Sa.$inject=[];var H=Array.isArray,T=function(b){return J(b)?b.trim():b},ed=function(b){return b.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1").replace(/\x08/g,"\\x08")},Ya=function(){if(z(Ya.isActive_))return Ya.isActive_; var b=!(!U.querySelector("[ng-csp]")&&!U.querySelector("[data-ng-csp]"));if(!b)try{new Function("")}catch(a){b=!0}return Ya.isActive_=b},lb=["ng-","data-ng-","ng:","x-ng-"],Kd=/[A-Z]/g,sc=!1,Lb,ka=1,jb=3,Od={full:"1.3.1",major:1,minor:3,dot:1,codeName:"spectral-lobster"};Q.expando="ng339";var tb=Q.cache={},ef=1;Q._data=function(b){return this.cache[b[this.expando]]||{}};var $e=/([\:\-\_]+(.))/g,af=/^moz([A-Z])/,Jf={mouseleave:"mouseout",mouseenter:"mouseover"},Ob=w("jqLite"),df=/^<(\w+)\s*\/?>(?:<\/\1>|)$/, Nb=/<|&#?\w+;/,bf=/<([\w:]+)/,cf=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ha={option:[1,'<select multiple="multiple">',"</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ha.optgroup=ha.option;ha.tbody=ha.tfoot=ha.colgroup=ha.caption=ha.thead;ha.th=ha.td;var Ka=Q.prototype={ready:function(b){function a(){c||(c= !0,b())}var c=!1;"complete"===U.readyState?setTimeout(a):(this.on("DOMContentLoaded",a),Q(N).on("load",a))},toString:function(){var b=[];s(this,function(a){b.push(""+a)});return"["+b.join(", ")+"]"},eq:function(b){return 0<=b?v(this[b]):v(this[this.length+b])},length:0,push:If,sort:[].sort,splice:[].splice},vb={};s("multiple selected checked disabled readOnly required open".split(" "),function(b){vb[S(b)]=b});var Kc={};s("input select option textarea button form details".split(" "),function(b){Kc[b]= !0});var Lc={ngMinlength:"minlength",ngMaxlength:"maxlength",ngMin:"min",ngMax:"max",ngPattern:"pattern"};s({data:Qb,removeData:rb},function(b,a){Q[a]=b});s({data:Qb,inheritedData:ub,scope:function(b){return v.data(b,"$scope")||ub(b.parentNode||b,["$isolateScope","$scope"])},isolateScope:function(b){return v.data(b,"$isolateScope")||v.data(b,"$isolateScopeNoTemplate")},controller:Gc,injector:function(b){return ub(b,"$injector")},removeAttr:function(b,a){b.removeAttribute(a)},hasClass:Rb,css:function(b, a,c){a=$a(a);if(z(c))b.style[a]=c;else return b.style[a]},attr:function(b,a,c){var d=S(a);if(vb[d])if(z(c))c?(b[a]=!0,b.setAttribute(a,d)):(b[a]=!1,b.removeAttribute(d));else return b[a]||(b.attributes.getNamedItem(a)||y).specified?d:t;else if(z(c))b.setAttribute(a,c);else if(b.getAttribute)return b=b.getAttribute(a,2),null===b?t:b},prop:function(b,a,c){if(z(c))b[a]=c;else return b[a]},text:function(){function b(a,b){if(x(b)){var d=a.nodeType;return d===ka||d===jb?a.textContent:""}a.textContent=b} b.$dv="";return b}(),val:function(b,a){if(x(a)){if(b.multiple&&"select"===pa(b)){var c=[];s(b.options,function(a){a.selected&&c.push(a.value||a.text)});return 0===c.length?null:c}return b.value}b.value=a},html:function(b,a){if(x(a))return b.innerHTML;qb(b,!0);b.innerHTML=a},empty:Hc},function(b,a){Q.prototype[a]=function(a,d){var e,f,g=this.length;if(b!==Hc&&(2==b.length&&b!==Rb&&b!==Gc?a:d)===t){if(P(a)){for(e=0;e<g;e++)if(b===Qb)b(this[e],a);else for(f in a)b(this[e],f,a[f]);return this}e=b.$dv; g=e===t?Math.min(g,1):g;for(f=0;f<g;f++){var k=b(this[f],a,d);e=e?e+k:k}return e}for(e=0;e<g;e++)b(this[e],a,d);return this}});s({removeData:rb,on:function a(c,d,e,f){if(z(f))throw Ob("onargs");if(Cc(c)){var g=sb(c,!0);f=g.events;var k=g.handle;k||(k=g.handle=hf(c,f));for(var g=0<=d.indexOf(" ")?d.split(" "):[d],h=g.length;h--;){d=g[h];var l=f[d];l||(f[d]=[],"mouseenter"===d||"mouseleave"===d?a(c,Jf[d],function(a){var c=a.relatedTarget;c&&(c===this||this.contains(c))||k(a,d)}):"$destroy"!==d&&c.addEventListener(d, k,!1),l=f[d]);l.push(e)}}},off:Fc,one:function(a,c,d){a=v(a);a.on(c,function f(){a.off(c,d);a.off(c,f)});a.on(c,d)},replaceWith:function(a,c){var d,e=a.parentNode;qb(a);s(new Q(c),function(c){d?e.insertBefore(c,d.nextSibling):e.replaceChild(c,a);d=c})},children:function(a){var c=[];s(a.childNodes,function(a){a.nodeType===ka&&c.push(a)});return c},contents:function(a){return a.contentDocument||a.childNodes||[]},append:function(a,c){var d=a.nodeType;if(d===ka||11===d){c=new Q(c);for(var d=0,e=c.length;d< e;d++)a.appendChild(c[d])}},prepend:function(a,c){if(a.nodeType===ka){var d=a.firstChild;s(new Q(c),function(c){a.insertBefore(c,d)})}},wrap:function(a,c){c=v(c).eq(0).clone()[0];var d=a.parentNode;d&&d.replaceChild(c,a);c.appendChild(a)},remove:Ic,detach:function(a){Ic(a,!0)},after:function(a,c){var d=a,e=a.parentNode;c=new Q(c);for(var f=0,g=c.length;f<g;f++){var k=c[f];e.insertBefore(k,d.nextSibling);d=k}},addClass:Tb,removeClass:Sb,toggleClass:function(a,c,d){c&&s(c.split(" "),function(c){var f= d;x(f)&&(f=!Rb(a,c));(f?Tb:Sb)(a,c)})},parent:function(a){return(a=a.parentNode)&&11!==a.nodeType?a:null},next:function(a){return a.nextElementSibling},find:function(a,c){return a.getElementsByTagName?a.getElementsByTagName(c):[]},clone:Pb,triggerHandler:function(a,c,d){var e,f,g=c.type||c,k=sb(a);if(k=(k=k&&k.events)&&k[g])e={preventDefault:function(){this.defaultPrevented=!0},isDefaultPrevented:function(){return!0===this.defaultPrevented},stopImmediatePropagation:function(){this.immediatePropagationStopped= !0},isImmediatePropagationStopped:function(){return!0===this.immediatePropagationStopped},stopPropagation:y,type:g,target:a},c.type&&(e=F(e,c)),c=qa(k),f=d?[e].concat(d):[e],s(c,function(c){e.isImmediatePropagationStopped()||c.apply(a,f)})}},function(a,c){Q.prototype[c]=function(c,e,f){for(var g,k=0,h=this.length;k<h;k++)x(g)?(g=a(this[k],c,e,f),z(g)&&(g=v(g))):Ec(g,a(this[k],c,e,f));return z(g)?g:this};Q.prototype.bind=Q.prototype.on;Q.prototype.unbind=Q.prototype.off});ab.prototype={put:function(a, c){this[Ma(a,this.nextUid)]=c},get:function(a){return this[Ma(a,this.nextUid)]},remove:function(a){var c=this[a=Ma(a,this.nextUid)];delete this[a];return c}};var Nc=/^function\s*[^\(]*\(\s*([^\)]*)\)/m,kf=/,/,lf=/^\s*(_?)(\S+?)\1\s*$/,Mc=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,Ea=w("$injector");Jb.$$annotate=Ub;var Kf=w("$animate"),Ae=["$provide",function(a){this.$$selectors={};this.register=function(c,d){var e=c+"-animation";if(c&&"."!=c.charAt(0))throw Kf("notcsel",c);this.$$selectors[c.substr(1)]=e; a.factory(e,d)};this.classNameFilter=function(a){1===arguments.length&&(this.$$classNameFilter=a instanceof RegExp?a:null);return this.$$classNameFilter};this.$get=["$$q","$$asyncCallback","$rootScope",function(a,d,e){function f(d){var f,g=a.defer();g.promise.$$cancelFn=function(){f&&f()};e.$$postDigest(function(){f=d(function(){g.resolve()})});return g.promise}function g(a,c){var d=[],e=[],f=wa();s((a.attr("class")||"").split(/\s+/),function(a){f[a]=!0});s(c,function(a,c){var g=f[c];!1===a&&g?e.push(c): !0!==a||g||d.push(c)});return 0<d.length+e.length&&[d.length?d:null,e.length?e:null]}function k(a,c,d){for(var e=0,f=c.length;e<f;++e)a[c[e]]=d}function h(){m||(m=a.defer(),d(function(){m.resolve();m=null}));return m.promise}function l(a,c){if(ta.isObject(c)){var d=F(c.from||{},c.to||{});a.css(d)}}var m;return{animate:function(a,c,d){l(a,{from:c,to:d});return h()},enter:function(a,c,d,e){l(a,e);d?d.after(a):c.prepend(a);return h()},leave:function(a,c){a.remove();return h()},move:function(a,c,d,e){return this.enter(a, c,d,e)},addClass:function(a,c,d){return this.setClass(a,c,[],d)},$$addClassImmediately:function(a,c,d){a=v(a);c=J(c)?c:H(c)?c.join(" "):"";s(a,function(a){Tb(a,c)});l(a,d);return h()},removeClass:function(a,c,d){return this.setClass(a,[],c,d)},$$removeClassImmediately:function(a,c,d){a=v(a);c=J(c)?c:H(c)?c.join(" "):"";s(a,function(a){Sb(a,c)});l(a,d);return h()},setClass:function(a,c,d,e){var h=this,l=!1;a=v(a);var m=a.data("$$animateClasses");m?e&&m.options&&(m.options=ta.extend(m.options||{},e)): (m={classes:{},options:e},l=!0);e=m.classes;c=H(c)?c:c.split(" ");d=H(d)?d:d.split(" ");k(e,c,!0);k(e,d,!1);l&&(m.promise=f(function(c){var d=a.data("$$animateClasses");a.removeData("$$animateClasses");if(d){var e=g(a,d.classes);e&&h.$$setClassImmediately(a,e[0],e[1],d.options)}c()}),a.data("$$animateClasses",m));return m.promise},$$setClassImmediately:function(a,c,d,e){c&&this.$$addClassImmediately(a,c);d&&this.$$removeClassImmediately(a,d);l(a,e);return h()},enabled:y,cancel:y}}]}],ia=w("$compile"); uc.$inject=["$provide","$$sanitizeUriProvider"];var of=/^((?:x|data)[\:\-_])/i,Sc="application/json",Xb={"Content-Type":Sc+";charset=utf-8"},rf=/^\s*(\[|\{[^\{])/,sf=/[\}\]]\s*$/,qf=/^\)\]\}',?\n/,Yb=w("$interpolate"),Lf=/^([^\?#]*)(\?([^#]*))?(#(.*))?$/,vf={http:80,https:443,ftp:21},bb=w("$location"),Mf={$$html5:!1,$$replace:!1,absUrl:zb("$$absUrl"),url:function(a){if(x(a))return this.$$url;a=Lf.exec(a);a[1]&&this.path(decodeURIComponent(a[1]));(a[2]||a[1])&&this.search(a[3]||"");this.hash(a[5]|| "");return this},protocol:zb("$$protocol"),host:zb("$$host"),port:zb("$$port"),path:$c("$$path",function(a){a=null!==a?a.toString():"";return"/"==a.charAt(0)?a:"/"+a}),search:function(a,c){switch(arguments.length){case 0:return this.$$search;case 1:if(J(a)||X(a))a=a.toString(),this.$$search=qc(a);else if(P(a))a=Ca(a,{}),s(a,function(c,e){null==c&&delete a[e]}),this.$$search=a;else throw bb("isrcharg");break;default:x(c)||null===c?delete this.$$search[a]:this.$$search[a]=c}this.$$compose();return this}, hash:$c("$$hash",function(a){return null!==a?a.toString():""}),replace:function(){this.$$replace=!0;return this}};s([Zc,bc,ac],function(a){a.prototype=Object.create(Mf);a.prototype.state=function(c){if(!arguments.length)return this.$$state;if(a!==ac||!this.$$html5)throw bb("nostate");this.$$state=x(c)?null:c;return this}});var oa=w("$parse"),Nf=Function.prototype.call,Of=Function.prototype.apply,Pf=Function.prototype.bind,Gb=wa();s({"null":function(){return null},"true":function(){return!0},"false":function(){return!1}, undefined:function(){}},function(a,c){a.constant=a.literal=a.sharedGetter=!0;Gb[c]=a});Gb["this"]=function(a){return a};Gb["this"].sharedGetter=!0;var hc=F(wa(),{"+":function(a,c,d,e){d=d(a,c);e=e(a,c);return z(d)?z(e)?d+e:d:z(e)?e:t},"-":function(a,c,d,e){d=d(a,c);e=e(a,c);return(z(d)?d:0)-(z(e)?e:0)},"*":function(a,c,d,e){return d(a,c)*e(a,c)},"/":function(a,c,d,e){return d(a,c)/e(a,c)},"%":function(a,c,d,e){return d(a,c)%e(a,c)},"===":function(a,c,d,e){return d(a,c)===e(a,c)},"!==":function(a, c,d,e){return d(a,c)!==e(a,c)},"==":function(a,c,d,e){return d(a,c)==e(a,c)},"!=":function(a,c,d,e){return d(a,c)!=e(a,c)},"<":function(a,c,d,e){return d(a,c)<e(a,c)},">":function(a,c,d,e){return d(a,c)>e(a,c)},"<=":function(a,c,d,e){return d(a,c)<=e(a,c)},">=":function(a,c,d,e){return d(a,c)>=e(a,c)},"&&":function(a,c,d,e){return d(a,c)&&e(a,c)},"||":function(a,c,d,e){return d(a,c)||e(a,c)},"!":function(a,c,d){return!d(a,c)},"=":!0,"|":!0}),Qf={n:"\n",f:"\f",r:"\r",t:"\t",v:"\v","'":"'",'"':'"'}, ec=function(a){this.options=a};ec.prototype={constructor:ec,lex:function(a){this.text=a;this.index=0;this.ch=t;for(this.tokens=[];this.index<this.text.length;)if(this.ch=this.text.charAt(this.index),this.is("\"'"))this.readString(this.ch);else if(this.isNumber(this.ch)||this.is(".")&&this.isNumber(this.peek()))this.readNumber();else if(this.isIdent(this.ch))this.readIdent();else if(this.is("(){}[].,;:?"))this.tokens.push({index:this.index,text:this.ch}),this.index++;else if(this.isWhitespace(this.ch))this.index++; else{a=this.ch+this.peek();var c=a+this.peek(2),d=hc[this.ch],e=hc[a],f=hc[c];f?(this.tokens.push({index:this.index,text:c,fn:f}),this.index+=3):e?(this.tokens.push({index:this.index,text:a,fn:e}),this.index+=2):d?(this.tokens.push({index:this.index,text:this.ch,fn:d}),this.index+=1):this.throwError("Unexpected next character ",this.index,this.index+1)}return this.tokens},is:function(a){return-1!==a.indexOf(this.ch)},peek:function(a){a=a||1;return this.index+a<this.text.length?this.text.charAt(this.index+ a):!1},isNumber:function(a){return"0"<=a&&"9">=a},isWhitespace:function(a){return" "===a||"\r"===a||"\t"===a||"\n"===a||"\v"===a||"\u00a0"===a},isIdent:function(a){return"a"<=a&&"z">=a||"A"<=a&&"Z">=a||"_"===a||"$"===a},isExpOperator:function(a){return"-"===a||"+"===a||this.isNumber(a)},throwError:function(a,c,d){d=d||this.index;c=z(c)?"s "+c+"-"+this.index+" ["+this.text.substring(c,d)+"]":" "+d;throw oa("lexerr",a,c,this.text);},readNumber:function(){for(var a="",c=this.index;this.index<this.text.length;){var d= S(this.text.charAt(this.index));if("."==d||this.isNumber(d))a+=d;else{var e=this.peek();if("e"==d&&this.isExpOperator(e))a+=d;else if(this.isExpOperator(d)&&e&&this.isNumber(e)&&"e"==a.charAt(a.length-1))a+=d;else if(!this.isExpOperator(d)||e&&this.isNumber(e)||"e"!=a.charAt(a.length-1))break;else this.throwError("Invalid exponent")}this.index++}a*=1;this.tokens.push({index:c,text:a,constant:!0,fn:function(){return a}})},readIdent:function(){for(var a=this.text,c="",d=this.index,e,f,g,k;this.index< this.text.length;){k=this.text.charAt(this.index);if("."===k||this.isIdent(k)||this.isNumber(k))"."===k&&(e=this.index),c+=k;else break;this.index++}e&&"."===c[c.length-1]&&(this.index--,c=c.slice(0,-1),e=c.lastIndexOf("."),-1===e&&(e=t));if(e)for(f=this.index;f<this.text.length;){k=this.text.charAt(f);if("("===k){g=c.substr(e-d+1);c=c.substr(0,e-d);this.index=f;break}if(this.isWhitespace(k))f++;else break}this.tokens.push({index:d,text:c,fn:Gb[c]||bd(c,this.options,a)});g&&(this.tokens.push({index:e, text:"."}),this.tokens.push({index:e+1,text:g}))},readString:function(a){var c=this.index;this.index++;for(var d="",e=a,f=!1;this.index<this.text.length;){var g=this.text.charAt(this.index),e=e+g;if(f)"u"===g?(f=this.text.substring(this.index+1,this.index+5),f.match(/[\da-f]{4}/i)||this.throwError("Invalid unicode escape [\\u"+f+"]"),this.index+=4,d+=String.fromCharCode(parseInt(f,16))):d+=Qf[g]||g,f=!1;else if("\\"===g)f=!0;else{if(g===a){this.index++;this.tokens.push({index:c,text:e,string:d,constant:!0, fn:function(){return d}});return}d+=g}this.index++}this.throwError("Unterminated quote",c)}};var cb=function(a,c,d){this.lexer=a;this.$filter=c;this.options=d};cb.ZERO=F(function(){return 0},{sharedGetter:!0,constant:!0});cb.prototype={constructor:cb,parse:function(a){this.text=a;this.tokens=this.lexer.lex(a);a=this.statements();0!==this.tokens.length&&this.throwError("is an unexpected token",this.tokens[0]);a.literal=!!a.literal;a.constant=!!a.constant;return a},primary:function(){var a;if(this.expect("("))a= this.filterChain(),this.consume(")");else if(this.expect("["))a=this.arrayDeclaration();else if(this.expect("{"))a=this.object();else{var c=this.expect();(a=c.fn)||this.throwError("not a primary expression",c);c.constant&&(a.constant=!0,a.literal=!0)}for(var d;c=this.expect("(","[",".");)"("===c.text?(a=this.functionCall(a,d),d=null):"["===c.text?(d=a,a=this.objectIndex(a)):"."===c.text?(d=a,a=this.fieldAccess(a)):this.throwError("IMPOSSIBLE");return a},throwError:function(a,c){throw oa("syntax", c.text,a,c.index+1,this.text,this.text.substring(c.index));},peekToken:function(){if(0===this.tokens.length)throw oa("ueoe",this.text);return this.tokens[0]},peek:function(a,c,d,e){if(0<this.tokens.length){var f=this.tokens[0],g=f.text;if(g===a||g===c||g===d||g===e||!(a||c||d||e))return f}return!1},expect:function(a,c,d,e){return(a=this.peek(a,c,d,e))?(this.tokens.shift(),a):!1},consume:function(a){this.expect(a)||this.throwError("is unexpected, expecting ["+a+"]",this.peek())},unaryFn:function(a, c){return F(function(d,e){return a(d,e,c)},{constant:c.constant,inputs:[c]})},binaryFn:function(a,c,d,e){return F(function(e,g){return c(e,g,a,d)},{constant:a.constant&&d.constant,inputs:!e&&[a,d]})},statements:function(){for(var a=[];;)if(0<this.tokens.length&&!this.peek("}",")",";","]")&&a.push(this.filterChain()),!this.expect(";"))return 1===a.length?a[0]:function(c,d){for(var e,f=0,g=a.length;f<g;f++)e=a[f](c,d);return e}},filterChain:function(){for(var a=this.expression();this.expect("|");)a= this.filter(a);return a},filter:function(a){var c=this.expect(),d=this.$filter(c.text),e,f;if(this.peek(":"))for(e=[],f=[];this.expect(":");)e.push(this.expression());c=[a].concat(e||[]);return F(function(c,k){var h=a(c,k);if(f){f[0]=h;for(h=e.length;h--;)f[h+1]=e[h](c,k);return d.apply(t,f)}return d(h)},{constant:!d.$stateful&&c.every(cc),inputs:!d.$stateful&&c})},expression:function(){return this.assignment()},assignment:function(){var a=this.ternary(),c,d;return(d=this.expect("="))?(a.assign|| this.throwError("implies assignment but ["+this.text.substring(0,d.index)+"] can not be assigned to",d),c=this.ternary(),F(function(d,f){return a.assign(d,c(d,f),f)},{inputs:[a,c]})):a},ternary:function(){var a=this.logicalOR(),c,d;if(d=this.expect("?")){c=this.assignment();if(d=this.expect(":")){var e=this.assignment();return F(function(d,g){return a(d,g)?c(d,g):e(d,g)},{constant:a.constant&&c.constant&&e.constant})}this.throwError("expected :",d)}return a},logicalOR:function(){for(var a=this.logicalAND(), c;c=this.expect("||");)a=this.binaryFn(a,c.fn,this.logicalAND(),!0);return a},logicalAND:function(){var a=this.equality(),c;if(c=this.expect("&&"))a=this.binaryFn(a,c.fn,this.logicalAND(),!0);return a},equality:function(){var a=this.relational(),c;if(c=this.expect("==","!=","===","!=="))a=this.binaryFn(a,c.fn,this.equality());return a},relational:function(){var a=this.additive(),c;if(c=this.expect("<",">","<=",">="))a=this.binaryFn(a,c.fn,this.relational());return a},additive:function(){for(var a= this.multiplicative(),c;c=this.expect("+","-");)a=this.binaryFn(a,c.fn,this.multiplicative());return a},multiplicative:function(){for(var a=this.unary(),c;c=this.expect("*","/","%");)a=this.binaryFn(a,c.fn,this.unary());return a},unary:function(){var a;return this.expect("+")?this.primary():(a=this.expect("-"))?this.binaryFn(cb.ZERO,a.fn,this.unary()):(a=this.expect("!"))?this.unaryFn(a.fn,this.unary()):this.primary()},fieldAccess:function(a){var c=this.text,d=this.expect().text,e=bd(d,this.options, c);return F(function(c,d,k){return e(k||a(c,d))},{assign:function(e,g,k){(k=a(e,k))||a.assign(e,k={});return Oa(k,d,g,c)}})},objectIndex:function(a){var c=this.text,d=this.expression();this.consume("]");return F(function(e,f){var g=a(e,f),k=d(e,f);na(k,c);return g?Aa(g[k],c):t},{assign:function(e,f,g){var k=na(d(e,g),c);(g=Aa(a(e,g),c))||a.assign(e,g={});return g[k]=f}})},functionCall:function(a,c){var d=[];if(")"!==this.peekToken().text){do d.push(this.expression());while(this.expect(","))}this.consume(")"); var e=this.text,f=d.length?[]:null;return function(g,k){var h=c?c(g,k):g,l=a(g,k,h)||y;if(f)for(var m=d.length;m--;)f[m]=Aa(d[m](g,k),e);Aa(h,e);if(l){if(l.constructor===l)throw oa("isecfn",e);if(l===Nf||l===Of||l===Pf)throw oa("isecff",e);}h=l.apply?l.apply(h,f):l(f[0],f[1],f[2],f[3],f[4]);return Aa(h,e)}},arrayDeclaration:function(){var a=[];if("]"!==this.peekToken().text){do{if(this.peek("]"))break;var c=this.expression();a.push(c)}while(this.expect(","))}this.consume("]");return F(function(c, e){for(var f=[],g=0,k=a.length;g<k;g++)f.push(a[g](c,e));return f},{literal:!0,constant:a.every(cc),inputs:a})},object:function(){var a=[],c=[];if("}"!==this.peekToken().text){do{if(this.peek("}"))break;var d=this.expect();a.push(d.string||d.text);this.consume(":");d=this.expression();c.push(d)}while(this.expect(","))}this.consume("}");return F(function(d,f){for(var g={},k=0,h=c.length;k<h;k++)g[a[k]]=c[k](d,f);return g},{literal:!0,constant:c.every(cc),inputs:c})}};var cd=wa(),wf=Object.prototype.valueOf, Ba=w("$sce"),ja={HTML:"html",CSS:"css",URL:"url",RESOURCE_URL:"resourceUrl",JS:"js"},ia=w("$compile"),Z=U.createElement("a"),gd=za(N.location.href,!0);Bc.$inject=["$provide"];hd.$inject=["$locale"];jd.$inject=["$locale"];var md=".",Ff={yyyy:$("FullYear",4),yy:$("FullYear",2,0,!0),y:$("FullYear",1),MMMM:Bb("Month"),MMM:Bb("Month",!0),MM:$("Month",2,1),M:$("Month",1,1),dd:$("Date",2),d:$("Date",1),HH:$("Hours",2),H:$("Hours",1),hh:$("Hours",2,-12),h:$("Hours",1,-12),mm:$("Minutes",2),m:$("Minutes", 1),ss:$("Seconds",2),s:$("Seconds",1),sss:$("Milliseconds",3),EEEE:Bb("Day"),EEE:Bb("Day",!0),a:function(a,c){return 12>a.getHours()?c.AMPMS[0]:c.AMPMS[1]},Z:function(a){a=-1*a.getTimezoneOffset();return a=(0<=a?"+":"")+(Ab(Math[0<a?"floor":"ceil"](a/60),2)+Ab(Math.abs(a%60),2))},ww:od(2),w:od(1)},Ef=/((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|w+))(.*)/,Df=/^\-?\d+$/;id.$inject=["$locale"];var Bf=da(S),Cf=da(ob);kd.$inject=["$parse"];var Rd=da({restrict:"E",compile:function(a, c){if(!c.href&&!c.xlinkHref&&!c.name)return function(a,c){var f="[object SVGAnimatedString]"===Ja.call(c.prop("href"))?"xlink:href":"href";c.on("click",function(a){c.attr(f)||a.preventDefault()})}}}),pb={};s(vb,function(a,c){if("multiple"!=a){var d=ua("ng-"+c);pb[d]=function(){return{restrict:"A",priority:100,link:function(a,f,g){a.$watch(g[d],function(a){g.$set(c,!!a)})}}}}});s(Lc,function(a,c){pb[c]=function(){return{priority:100,link:function(a,e,f){if("ngPattern"===c&&"/"==f.ngPattern.charAt(0)&& (e=f.ngPattern.match(Hf))){f.$set("ngPattern",new RegExp(e[1],e[2]));return}a.$watch(f[c],function(a){f.$set(c,a)})}}}});s(["src","srcset","href"],function(a){var c=ua("ng-"+a);pb[c]=function(){return{priority:99,link:function(d,e,f){var g=a,k=a;"href"===a&&"[object SVGAnimatedString]"===Ja.call(e.prop("href"))&&(k="xlinkHref",f.$attr[k]="xlink:href",g=null);f.$observe(c,function(c){c?(f.$set(k,c),Ha&&g&&e.prop(g,f[k])):"href"===a&&f.$set(k,null)})}}}});var Cb={$addControl:y,$$renameControl:function(a, c){a.$name=c},$removeControl:y,$setValidity:y,$setDirty:y,$setPristine:y,$setSubmitted:y};pd.$inject=["$element","$attrs","$scope","$animate","$interpolate"];var wd=function(a){return["$timeout",function(c){return{name:"form",restrict:a?"EAC":"E",controller:pd,compile:function(a){a.addClass(Pa).addClass(fb);return{pre:function(a,d,g,k){if(!("action"in g)){var h=function(c){a.$apply(function(){k.$commitViewValue();k.$setSubmitted()});c.preventDefault?c.preventDefault():c.returnValue=!1};d[0].addEventListener("submit", h,!1);d.on("$destroy",function(){c(function(){d[0].removeEventListener("submit",h,!1)},0,!1)})}var l=k.$$parentForm,m=k.$name;m&&(Oa(a,m,k,m),g.$observe(g.name?"name":"ngForm",function(c){m!==c&&(Oa(a,m,t,m),m=c,Oa(a,m,k,m),l.$$renameControl(k,m))}));d.on("$destroy",function(){l.$removeControl(k);m&&Oa(a,m,t,m);F(k,Cb)})}}}}}]},Sd=wd(),ee=wd(!0),Gf=/\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/,Rf=/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/, Sf=/^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i,Tf=/^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/,xd=/^(\d{4})-(\d{2})-(\d{2})$/,yd=/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/,ic=/^(\d{4})-W(\d\d)$/,zd=/^(\d{4})-(\d\d)$/,Ad=/^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/,Uf=/(\s+|^)default(\s+|$)/,Fb=new w("ngModel"),Bd={text:function(a,c,d,e,f,g){db(a,c,d,e,f,g);fc(e)},date:eb("date",xd,Eb(xd,["yyyy","MM","dd"]),"yyyy-MM-dd"),"datetime-local":eb("datetimelocal", yd,Eb(yd,"yyyy MM dd HH mm ss sss".split(" ")),"yyyy-MM-ddTHH:mm:ss.sss"),time:eb("time",Ad,Eb(Ad,["HH","mm","ss","sss"]),"HH:mm:ss.sss"),week:eb("week",ic,function(a,c){if(ea(a))return a;if(J(a)){ic.lastIndex=0;var d=ic.exec(a);if(d){var e=+d[1],f=+d[2],g=d=0,k=0,h=0,l=nd(e),f=7*(f-1);c&&(d=c.getHours(),g=c.getMinutes(),k=c.getSeconds(),h=c.getMilliseconds());return new Date(e,0,l.getDate()+f,d,g,k,h)}}return NaN},"yyyy-Www"),month:eb("month",zd,Eb(zd,["yyyy","MM"]),"yyyy-MM"),number:function(a, c,d,e,f,g){rd(a,c,d,e);db(a,c,d,e,f,g);e.$$parserName="number";e.$parsers.push(function(a){return e.$isEmpty(a)?null:Tf.test(a)?parseFloat(a):t});e.$formatters.push(function(a){if(!e.$isEmpty(a)){if(!X(a))throw Fb("numfmt",a);a=a.toString()}return a});if(d.min||d.ngMin){var k;e.$validators.min=function(a){return e.$isEmpty(a)||x(k)||a>=k};d.$observe("min",function(a){z(a)&&!X(a)&&(a=parseFloat(a,10));k=X(a)&&!isNaN(a)?a:t;e.$validate()})}if(d.max||d.ngMax){var h;e.$validators.max=function(a){return e.$isEmpty(a)|| x(h)||a<=h};d.$observe("max",function(a){z(a)&&!X(a)&&(a=parseFloat(a,10));h=X(a)&&!isNaN(a)?a:t;e.$validate()})}},url:function(a,c,d,e,f,g){db(a,c,d,e,f,g);fc(e);e.$$parserName="url";e.$validators.url=function(a){return e.$isEmpty(a)||Rf.test(a)}},email:function(a,c,d,e,f,g){db(a,c,d,e,f,g);fc(e);e.$$parserName="email";e.$validators.email=function(a){return e.$isEmpty(a)||Sf.test(a)}},radio:function(a,c,d,e){x(d.name)&&c.attr("name",++gb);c.on("click",function(a){c[0].checked&&e.$setViewValue(d.value, a&&a.type)});e.$render=function(){c[0].checked=d.value==e.$viewValue};d.$observe("value",e.$render)},checkbox:function(a,c,d,e,f,g,k,h){var l=sd(h,a,"ngTrueValue",d.ngTrueValue,!0),m=sd(h,a,"ngFalseValue",d.ngFalseValue,!1);c.on("click",function(a){e.$setViewValue(c[0].checked,a&&a.type)});e.$render=function(){c[0].checked=e.$viewValue};e.$isEmpty=function(a){return a!==l};e.$formatters.push(function(a){return la(a,l)});e.$parsers.push(function(a){return a?l:m})},hidden:y,button:y,submit:y,reset:y, file:y},vc=["$browser","$sniffer","$filter","$parse",function(a,c,d,e){return{restrict:"E",require:["?ngModel"],link:{pre:function(f,g,k,h){h[0]&&(Bd[S(k.type)]||Bd.text)(f,g,k,h[0],c,a,d,e)}}}}],fb="ng-valid",td="ng-invalid",Pa="ng-pristine",Db="ng-dirty",vd="ng-pending",Vf=["$scope","$exceptionHandler","$attrs","$element","$parse","$animate","$timeout","$rootScope","$q","$interpolate",function(a,c,d,e,f,g,k,h,l,m){this.$modelValue=this.$viewValue=Number.NaN;this.$validators={};this.$asyncValidators= {};this.$parsers=[];this.$formatters=[];this.$viewChangeListeners=[];this.$untouched=!0;this.$touched=!1;this.$pristine=!0;this.$dirty=!1;this.$valid=!0;this.$invalid=!1;this.$error={};this.$$success={};this.$pending=t;this.$name=m(d.name||"",!1)(a);var p=f(d.ngModel),q=null,n=this,r=function(){var c=p(a);n.$options&&n.$options.getterSetter&&A(c)&&(c=c());return c},O=function(c){var d;n.$options&&n.$options.getterSetter&&A(d=p(a))?d(n.$modelValue):p.assign(a,n.$modelValue)};this.$$setOptions=function(a){n.$options= a;if(!(p.assign||a&&a.getterSetter))throw Fb("nonassign",d.ngModel,sa(e));};this.$render=y;this.$isEmpty=function(a){return x(a)||""===a||null===a||a!==a};var B=e.inheritedData("$formController")||Cb,C=0;qd({ctrl:this,$element:e,set:function(a,c){a[c]=!0},unset:function(a,c){delete a[c]},parentForm:B,$animate:g});this.$setPristine=function(){n.$dirty=!1;n.$pristine=!0;g.removeClass(e,Db);g.addClass(e,Pa)};this.$setUntouched=function(){n.$touched=!1;n.$untouched=!0;g.setClass(e,"ng-untouched","ng-touched")}; this.$setTouched=function(){n.$touched=!0;n.$untouched=!1;g.setClass(e,"ng-touched","ng-untouched")};this.$rollbackViewValue=function(){k.cancel(q);n.$viewValue=n.$$lastCommittedViewValue;n.$render()};this.$validate=function(){X(n.$modelValue)&&isNaN(n.$modelValue)||this.$$parseAndValidate()};this.$$runValidators=function(a,c,d,e){function f(){var a=!0;s(n.$validators,function(e,f){var g=e(c,d);a=a&&g;h(f,g)});return a?!0:(s(n.$asyncValidators,function(a,c){h(c,null)}),!1)}function g(){var a=[],e= !0;s(n.$asyncValidators,function(f,g){var k=f(c,d);if(!k||!A(k.then))throw Fb("$asyncValidators",k);h(g,t);a.push(k.then(function(){h(g,!0)},function(a){e=!1;h(g,!1)}))});a.length?l.all(a).then(function(){k(e)},y):k(!0)}function h(a,c){m===C&&n.$setValidity(a,c)}function k(a){m===C&&e(a)}C++;var m=C;(function(a){var c=n.$$parserName||"parse";if(a===t)h(c,null);else if(h(c,a),!a)return s(n.$validators,function(a,c){h(c,null)}),s(n.$asyncValidators,function(a,c){h(c,null)}),!1;return!0})(a)?f()?g(): k(!1):k(!1)};this.$commitViewValue=function(){var a=n.$viewValue;k.cancel(q);if(n.$$lastCommittedViewValue!==a||""===a&&n.$$hasNativeValidators)n.$$lastCommittedViewValue=a,n.$pristine&&(n.$dirty=!0,n.$pristine=!1,g.removeClass(e,Pa),g.addClass(e,Db),B.$setDirty()),this.$$parseAndValidate()};this.$$parseAndValidate=function(){var a=n.$$lastCommittedViewValue,c=a,d=x(c)?t:!0;if(d)for(var e=0;e<n.$parsers.length;e++)if(c=n.$parsers[e](c),x(c)){d=!1;break}X(n.$modelValue)&&isNaN(n.$modelValue)&&(n.$modelValue= r());var f=n.$modelValue,g=n.$options&&n.$options.allowInvalid;g&&(n.$modelValue=c,n.$modelValue!==f&&n.$$writeModelToScope());n.$$runValidators(d,c,a,function(a){g||(n.$modelValue=a?c:t,n.$modelValue!==f&&n.$$writeModelToScope())})};this.$$writeModelToScope=function(){O(n.$modelValue);s(n.$viewChangeListeners,function(a){try{a()}catch(d){c(d)}})};this.$setViewValue=function(a,c){n.$viewValue=a;n.$options&&!n.$options.updateOnDefault||n.$$debounceViewValueCommit(c)};this.$$debounceViewValueCommit= function(c){var d=0,e=n.$options;e&&z(e.debounce)&&(e=e.debounce,X(e)?d=e:X(e[c])?d=e[c]:X(e["default"])&&(d=e["default"]));k.cancel(q);d?q=k(function(){n.$commitViewValue()},d):h.$$phase?n.$commitViewValue():a.$apply(function(){n.$commitViewValue()})};a.$watch(function(){var a=r();if(a!==n.$modelValue){n.$modelValue=a;for(var c=n.$formatters,d=c.length,e=a;d--;)e=c[d](e);n.$viewValue!==e&&(n.$viewValue=n.$$lastCommittedViewValue=e,n.$render(),n.$$runValidators(t,a,e,y))}return a})}],te=function(){return{restrict:"A", require:["ngModel","^?form","^?ngModelOptions"],controller:Vf,priority:1,compile:function(a){a.addClass(Pa).addClass("ng-untouched").addClass(fb);return{pre:function(a,d,e,f){var g=f[0],k=f[1]||Cb;g.$$setOptions(f[2]&&f[2].$options);k.$addControl(g);e.$observe("name",function(a){g.$name!==a&&k.$$renameControl(g,a)});a.$on("$destroy",function(){k.$removeControl(g)})},post:function(a,d,e,f){var g=f[0];if(g.$options&&g.$options.updateOn)d.on(g.$options.updateOn,function(a){g.$$debounceViewValueCommit(a&& a.type)});d.on("blur",function(d){g.$touched||a.$apply(function(){g.$setTouched()})})}}}}},ve=da({restrict:"A",require:"ngModel",link:function(a,c,d,e){e.$viewChangeListeners.push(function(){a.$eval(d.ngChange)})}}),xc=function(){return{restrict:"A",require:"?ngModel",link:function(a,c,d,e){e&&(d.required=!0,e.$validators.required=function(a){return!d.required||!e.$isEmpty(a)},d.$observe("required",function(){e.$validate()}))}}},wc=function(){return{restrict:"A",require:"?ngModel",link:function(a, c,d,e){if(e){var f,g=d.ngPattern||d.pattern;d.$observe("pattern",function(a){J(a)&&0<a.length&&(a=new RegExp(a));if(a&&!a.test)throw w("ngPattern")("noregexp",g,a,sa(c));f=a||t;e.$validate()});e.$validators.pattern=function(a){return e.$isEmpty(a)||x(f)||f.test(a)}}}}},zc=function(){return{restrict:"A",require:"?ngModel",link:function(a,c,d,e){if(e){var f=0;d.$observe("maxlength",function(a){f=aa(a)||0;e.$validate()});e.$validators.maxlength=function(a,c){return e.$isEmpty(a)||c.length<=f}}}}},yc= function(){return{restrict:"A",require:"?ngModel",link:function(a,c,d,e){if(e){var f=0;d.$observe("minlength",function(a){f=aa(a)||0;e.$validate()});e.$validators.minlength=function(a,c){return e.$isEmpty(a)||c.length>=f}}}}},ue=function(){return{restrict:"A",priority:100,require:"ngModel",link:function(a,c,d,e){var f=c.attr(d.$attr.ngList)||", ",g="false"!==d.ngTrim,k=g?T(f):f;e.$parsers.push(function(a){if(!x(a)){var c=[];a&&s(a.split(k),function(a){a&&c.push(g?T(a):a)});return c}});e.$formatters.push(function(a){return H(a)? a.join(f):t});e.$isEmpty=function(a){return!a||!a.length}}}},Wf=/^(true|false|\d+)$/,we=function(){return{restrict:"A",priority:100,compile:function(a,c){return Wf.test(c.ngValue)?function(a,c,f){f.$set("value",a.$eval(f.ngValue))}:function(a,c,f){a.$watch(f.ngValue,function(a){f.$set("value",a)})}}}},xe=function(){return{restrict:"A",controller:["$scope","$attrs",function(a,c){var d=this;this.$options=a.$eval(c.ngModelOptions);this.$options.updateOn!==t?(this.$options.updateOnDefault=!1,this.$options.updateOn= T(this.$options.updateOn.replace(Uf,function(){d.$options.updateOnDefault=!0;return" "}))):this.$options.updateOnDefault=!0}]}},Xd=["$compile",function(a){return{restrict:"AC",compile:function(c){a.$$addBindingClass(c);return function(c,e,f){a.$$addBindingInfo(e,f.ngBind);e=e[0];c.$watch(f.ngBind,function(a){e.textContent=a===t?"":a})}}}}],Zd=["$interpolate","$compile",function(a,c){return{compile:function(d){c.$$addBindingClass(d);return function(d,f,g){d=a(f.attr(g.$attr.ngBindTemplate));c.$$addBindingInfo(f, d.expressions);f=f[0];g.$observe("ngBindTemplate",function(a){f.textContent=a===t?"":a})}}}}],Yd=["$sce","$parse","$compile",function(a,c,d){return{restrict:"A",compile:function(e,f){var g=c(f.ngBindHtml),k=c(f.ngBindHtml,function(a){return(a||"").toString()});d.$$addBindingClass(e);return function(c,e,f){d.$$addBindingInfo(e,f.ngBindHtml);c.$watch(k,function(){e.html(a.getTrustedHtml(g(c))||"")})}}}}],$d=gc("",!0),be=gc("Odd",0),ae=gc("Even",1),ce=Ia({compile:function(a,c){c.$set("ngCloak",t);a.removeClass("ng-cloak")}}), de=[function(){return{restrict:"A",scope:!0,controller:"@",priority:500}}],Ac={},Xf={blur:!0,focus:!0};s("click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste".split(" "),function(a){var c=ua("ng-"+a);Ac[c]=["$parse","$rootScope",function(d,e){return{restrict:"A",compile:function(f,g){var k=d(g[c]);return function(c,d){d.on(a,function(d){var f=function(){k(c,{$event:d})};Xf[a]&&e.$$phase?c.$evalAsync(f):c.$apply(f)})}}}}]}); var ge=["$animate",function(a){return{multiElement:!0,transclude:"element",priority:600,terminal:!0,restrict:"A",$$tlb:!0,link:function(c,d,e,f,g){var k,h,l;c.$watch(e.ngIf,function(c){c?h||g(function(c,f){h=f;c[c.length++]=U.createComment(" end ngIf: "+e.ngIf+" ");k={clone:c};a.enter(c,d.parent(),d)}):(l&&(l.remove(),l=null),h&&(h.$destroy(),h=null),k&&(l=nb(k.clone),a.leave(l).then(function(){l=null}),k=null))})}}}],he=["$templateRequest","$anchorScroll","$animate","$sce",function(a,c,d,e){return{restrict:"ECA", priority:400,terminal:!0,transclude:"element",controller:ta.noop,compile:function(f,g){var k=g.ngInclude||g.src,h=g.onload||"",l=g.autoscroll;return function(f,g,q,n,r){var s=0,t,C,D,G=function(){C&&(C.remove(),C=null);t&&(t.$destroy(),t=null);D&&(d.leave(D).then(function(){C=null}),C=D,D=null)};f.$watch(e.parseAsResourceUrl(k),function(e){var k=function(){!z(l)||l&&!f.$eval(l)||c()},q=++s;e?(a(e,!0).then(function(a){if(q===s){var c=f.$new();n.template=a;a=r(c,function(a){G();d.enter(a,null,g).then(k)}); t=c;D=a;t.$emit("$includeContentLoaded",e);f.$eval(h)}},function(){q===s&&(G(),f.$emit("$includeContentError",e))}),f.$emit("$includeContentRequested",e)):(G(),n.template=null)})}}}}],ye=["$compile",function(a){return{restrict:"ECA",priority:-400,require:"ngInclude",link:function(c,d,e,f){/SVG/.test(d[0].toString())?(d.empty(),a(Dc(f.template,U).childNodes)(c,function(a){d.append(a)},t,t,d)):(d.html(f.template),a(d.contents())(c))}}}],ie=Ia({priority:450,compile:function(){return{pre:function(a,c, d){a.$eval(d.ngInit)}}}}),je=Ia({terminal:!0,priority:1E3}),ke=["$locale","$interpolate",function(a,c){var d=/{}/g;return{restrict:"EA",link:function(e,f,g){var k=g.count,h=g.$attr.when&&f.attr(g.$attr.when),l=g.offset||0,m=e.$eval(h)||{},p={},q=c.startSymbol(),n=c.endSymbol(),r=/^when(Minus)?(.+)$/;s(g,function(a,c){r.test(c)&&(m[S(c.replace("when","").replace("Minus","-"))]=f.attr(g.$attr[c]))});s(m,function(a,e){p[e]=c(a.replace(d,q+k+"-"+l+n))});e.$watch(function(){var c=parseFloat(e.$eval(k)); if(isNaN(c))return"";c in m||(c=a.pluralCat(c-l));return p[c](e)},function(a){f.text(a)})}}}],le=["$parse","$animate",function(a,c){var d=w("ngRepeat"),e=function(a,c,d,e,l,m,p){a[d]=e;l&&(a[l]=m);a.$index=c;a.$first=0===c;a.$last=c===p-1;a.$middle=!(a.$first||a.$last);a.$odd=!(a.$even=0===(c&1))};return{restrict:"A",multiElement:!0,transclude:"element",priority:1E3,terminal:!0,$$tlb:!0,compile:function(f,g){var k=g.ngRepeat,h=U.createComment(" end ngRepeat: "+k+" "),l=k.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/); if(!l)throw d("iexp",k);var m=l[1],p=l[2],q=l[3],n=l[4],l=m.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);if(!l)throw d("iidexp",m);var r=l[3]||l[1],z=l[2];if(q&&(!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(q)||/^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent)$/.test(q)))throw d("badident",q);var w,C,D,G,u={$id:Ma};n?w=a(n):(D=function(a,c){return Ma(c)},G=function(a){return a});return function(a,f,g,l,m){w&&(C=function(c,d,e){z&&(u[z]=c);u[r]=d;u.$index=e;return w(a,u)}); var n=wa();a.$watchCollection(p,function(g){var l,p,E=f[0],u,w=wa(),B,y,F,x,H,A,J;q&&(a[q]=g);if(Qa(g))H=g,p=C||D;else{p=C||G;H=[];for(J in g)g.hasOwnProperty(J)&&"$"!=J.charAt(0)&&H.push(J);H.sort()}B=H.length;J=Array(B);for(l=0;l<B;l++)if(y=g===H?l:H[l],F=g[y],x=p(y,F,l),n[x])A=n[x],delete n[x],w[x]=A,J[l]=A;else{if(w[x])throw s(J,function(a){a&&a.scope&&(n[a.id]=a)}),d("dupes",k,x,ra(F));J[l]={id:x,scope:t,clone:t};w[x]=!0}for(u in n){A=n[u];x=nb(A.clone);c.leave(x);if(x[0].parentNode)for(l=0, p=x.length;l<p;l++)x[l].$$NG_REMOVED=!0;A.scope.$destroy()}for(l=0;l<B;l++)if(y=g===H?l:H[l],F=g[y],A=J[l],A.scope){u=E;do u=u.nextSibling;while(u&&u.$$NG_REMOVED);A.clone[0]!=u&&c.move(nb(A.clone),null,v(E));E=A.clone[A.clone.length-1];e(A.scope,l,r,F,z,y,B)}else m(function(a,d){A.scope=d;var f=h.cloneNode(!1);a[a.length++]=f;c.enter(a,null,v(E));E=f;A.clone=a;w[A.id]=A;e(A.scope,l,r,F,z,y,B)});n=w})}}}}],me=["$animate",function(a){return{restrict:"A",multiElement:!0,link:function(c,d,e){c.$watch(e.ngShow, function(c){a[c?"removeClass":"addClass"](d,"ng-hide",{tempClasses:"ng-hide-animate"})})}}}],fe=["$animate",function(a){return{restrict:"A",multiElement:!0,link:function(c,d,e){c.$watch(e.ngHide,function(c){a[c?"addClass":"removeClass"](d,"ng-hide",{tempClasses:"ng-hide-animate"})})}}}],ne=Ia(function(a,c,d){a.$watch(d.ngStyle,function(a,d){d&&a!==d&&s(d,function(a,d){c.css(d,"")});a&&c.css(a)},!0)}),oe=["$animate",function(a){return{restrict:"EA",require:"ngSwitch",controller:["$scope",function(){this.cases= {}}],link:function(c,d,e,f){var g=[],k=[],h=[],l=[],m=function(a,c){return function(){a.splice(c,1)}};c.$watch(e.ngSwitch||e.on,function(c){var d,e;d=0;for(e=h.length;d<e;++d)a.cancel(h[d]);d=h.length=0;for(e=l.length;d<e;++d){var r=nb(k[d].clone);l[d].$destroy();(h[d]=a.leave(r)).then(m(h,d))}k.length=0;l.length=0;(g=f.cases["!"+c]||f.cases["?"])&&s(g,function(c){c.transclude(function(d,e){l.push(e);var f=c.element;d[d.length++]=U.createComment(" end ngSwitchWhen: ");k.push({clone:d});a.enter(d, f.parent(),f)})})})}}}],pe=Ia({transclude:"element",priority:1200,require:"^ngSwitch",multiElement:!0,link:function(a,c,d,e,f){e.cases["!"+d.ngSwitchWhen]=e.cases["!"+d.ngSwitchWhen]||[];e.cases["!"+d.ngSwitchWhen].push({transclude:f,element:c})}}),qe=Ia({transclude:"element",priority:1200,require:"^ngSwitch",multiElement:!0,link:function(a,c,d,e,f){e.cases["?"]=e.cases["?"]||[];e.cases["?"].push({transclude:f,element:c})}}),se=Ia({restrict:"EAC",link:function(a,c,d,e,f){if(!f)throw w("ngTransclude")("orphan", sa(c));f(function(a){c.empty();c.append(a)})}}),Td=["$templateCache",function(a){return{restrict:"E",terminal:!0,compile:function(c,d){"text/ng-template"==d.type&&a.put(d.id,c[0].text)}}}],Yf=w("ngOptions"),re=da({restrict:"A",terminal:!0}),Ud=["$compile","$parse",function(a,c){var d=/^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/,e={$setViewValue:y}; return{restrict:"E",require:["select","?ngModel"],controller:["$element","$scope","$attrs",function(a,c,d){var h=this,l={},m=e,p;h.databound=d.ngModel;h.init=function(a,c,d){m=a;p=d};h.addOption=function(c,d){La(c,'"option value"');l[c]=!0;m.$viewValue==c&&(a.val(c),p.parent()&&p.remove());d&&d[0].hasAttribute("selected")&&(d[0].selected=!0)};h.removeOption=function(a){this.hasOption(a)&&(delete l[a],m.$viewValue==a&&this.renderUnknownOption(a))};h.renderUnknownOption=function(c){c="? "+Ma(c)+" ?"; p.val(c);a.prepend(p);a.val(c);p.prop("selected",!0)};h.hasOption=function(a){return l.hasOwnProperty(a)};c.$on("$destroy",function(){h.renderUnknownOption=y})}],link:function(e,g,k,h){function l(a,c,d,e){d.$render=function(){var a=d.$viewValue;e.hasOption(a)?(u.parent()&&u.remove(),c.val(a),""===a&&A.prop("selected",!0)):x(a)&&A?c.val(""):e.renderUnknownOption(a)};c.on("change",function(){a.$apply(function(){u.parent()&&u.remove();d.$setViewValue(c.val())})})}function m(a,c,d){var e;d.$render=function(){var a= new ab(d.$viewValue);s(c.find("option"),function(c){c.selected=z(a.get(c.value))})};a.$watch(function(){la(e,d.$viewValue)||(e=qa(d.$viewValue),d.$render())});c.on("change",function(){a.$apply(function(){var a=[];s(c.find("option"),function(c){c.selected&&a.push(c.value)});d.$setViewValue(a)})})}function p(e,f,g){function h(a,c,d){S[y]=d;F&&(S[F]=c);return a(e,S)}function k(a){var c;if(n)if(I&&H(a)){c=new ab([]);for(var d=0;d<a.length;d++)c.put(h(I,null,a[d]),!0)}else c=new ab(a);else I&&(a=h(I,null, a));return function(d,e){var f;f=I?I:v?v:B;return n?z(c.remove(h(f,d,e))):a==h(f,d,e)}}function l(){C||(e.$$postDigest(p),C=!0)}function m(a,c,d){a[c]=a[c]||0;a[c]+=d?1:-1}function p(){C=!1;var a={"":[]},c=[""],d,l,r,t,u;r=g.$viewValue;t=K(e)||[];var y=F?Object.keys(t).sort():t,v,x,H,B,R={};u=k(r);var N=!1,T,U;P={};for(B=0;H=y.length,B<H;B++){v=B;if(F&&(v=y[B],"$"===v.charAt(0)))continue;x=t[v];d=h(J,v,x)||"";(l=a[d])||(l=a[d]=[],c.push(d));d=u(v,x);N=N||d;x=h(A,v,x);x=z(x)?x:"";U=I?I(e,S):F?y[B]: B;I&&(P[U]=v);l.push({id:U,label:x,selected:d})}n||(w||null===r?a[""].unshift({id:"",label:"",selected:!N}):N||a[""].unshift({id:"?",label:"",selected:!0}));v=0;for(y=c.length;v<y;v++){d=c[v];l=a[d];Q.length<=v?(r={element:G.clone().attr("label",d),label:l.label},t=[r],Q.push(t),f.append(r.element)):(t=Q[v],r=t[0],r.label!=d&&r.element.attr("label",r.label=d));N=null;B=0;for(H=l.length;B<H;B++)d=l[B],(u=t[B+1])?(N=u.element,u.label!==d.label&&(m(R,u.label,!1),m(R,d.label,!0),N.text(u.label=d.label)), u.id!==d.id&&N.val(u.id=d.id),N[0].selected!==d.selected&&(N.prop("selected",u.selected=d.selected),Ha&&N.prop("selected",u.selected))):(""===d.id&&w?T=w:(T=D.clone()).val(d.id).prop("selected",d.selected).attr("selected",d.selected).text(d.label),t.push(u={element:T,label:d.label,id:d.id,selected:d.selected}),m(R,d.label,!0),N?N.after(T):r.element.append(T),N=T);for(B++;t.length>B;)d=t.pop(),m(R,d.label,!1),d.element.remove();s(R,function(a,c){0<a?q.addOption(c):0>a&&q.removeOption(c)})}for(;Q.length> v;)Q.pop()[0].element.remove()}var u;if(!(u=r.match(d)))throw Yf("iexp",r,sa(f));var A=c(u[2]||u[1]),y=u[4]||u[6],x=/ as /.test(u[0])&&u[1],v=x?c(x):null,F=u[5],J=c(u[3]||""),B=c(u[2]?u[1]:y),K=c(u[7]),I=u[8]?c(u[8]):null,P={},Q=[[{element:f,label:""}]],S={};w&&(a(w)(e),w.removeClass("ng-scope"),w.remove());f.empty();f.on("change",function(){e.$apply(function(){var a=K(e)||[],c;if(n)c=[],s(f.val(),function(d){d=I?P[d]:d;c.push("?"===d?t:""===d?null:h(v?v:B,d,a[d]))});else{var d=I?P[f.val()]:f.val(); c="?"===d?t:""===d?null:h(v?v:B,d,a[d])}g.$setViewValue(c);p()})});g.$render=p;e.$watchCollection(K,l);e.$watchCollection(function(){var a=K(e),c;if(a&&H(a)){c=Array(a.length);for(var d=0,f=a.length;d<f;d++)c[d]=h(A,d,a[d])}else if(a)for(d in c={},a)a.hasOwnProperty(d)&&(c[d]=h(A,d,a[d]));return c},l);n&&e.$watchCollection(function(){return g.$modelValue},l)}if(h[1]){var q=h[0];h=h[1];var n=k.multiple,r=k.ngOptions,w=!1,A,C=!1,D=v(U.createElement("option")),G=v(U.createElement("optgroup")),u=D.clone(); k=0;for(var y=g.children(),F=y.length;k<F;k++)if(""===y[k].value){A=w=y.eq(k);break}q.init(h,w,u);n&&(h.$isEmpty=function(a){return!a||0===a.length});r?p(e,g,h):n?m(e,g,h):l(e,g,h,q)}}}}],Wd=["$interpolate",function(a){var c={addOption:y,removeOption:y};return{restrict:"E",priority:100,compile:function(d,e){if(x(e.value)){var f=a(d.text(),!0);f||e.$set("value",d.text())}return function(a,d,e){var l=d.parent(),m=l.data("$selectController")||l.parent().data("$selectController");m&&m.databound||(m=c); f?a.$watch(f,function(a,c){e.$set("value",a);c!==a&&m.removeOption(c);m.addOption(a,d)}):m.addOption(e.value,d);d.on("$destroy",function(){m.removeOption(e.value)})}}}}],Vd=da({restrict:"E",terminal:!1});N.angular.bootstrap?console.log("WARNING: Tried to load angular more than once."):(Ld(),Nd(ta),v(U).ready(function(){Hd(U,rc)}))})(window,document);!window.angular.$$csp()&&window.angular.element(document).find("head").prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}</style>');
module.exports={A:{A:{"2":"H E G C WB","260":"B A"},B:{"260":"D u g I J"},C:{"1":"0 1 2 3 4 5 6 X v Z a b c d N f M h i j k l m n o p q r s t y K","2":"UB x SB","260":"F L H E G C B A D u g I J Y O e P Q R S T U V W RB"},D:{"1":"0 1 2 3 4 5 6 h i j k l m n o p q r s t y K GB AB CB VB DB EB","2":"F L","260":"u g I J Y O e P Q R S T U V W X v Z a b c d N f M","388":"H E G C B A D"},E:{"1":"B A LB MB","2":"9 F L FB","260":"H E G C IB JB KB","388":"HB"},F:{"1":"U V W X v Z a b c d N f M h i j k l m n o p q r s t","2":"C A NB OB PB QB","260":"7 8 D I J Y O e P Q R S T TB w"},G:{"1":"A dB eB","2":"9 BB z XB","260":"G YB ZB aB bB cB"},H:{"2":"fB"},I:{"1":"K lB","2":"gB hB iB","260":"kB","388":"x F jB z"},J:{"260":"B","388":"E"},K:{"1":"M","2":"B A","260":"7 8 D w"},L:{"1":"AB"},M:{"1":"K"},N:{"2":"B","260":"A"},O:{"260":"mB"},P:{"1":"F L"},Q:{"1":"nB"},R:{"1":"oB"}},B:5,C:"File API"};
/// <binding Clean='clean' ProjectOpened='watch' /> var gulp = require("gulp"), rimraf = require("rimraf"), concat = require("gulp-concat"), cssmin = require("gulp-cssmin"), ts = require('gulp-typescript'), fs = require('fs'); // https://www.npmjs.com/package/gulp-typescript // http://weblogs.asp.net/dwahlin/creating-a-typescript-workflow-with-gulp var tsProject = ts.createProject('tsconfig.json'); var paths = { webroot: "./wwwroot/" }; paths.ts = paths.webroot + "{ts,js}/**/*.ts"; paths.css = paths.webroot + "css/**/*.css"; paths.minCss = paths.webroot + "css/**/*.min.css"; paths.concatCssDest = paths.webroot + "css/site.min.css"; gulp.task("clean", function (cb) { rimraf(paths.concatCssDest, cb); }); gulp.task('build:lib', function () { function getNPMDependencies() { var buffer, packages, keys; buffer = fs.readFileSync('package.json'); packages = JSON.parse(buffer.toString()); keys = []; for (var key in packages.dependencies) { keys.push(key); } return keys; } function copyNodeModule(name) { gulp.src('node_modules/' + name + '/**/*') .pipe(gulp.dest('wwwroot/lib/' + name + '/')); }; var dependencies = getNPMDependencies(); for (var i in dependencies) { copyNodeModule(dependencies[i]) } }) gulp.task('build:ts', function () { var tsResult = tsProject.src() .pipe(tsProject()) .js.pipe(gulp.dest(paths.webroot)); }); gulp.task("build:css", function () { return gulp.src([paths.css, "!" + paths.minCss]) .pipe(concat(paths.concatCssDest)) .pipe(cssmin()) .pipe(gulp.dest(".")); }); gulp.task("build", ["build:lib", "build:ts", "build:css"]); gulp.task("min", ["build"]); gulp.task("watch", function () { gulp.watch([paths.css, paths.ts], ["build"]); });
const bluebird = require('bluebird'); const crypto = bluebird.promisifyAll(require('crypto')); const nodemailer = require('nodemailer'); const passport = require('passport'); const User = require('../models/User'); /** * GET /login * Login page. */ exports.getLogin = (req, res) => { if (req.user) { return res.redirect('/'); } res.render('account/login', { title: 'Login' }); }; /** * POST /login * Sign in using email and password. */ exports.postLogin = (req, res, next) => { req.assert('email', 'Email is not valid').isEmail(); req.assert('password', 'Password cannot be blank').notEmpty(); req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/login'); } passport.authenticate('local', (err, user, info) => { if (err) { return next(err); } if (!user) { req.flash('errors', info); return res.redirect('/login'); } req.logIn(user, (err) => { if (err) { return next(err); } req.flash('success', { msg: 'Success! You are logged in.' }); res.redirect(req.session.returnTo || '/'); }); })(req, res, next); }; /** * GET /logout * Log out. */ exports.logout = (req, res) => { req.logout(); res.redirect('/'); }; /** * GET /signup * Signup page. */ exports.getSignup = (req, res) => { if (req.user) { return res.redirect('/'); } res.render('account/signup', { title: 'Create Account' }); }; /** * POST /signup * Create a new local account. */ exports.postSignup = (req, res, next) => { req.assert('email', 'Email is not valid').isEmail(); req.assert('password', 'Password must be at least 4 characters long').len(4); req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password); req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/signup'); } const user = new User({ email: req.body.email, password: req.body.password }); User.findOne({ email: req.body.email }, (err, existingUser) => { if (err) { return next(err); } if (existingUser) { req.flash('errors', { msg: 'Account with that email address already exists.' }); return res.redirect('/signup'); } user.save((err) => { if (err) { return next(err); } req.logIn(user, (err) => { if (err) { return next(err); } res.redirect('/'); }); }); }); }; /** * GET /account * Profile page. */ exports.getAccount = (req, res) => { res.render('account/profile', { title: 'Account Management' }); }; /** * POST /account/profile * Update profile information. */ exports.postUpdateProfile = (req, res, next) => { req.assert('email', 'Please enter a valid email address.').isEmail(); req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/account'); } User.findById(req.user.id, (err, user) => { if (err) { return next(err); } user.email = req.body.email || ''; user.profile.name = req.body.name || ''; user.profile.gender = req.body.gender || ''; user.profile.location = req.body.location || ''; user.profile.website = req.body.website || ''; user.save((err) => { if (err) { if (err.code === 11000) { req.flash('errors', { msg: 'The email address you have entered is already associated with an account.' }); return res.redirect('/account'); } return next(err); } req.flash('success', { msg: 'Profile information has been updated.' }); res.redirect('/account'); }); }); }; /** * POST /account/password * Update current password. */ exports.postUpdatePassword = (req, res, next) => { req.assert('password', 'Password must be at least 4 characters long').len(4); req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/account'); } User.findById(req.user.id, (err, user) => { if (err) { return next(err); } user.password = req.body.password; user.save((err) => { if (err) { return next(err); } req.flash('success', { msg: 'Password has been changed.' }); res.redirect('/account'); }); }); }; /** * POST /account/delete * Delete user account. */ exports.postDeleteAccount = (req, res, next) => { User.remove({ _id: req.user.id }, (err) => { if (err) { return next(err); } req.logout(); req.flash('info', { msg: 'Your account has been deleted.' }); res.redirect('/'); }); }; /** * GET /account/unlink/:provider * Unlink OAuth provider. */ exports.getOauthUnlink = (req, res, next) => { const provider = req.params.provider; User.findById(req.user.id, (err, user) => { if (err) { return next(err); } user[provider] = undefined; user.tokens = user.tokens.filter(token => token.kind !== provider); user.save((err) => { if (err) { return next(err); } req.flash('info', { msg: `${provider} account has been unlinked.` }); res.redirect('/account'); }); }); }; /** * GET /reset/:token * Reset Password page. */ exports.getReset = (req, res, next) => { if (req.isAuthenticated()) { return res.redirect('/'); } User .findOne({ passwordResetToken: req.params.token }) .where('passwordResetExpires').gt(Date.now()) .exec((err, user) => { if (err) { return next(err); } if (!user) { req.flash('errors', { msg: 'Password reset token is invalid or has expired.' }); return res.redirect('/forgot'); } res.render('account/reset', { title: 'Password Reset' }); }); }; /** * POST /reset/:token * Process the reset password request. */ exports.postReset = (req, res, next) => { req.assert('password', 'Password must be at least 4 characters long.').len(4); req.assert('confirm', 'Passwords must match.').equals(req.body.password); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('back'); } const resetPassword = () => User .findOne({ passwordResetToken: req.params.token }) .where('passwordResetExpires').gt(Date.now()) .then((user) => { if (!user) { req.flash('errors', { msg: 'Password reset token is invalid or has expired.' }); return res.redirect('back'); } user.password = req.body.password; user.passwordResetToken = undefined; user.passwordResetExpires = undefined; return user.save().then(() => new Promise((resolve, reject) => { req.logIn(user, (err) => { if (err) { return reject(err); } resolve(user); }); })); }); const sendResetPasswordEmail = (user) => { if (!user) { return; } const transporter = nodemailer.createTransport({ service: 'SendGrid', auth: { user: process.env.SENDGRID_USER, pass: process.env.SENDGRID_PASSWORD } }); const mailOptions = { to: user.email, from: 'hackathon@starter.com', subject: 'Your Hackathon Starter password has been changed', text: `Hello,\n\nThis is a confirmation that the password for your account ${user.email} has just been changed.\n` }; return transporter.sendMail(mailOptions) .then(() => { req.flash('success', { msg: 'Success! Your password has been changed.' }); }); }; resetPassword() .then(sendResetPasswordEmail) .then(() => { if (!res.finished) res.redirect('/'); }) .catch(err => next(err)); }; /** * GET /forgot * Forgot Password page. */ exports.getForgot = (req, res) => { if (req.isAuthenticated()) { return res.redirect('/'); } res.render('account/forgot', { title: 'Forgot Password' }); }; /** * POST /forgot * Create a random token, then the send user an email with a reset link. */ exports.postForgot = (req, res, next) => { req.assert('email', 'Please enter a valid email address.').isEmail(); req.sanitize('email').normalizeEmail({ gmail_remove_dots: false }); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/forgot'); } const createRandomToken = crypto .randomBytesAsync(16) .then(buf => buf.toString('hex')); const setRandomToken = token => User .findOne({ email: req.body.email }) .then((user) => { if (!user) { req.flash('errors', { msg: 'Account with that email address does not exist.' }); } else { user.passwordResetToken = token; user.passwordResetExpires = Date.now() + 3600000; // 1 hour user = user.save(); } return user; }); const sendForgotPasswordEmail = (user) => { if (!user) { return; } const token = user.passwordResetToken; const transporter = nodemailer.createTransport({ service: 'SendGrid', auth: { user: process.env.SENDGRID_USER, pass: process.env.SENDGRID_PASSWORD } }); const mailOptions = { to: user.email, from: 'hackathon@starter.com', subject: 'Reset your password on Hackathon Starter', text: `You are receiving this email because you (or someone else) have requested the reset of the password for your account.\n\n Please click on the following link, or paste this into your browser to complete the process:\n\n http://${req.headers.host}/reset/${token}\n\n If you did not request this, please ignore this email and your password will remain unchanged.\n` }; return transporter.sendMail(mailOptions) .then(() => { req.flash('info', { msg: `An e-mail has been sent to ${user.email} with further instructions.` }); }); }; createRandomToken .then(setRandomToken) .then(sendForgotPasswordEmail) .then(() => res.redirect('/forgot')) .catch(next); };
/** * mixin authorization * * Copyright 2012 Cloud9 IDE, Inc. * * This product includes software developed by * Cloud9 IDE, Inc (http://c9.io). * * Author: Mike de Boer <info@mikedeboer.nl> **/ "use strict"; var error = require("./../../error"); var Util = require("./../../util"); var authorization = module.exports = { authorization: {} }; (function() { /** section: github * authorization#getAll(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - page (Number): Optional. Page number of the results to fetch. Validation rule: ` ^[0-9]+$ `. * - per_page (Number): Optional. A custom page size up to 100. Default is 30. Validation rule: ` ^[0-9]+$ `. * * https://developer.github.com/v3/oauth_authorizations/#list-your-authorizations **/ this.getAll = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data; var contentType = res.headers["content-type"]; if (contentType && contentType.indexOf("application/json") !== -1) ret = JSON.parse(ret); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (typeof ret == "object") { if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); } if (callback) callback(null, ret); }); }; /** section: github * authorization#get(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - id (String): Required. * * https://developer.github.com/v3/oauth_authorizations/#get-a-single-authorization **/ this.get = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data; var contentType = res.headers["content-type"]; if (contentType && contentType.indexOf("application/json") !== -1) ret = JSON.parse(ret); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (typeof ret == "object") { if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); } if (callback) callback(null, ret); }); }; /** section: github * authorization#create(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - scopes (Array): Optional. A list of scopes that this authorization is in. * - note (String): Optional. A note to remind you what the OAuth token is for. * - note_url (String): Optional. A URL to remind you what app the OAuth token is for. * * https://developer.github.com/v3/oauth_authorizations/#create-a-new-authorization **/ this.create = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data; var contentType = res.headers["content-type"]; if (contentType && contentType.indexOf("application/json") !== -1) ret = JSON.parse(ret); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (typeof ret == "object") { if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); } if (callback) callback(null, ret); }); }; /** section: github * authorization#update(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - id (String): Required. * - scopes (Array): Optional. A list of scopes that this authorization is in. * - add_scopes (Array): Optional. A list of scopes to add to this authorization. * - remove_scopes (Array): Optional. A list of scopes to remove from this authorization. * - note (String): Optional. A note to remind you what the OAuth token is for. * - note_url (String): Optional. A URL to remind you what app the OAuth token is for. * * https://developer.github.com/v3/oauth_authorizations/#update-an-existing-authorization **/ this.update = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data; var contentType = res.headers["content-type"]; if (contentType && contentType.indexOf("application/json") !== -1) ret = JSON.parse(ret); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (typeof ret == "object") { if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); } if (callback) callback(null, ret); }); }; /** section: github * authorization#delete(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - id (String): Required. * * https://developer.github.com/v3/oauth_authorizations/#delete-an-authorization **/ this.delete = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data; var contentType = res.headers["content-type"]; if (contentType && contentType.indexOf("application/json") !== -1) ret = JSON.parse(ret); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (typeof ret == "object") { if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); } if (callback) callback(null, ret); }); }; }).call(authorization.authorization);
/* Copyright (c) 2012-2013 LevelUP contributors * See list at <https://github.com/rvagg/node-levelup#contributing> * MIT +no-false-attribs License <https://github.com/rvagg/node-levelup/blob/master/LICENSE> */ var errors = require('../lib/errors.js') , async = require('async') , common = require('./common') , assert = require('referee').assert , refute = require('referee').refute , buster = require('bustermove') buster.testCase('get() / put() / del()', { 'setUp': common.commonSetUp , 'tearDown': common.commonTearDown , 'Simple operations': { 'get() on empty database causes error': function (done) { this.openTestDatabase(function (db) { db.get('undefkey', function (err, value) { refute(value) assert.isInstanceOf(err, Error) assert.isInstanceOf(err, errors.LevelUPError) assert.isInstanceOf(err, errors.NotFoundError) assert(err.notFound === true, 'err.notFound is `true`') assert.equals(err.status, 404, 'err.status is 404') assert.match(err, '[undefkey]') done() }) }) } , 'put() and get() simple string key/value pairs': function (done) { this.openTestDatabase(function (db) { db.put('some key', 'some value stored in the database', function (err) { refute(err) db.get('some key', function (err, value) { refute(err) assert.equals(value, 'some value stored in the database') done() }) }) }) } , 'del() on empty database doesn\'t cause error': function (done) { this.openTestDatabase(function (db) { db.del('undefkey', function (err) { refute(err) done() }) }) } , 'del() works on real entries': function (done) { this.openTestDatabase(function (db) { async.series( [ function (callback) { async.forEach( ['foo', 'bar', 'baz'] , function (key, callback) { db.put(key, 1 + Math.random(), callback) } , callback ) } , function (callback) { db.del('bar', callback) } , function (callback) { async.forEach( ['foo', 'bar', 'baz'] , function (key, callback) { db.get(key, function (err, value) { // we should get foo & baz but not bar if (key == 'bar') { assert(err) refute(value) } else { refute(err) assert(value) } callback() }) } , callback ) } ] , done ) }) } } , 'test get() throwables': function (done) { this.openTestDatabase(function (db) { assert.exception( db.get.bind(db) , { name: 'ReadError', message: 'get() requires key and callback arguments' } , 'no-arg get() throws' ) assert.exception( db.get.bind(db, 'foo') , { name: 'ReadError', message: 'get() requires key and callback arguments' } , 'callback-less, 1-arg get() throws' ) assert.exception( db.get.bind(db, 'foo', {}) , { name: 'ReadError', message: 'get() requires key and callback arguments' } , 'callback-less, 2-arg get() throws' ) done() }) } , 'test put() throwables': function (done) { this.openTestDatabase(function (db) { assert.exception( db.put.bind(db) , { name: 'WriteError', message: 'put() requires key and value arguments' } , 'no-arg put() throws' ) assert.exception( db.put.bind(db, 'foo') , { name: 'WriteError', message: 'put() requires key and value arguments' } , 'callback-less, 1-arg put() throws' ) done() }) } , 'test del() throwables': function (done) { this.openTestDatabase(function (db) { assert.exception( db.del.bind(db) , { name: 'WriteError', message: 'del() requires a key argument' } , 'no-arg del() throws' ) done() }) } , 'test approximateSize() throwables': function (done) { this.openTestDatabase(function (db) { assert.exception( db.approximateSize.bind(db) , { name: 'ReadError', message: 'approximateSize() requires start, end and callback arguments' } , 'no-arg approximateSize() throws' ) assert.exception( db.approximateSize.bind(db, 'foo') , { name: 'ReadError', message: 'approximateSize() requires start, end and callback arguments' } , 'callback-less, 1-arg approximateSize() throws' ) assert.exception( db.approximateSize.bind(db, 'foo', 'bar') , { name: 'ReadError', message: 'approximateSize() requires start, end and callback arguments' } , 'callback-less, 2-arg approximateSize() throws' ) assert.exception( db.approximateSize.bind(db, 'foo', 'bar', {}) , { name: 'ReadError', message: 'approximateSize() requires start, end and callback arguments' } , 'callback-less, 3-arg approximateSize(), no cb throws' ) done() }) } })
describe('timepicker directive', function () { var $rootScope, element; beforeEach(module('ui.bootstrap.timepicker')); beforeEach(module('template/timepicker/timepicker.html')); beforeEach(inject(function(_$compile_, _$rootScope_) { $compile = _$compile_; $rootScope = _$rootScope_; $rootScope.time = newTime(14, 40); element = $compile('<timepicker ng-model="$parent.time"></timepicker>')($rootScope); $rootScope.$digest(); })); function newTime(hours, minutes) { var time = new Date(); time.setHours(hours); time.setMinutes(minutes); return time; } function getTimeState(withoutMeridian) { var inputs = element.find('input'); var state = []; for (var i = 0; i < 2; i ++) { state.push(inputs.eq(i).val()); } if ( withoutMeridian !== true ) { state.push( getMeridianButton().text() ); } return state; } function getModelState() { return [ $rootScope.time.getHours(), $rootScope.time.getMinutes() ]; } function getArrow(isUp, tdIndex) { return element.find('tr').eq( (isUp) ? 0 : 2 ).find('td').eq( tdIndex ).find('a').eq(0); } function getHoursButton(isUp) { return getArrow(isUp, 0); } function getMinutesButton(isUp) { return getArrow(isUp, 2); } function getMeridianButton() { return element.find('button').eq(0); } function doClick(button, n) { for (var i = 0, max = n || 1; i < max; i++) { button.click(); $rootScope.$digest(); } } function wheelThatMouse(delta) { var e = $.Event('mousewheel'); e.wheelDelta = delta; return e; } function wheelThatOtherMouse(delta) { var e = $.Event('wheel'); e.deltaY = delta; return e; } it('contains three row & three input elements', function() { expect(element.find('tr').length).toBe(3); expect(element.find('input').length).toBe(2); expect(element.find('button').length).toBe(1); }); it('has initially the correct time & meridian', function() { expect(getTimeState()).toEqual(['02', '40', 'PM']); expect(getModelState()).toEqual([14, 40]); }); it('has `selected` current time when model is initially cleared', function() { $rootScope.time = null; element = $compile('<timepicker ng-model="$parent.time"></timepicker>')($rootScope); $rootScope.$digest(); expect($rootScope.time).toBe(null); expect(getTimeState()).not.toEqual(['', '', '']); }); it('changes inputs when model changes value', function() { $rootScope.time = newTime(11, 50); $rootScope.$digest(); expect(getTimeState()).toEqual(['11', '50', 'AM']); expect(getModelState()).toEqual([11, 50]); $rootScope.time = newTime(16, 40); $rootScope.$digest(); expect(getTimeState()).toEqual(['04', '40', 'PM']); expect(getModelState()).toEqual([16, 40]); }); it('increases / decreases hours when arrows are clicked', function() { var up = getHoursButton(true); var down = getHoursButton(false); doClick(up); expect(getTimeState()).toEqual(['03', '40', 'PM']); expect(getModelState()).toEqual([15, 40]); doClick(down); expect(getTimeState()).toEqual(['02', '40', 'PM']); expect(getModelState()).toEqual([14, 40]); doClick(down); expect(getTimeState()).toEqual(['01', '40', 'PM']); expect(getModelState()).toEqual([13, 40]); }); it('increase / decreases minutes by default step when arrows are clicked', function() { var up = getMinutesButton(true); var down = getMinutesButton(false); doClick(up); expect(getTimeState()).toEqual(['02', '41', 'PM']); expect(getModelState()).toEqual([14, 41]); doClick(down); expect(getTimeState()).toEqual(['02', '40', 'PM']); expect(getModelState()).toEqual([14, 40]); doClick(down); expect(getTimeState()).toEqual(['02', '39', 'PM']); expect(getModelState()).toEqual([14, 39]); }); it('toggles meridian when arrows are clicked', function() { var button = getMeridianButton(); doClick(button); expect(getTimeState()).toEqual(['02', '40', 'AM']); expect(getModelState()).toEqual([2, 40]); doClick(button); expect(getTimeState()).toEqual(['02', '40', 'PM']); expect(getModelState()).toEqual([14, 40]); doClick(button); expect(getTimeState()).toEqual(['02', '40', 'AM']); expect(getModelState()).toEqual([2, 40]); }); it('has minutes "connected" to hours', function() { var up = getMinutesButton(true); var down = getMinutesButton(false); doClick(up, 10); expect(getTimeState()).toEqual(['02', '50', 'PM']); expect(getModelState()).toEqual([14, 50]); doClick(up, 10); expect(getTimeState()).toEqual(['03', '00', 'PM']); expect(getModelState()).toEqual([15, 0]); doClick(up, 10); $rootScope.$digest(); expect(getTimeState()).toEqual(['03', '10', 'PM']); expect(getModelState()).toEqual([15, 10]); doClick(down, 10); $rootScope.$digest(); expect(getTimeState()).toEqual(['03', '00', 'PM']); expect(getModelState()).toEqual([15, 0]); doClick(down, 10); $rootScope.$digest(); expect(getTimeState()).toEqual(['02', '50', 'PM']); expect(getModelState()).toEqual([14, 50]); }); it('has hours "connected" to meridian', function() { var up = getHoursButton(true); var down = getHoursButton(false); // AM -> PM $rootScope.time = newTime(11, 0); $rootScope.$digest(); expect(getTimeState()).toEqual(['11', '00', 'AM']); expect(getModelState()).toEqual([11, 0]); doClick(up); expect(getTimeState()).toEqual(['12', '00', 'PM']); expect(getModelState()).toEqual([12, 0]); doClick(up); expect(getTimeState()).toEqual(['01', '00', 'PM']); expect(getModelState()).toEqual([13, 0]); doClick(down); expect(getTimeState()).toEqual(['12', '00', 'PM']); expect(getModelState()).toEqual([12, 0]); doClick(down); expect(getTimeState()).toEqual(['11', '00', 'AM']); expect(getModelState()).toEqual([11, 0]); // PM -> AM $rootScope.time = newTime(23, 0); $rootScope.$digest(); expect(getTimeState()).toEqual(['11', '00', 'PM']); expect(getModelState()).toEqual([23, 0]); doClick(up); expect(getTimeState()).toEqual(['12', '00', 'AM']); expect(getModelState()).toEqual([0, 0]); doClick(up); expect(getTimeState()).toEqual(['01', '00', 'AM']); expect(getModelState()).toEqual([01, 0]); doClick(down); expect(getTimeState()).toEqual(['12', '00', 'AM']); expect(getModelState()).toEqual([0, 0]); doClick(down); expect(getTimeState()).toEqual(['11', '00', 'PM']); expect(getModelState()).toEqual([23, 0]); }); it('changes only the time part when hours change', function() { $rootScope.time = newTime(23, 50); $rootScope.$digest(); var date = $rootScope.time.getDate(); var up = getHoursButton(true); doClick(up); expect(getTimeState()).toEqual(['12', '50', 'AM']); expect(getModelState()).toEqual([0, 50]); expect(date).toEqual($rootScope.time.getDate()); }); it('changes only the time part when minutes change', function() { element = $compile('<timepicker ng-model="$parent.time" minute-step="15"></timepicker>')($rootScope); $rootScope.time = newTime(0, 0); $rootScope.$digest(); var date = $rootScope.time.getDate(); var up = getMinutesButton(true); doClick(up, 2); expect(getTimeState()).toEqual(['12', '30', 'AM']); expect(getModelState()).toEqual([0, 30]); expect(date).toEqual($rootScope.time.getDate()); var down = getMinutesButton(false); doClick(down, 2); expect(getTimeState()).toEqual(['12', '00', 'AM']); expect(getModelState()).toEqual([0, 0]); expect(date).toEqual($rootScope.time.getDate()); doClick(down, 2); expect(getTimeState()).toEqual(['11', '30', 'PM']); expect(getModelState()).toEqual([23, 30]); expect(date).toEqual($rootScope.time.getDate()); }); it('responds properly on "mousewheel" events', function() { var inputs = element.find('input'); var hoursEl = inputs.eq(0), minutesEl = inputs.eq(1); var upMouseWheelEvent = wheelThatMouse(1); var downMouseWheelEvent = wheelThatMouse(-1); expect(getTimeState()).toEqual(['02', '40', 'PM']); expect(getModelState()).toEqual([14, 40]); // UP hoursEl.trigger( upMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['03', '40', 'PM']); expect(getModelState()).toEqual([15, 40]); hoursEl.trigger( upMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['04', '40', 'PM']); expect(getModelState()).toEqual([16, 40]); minutesEl.trigger( upMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['04', '41', 'PM']); expect(getModelState()).toEqual([16, 41]); minutesEl.trigger( upMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['04', '42', 'PM']); expect(getModelState()).toEqual([16, 42]); // DOWN minutesEl.trigger( downMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['04', '41', 'PM']); expect(getModelState()).toEqual([16, 41]); minutesEl.trigger( downMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['04', '40', 'PM']); expect(getModelState()).toEqual([16, 40]); hoursEl.trigger( downMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['03', '40', 'PM']); expect(getModelState()).toEqual([15, 40]); hoursEl.trigger( downMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['02', '40', 'PM']); expect(getModelState()).toEqual([14, 40]); }); it('responds properly on "wheel" events', function() { var inputs = element.find('input'); var hoursEl = inputs.eq(0), minutesEl = inputs.eq(1); var upMouseWheelEvent = wheelThatOtherMouse(-1); var downMouseWheelEvent = wheelThatOtherMouse(1); expect(getTimeState()).toEqual(['02', '40', 'PM']); expect(getModelState()).toEqual([14, 40]); // UP hoursEl.trigger( upMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['03', '40', 'PM']); expect(getModelState()).toEqual([15, 40]); hoursEl.trigger( upMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['04', '40', 'PM']); expect(getModelState()).toEqual([16, 40]); minutesEl.trigger( upMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['04', '41', 'PM']); expect(getModelState()).toEqual([16, 41]); minutesEl.trigger( upMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['04', '42', 'PM']); expect(getModelState()).toEqual([16, 42]); // DOWN minutesEl.trigger( downMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['04', '41', 'PM']); expect(getModelState()).toEqual([16, 41]); minutesEl.trigger( downMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['04', '40', 'PM']); expect(getModelState()).toEqual([16, 40]); hoursEl.trigger( downMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['03', '40', 'PM']); expect(getModelState()).toEqual([15, 40]); hoursEl.trigger( downMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['02', '40', 'PM']); expect(getModelState()).toEqual([14, 40]); }); describe('attributes', function () { beforeEach(function() { $rootScope.hstep = 2; $rootScope.mstep = 30; $rootScope.time = newTime(14, 0); element = $compile('<timepicker ng-model="$parent.time" hour-step="hstep" minute-step="mstep"></timepicker>')($rootScope); $rootScope.$digest(); }); it('increases / decreases hours by configurable step', function() { var up = getHoursButton(true); var down = getHoursButton(false); expect(getTimeState()).toEqual(['02', '00', 'PM']); expect(getModelState()).toEqual([14, 0]); doClick(up); expect(getTimeState()).toEqual(['04', '00', 'PM']); expect(getModelState()).toEqual([16, 0]); doClick(down); expect(getTimeState()).toEqual(['02', '00', 'PM']); expect(getModelState()).toEqual([14, 0]); doClick(down); expect(getTimeState()).toEqual(['12', '00', 'PM']); expect(getModelState()).toEqual([12, 0]); // Change step $rootScope.hstep = 3; $rootScope.$digest(); doClick(up); expect(getTimeState()).toEqual(['03', '00', 'PM']); expect(getModelState()).toEqual([15, 0]); doClick(down); expect(getTimeState()).toEqual(['12', '00', 'PM']); expect(getModelState()).toEqual([12, 0]); }); it('increases / decreases minutes by configurable step', function() { var up = getMinutesButton(true); var down = getMinutesButton(false); doClick(up); expect(getTimeState()).toEqual(['02', '30', 'PM']); expect(getModelState()).toEqual([14, 30]); doClick(up); expect(getTimeState()).toEqual(['03', '00', 'PM']); expect(getModelState()).toEqual([15, 0]); doClick(down); expect(getTimeState()).toEqual(['02', '30', 'PM']); expect(getModelState()).toEqual([14, 30]); doClick(down); expect(getTimeState()).toEqual(['02', '00', 'PM']); expect(getModelState()).toEqual([14, 0]); // Change step $rootScope.mstep = 15; $rootScope.$digest(); doClick(up); expect(getTimeState()).toEqual(['02', '15', 'PM']); expect(getModelState()).toEqual([14, 15]); doClick(down); expect(getTimeState()).toEqual(['02', '00', 'PM']); expect(getModelState()).toEqual([14, 0]); doClick(down); expect(getTimeState()).toEqual(['01', '45', 'PM']); expect(getModelState()).toEqual([13, 45]); }); it('responds properly on "mousewheel" events with configurable steps', function() { var inputs = element.find('input'); var hoursEl = inputs.eq(0), minutesEl = inputs.eq(1); var upMouseWheelEvent = wheelThatMouse(1); var downMouseWheelEvent = wheelThatMouse(-1); expect(getTimeState()).toEqual(['02', '00', 'PM']); expect(getModelState()).toEqual([14, 0]); // UP hoursEl.trigger( upMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['04', '00', 'PM']); expect(getModelState()).toEqual([16, 0]); minutesEl.trigger( upMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['04', '30', 'PM']); expect(getModelState()).toEqual([16, 30]); // DOWN minutesEl.trigger( downMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['04', '00', 'PM']); expect(getModelState()).toEqual([16, 0]); hoursEl.trigger( downMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['02', '00', 'PM']); expect(getModelState()).toEqual([14, 0]); }); it('responds properly on "wheel" events with configurable steps', function() { var inputs = element.find('input'); var hoursEl = inputs.eq(0), minutesEl = inputs.eq(1); var upMouseWheelEvent = wheelThatOtherMouse(-1); var downMouseWheelEvent = wheelThatOtherMouse(1); expect(getTimeState()).toEqual(['02', '00', 'PM']); expect(getModelState()).toEqual([14, 0]); // UP hoursEl.trigger( upMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['04', '00', 'PM']); expect(getModelState()).toEqual([16, 0]); minutesEl.trigger( upMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['04', '30', 'PM']); expect(getModelState()).toEqual([16, 30]); // DOWN minutesEl.trigger( downMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['04', '00', 'PM']); expect(getModelState()).toEqual([16, 0]); hoursEl.trigger( downMouseWheelEvent ); $rootScope.$digest(); expect(getTimeState()).toEqual(['02', '00', 'PM']); expect(getModelState()).toEqual([14, 0]); }); it('can handle strings as steps', function() { var upHours = getHoursButton(true); var upMinutes = getMinutesButton(true); expect(getTimeState()).toEqual(['02', '00', 'PM']); expect(getModelState()).toEqual([14, 0]); $rootScope.hstep = '4'; $rootScope.mstep = '20'; $rootScope.$digest(); doClick(upHours); expect(getTimeState()).toEqual(['06', '00', 'PM']); expect(getModelState()).toEqual([18, 0]); doClick(upMinutes); expect(getTimeState()).toEqual(['06', '20', 'PM']); expect(getModelState()).toEqual([18, 20]); }); }); describe('12 / 24 hour mode', function () { beforeEach(function() { $rootScope.meridian = false; $rootScope.time = newTime(14, 10); element = $compile('<timepicker ng-model="$parent.time" show-meridian="meridian"></timepicker>')($rootScope); $rootScope.$digest(); }); function getMeridianTd() { return element.find('tr').eq(1).find('td').eq(3); } it('initially displays correct time when `show-meridian` is false', function() { expect(getTimeState(true)).toEqual(['14', '10']); expect(getModelState()).toEqual([14, 10]); expect(getMeridianTd().css('display')).toBe('none'); }); it('toggles correctly between different modes', function() { expect(getTimeState(true)).toEqual(['14', '10']); $rootScope.meridian = true; $rootScope.$digest(); expect(getTimeState()).toEqual(['02', '10', 'PM']); expect(getModelState()).toEqual([14, 10]); expect(getMeridianTd().css('display')).not.toBe('none'); $rootScope.meridian = false; $rootScope.$digest(); expect(getTimeState(true)).toEqual(['14', '10']); expect(getModelState()).toEqual([14, 10]); expect(getMeridianTd().css('display')).toBe('none'); }); it('handles correctly initially empty model on parent element', function() { $rootScope.time = null; element = $compile('<span ng-model="time"><timepicker show-meridian="meridian"></timepicker></span>')($rootScope); $rootScope.$digest(); expect($rootScope.time).toBe(null); }); }); describe('setting timepickerConfig steps', function() { var originalConfig = {}; beforeEach(inject(function(_$compile_, _$rootScope_, timepickerConfig) { angular.extend(originalConfig, timepickerConfig); timepickerConfig.hourStep = 2; timepickerConfig.minuteStep = 10; timepickerConfig.showMeridian = false; element = $compile('<timepicker ng-model="$parent.time"></timepicker>')($rootScope); $rootScope.$digest(); })); afterEach(inject(function(timepickerConfig) { // return it to the original state angular.extend(timepickerConfig, originalConfig); })); it('does not affect the initial value', function () { expect(getTimeState(true)).toEqual(['14', '40']); expect(getModelState()).toEqual([14, 40]); }); it('increases / decreases hours with configured step', function() { var up = getHoursButton(true); var down = getHoursButton(false); doClick(up, 2); expect(getTimeState(true)).toEqual(['18', '40']); expect(getModelState()).toEqual([18, 40]); doClick(down, 3); expect(getTimeState(true)).toEqual(['12', '40']); expect(getModelState()).toEqual([12, 40]); }); it('increases / decreases minutes with configured step', function() { var up = getMinutesButton(true); var down = getMinutesButton(false); doClick(up); expect(getTimeState(true)).toEqual(['14', '50']); expect(getModelState()).toEqual([14, 50]); doClick(down, 3); expect(getTimeState(true)).toEqual(['14', '20']); expect(getModelState()).toEqual([14, 20]); }); }); describe('setting timepickerConfig meridian labels', function() { var originalConfig = {}; beforeEach(inject(function(_$compile_, _$rootScope_, timepickerConfig) { angular.extend(originalConfig, timepickerConfig); timepickerConfig.meridians = ['π.μ.', 'μ.μ.']; timepickerConfig.showMeridian = true; element = $compile('<timepicker ng-model="$parent.time"></timepicker>')($rootScope); $rootScope.$digest(); })); afterEach(inject(function(timepickerConfig) { // return it to the original state angular.extend(timepickerConfig, originalConfig); })); it('displays correctly', function () { expect(getTimeState()).toEqual(['02', '40', 'μ.μ.']); expect(getModelState()).toEqual([14, 40]); }); it('toggles correctly', function () { $rootScope.time = newTime(2, 40); $rootScope.$digest(); expect(getTimeState()).toEqual(['02', '40', 'π.μ.']); expect(getModelState()).toEqual([2, 40]); }); }); describe('user input validation', function () { var changeInputValueTo; beforeEach(inject(function($sniffer) { changeInputValueTo = function (inputEl, value) { inputEl.val(value); inputEl.trigger($sniffer.hasEvent('input') ? 'input' : 'change'); $rootScope.$digest(); }; })); function getHoursInputEl() { return element.find('input').eq(0); } function getMinutesInputEl() { return element.find('input').eq(1); } it('has initially the correct time & meridian', function() { expect(getTimeState()).toEqual(['02', '40', 'PM']); expect(getModelState()).toEqual([14, 40]); }); it('updates hours & pads on input change & pads on blur', function() { var el = getHoursInputEl(); changeInputValueTo(el, 5); expect(getTimeState()).toEqual(['5', '40', 'PM']); expect(getModelState()).toEqual([17, 40]); el.blur(); expect(getTimeState()).toEqual(['05', '40', 'PM']); expect(getModelState()).toEqual([17, 40]); }); it('updates minutes & pads on input change & pads on blur', function() { var el = getMinutesInputEl(); changeInputValueTo(el, 9); expect(getTimeState()).toEqual(['02', '9', 'PM']); expect(getModelState()).toEqual([14, 9]); el.blur(); expect(getTimeState()).toEqual(['02', '09', 'PM']); expect(getModelState()).toEqual([14, 9]); }); it('clears model when input hours is invalid & alerts the UI', function() { var el = getHoursInputEl(); changeInputValueTo(el, 'pizza'); expect($rootScope.time).toBe(null); expect(el.parent().hasClass('error')).toBe(true); expect(element.hasClass('ng-invalid-time')).toBe(true); changeInputValueTo(el, 8); el.blur(); $rootScope.$digest(); expect(getTimeState()).toEqual(['08', '40', 'PM']); expect(getModelState()).toEqual([20, 40]); expect(el.parent().hasClass('error')).toBe(false); expect(element.hasClass('ng-invalid-time')).toBe(false); }); it('clears model when input minutes is invalid & alerts the UI', function() { var el = getMinutesInputEl(); changeInputValueTo(el, 'pizza'); expect($rootScope.time).toBe(null); expect(el.parent().hasClass('error')).toBe(true); expect(element.hasClass('ng-invalid-time')).toBe(true); changeInputValueTo(el, 22); expect(getTimeState()).toEqual(['02', '22', 'PM']); expect(getModelState()).toEqual([14, 22]); expect(el.parent().hasClass('error')).toBe(false); expect(element.hasClass('ng-invalid-time')).toBe(false); }); it('handles 12/24H mode change', function() { $rootScope.meridian = true; element = $compile('<timepicker ng-model="$parent.time" show-meridian="meridian"></timepicker>')($rootScope); $rootScope.$digest(); var el = getHoursInputEl(); changeInputValueTo(el, '16'); expect($rootScope.time).toBe(null); expect(el.parent().hasClass('error')).toBe(true); expect(element.hasClass('ng-invalid-time')).toBe(true); $rootScope.meridian = false; $rootScope.$digest(); expect(getTimeState(true)).toEqual(['16', '40']); expect(getModelState()).toEqual([16, 40]); expect(element.hasClass('ng-invalid-time')).toBe(false); }); }); describe('when model is not a Date', function() { beforeEach(inject(function() { eelement = $compile('<timepicker ng-model="$parent.time"></timepicker>')($rootScope); })); it('should not be invalid when the model is null', function() { $rootScope.time = null; $rootScope.$digest(); expect(element.hasClass('ng-invalid-time')).toBe(false); }); it('should not be invalid when the model is undefined', function() { $rootScope.time = undefined; $rootScope.$digest(); expect(element.hasClass('ng-invalid-time')).toBe(false); }); it('should not be invalid when the model is a valid string date representation', function() { $rootScope.time = 'September 30, 2010 15:30:00'; $rootScope.$digest(); expect(element.hasClass('ng-invalid-time')).toBe(false); expect(getTimeState()).toEqual(['03', '30', 'PM']); }); it('should be invalid when the model is not a valid string date representation', function() { $rootScope.time = 'pizza'; $rootScope.$digest(); expect(element.hasClass('ng-invalid-time')).toBe(true); }); it('should return valid when the model becomes valid', function() { $rootScope.time = 'pizza'; $rootScope.$digest(); expect(element.hasClass('ng-invalid-time')).toBe(true); $rootScope.time = new Date(); $rootScope.$digest(); expect(element.hasClass('ng-invalid-time')).toBe(false); }); it('should return valid when the model is cleared', function() { $rootScope.time = 'pizza'; $rootScope.$digest(); expect(element.hasClass('ng-invalid-time')).toBe(true); $rootScope.time = null; $rootScope.$digest(); expect(element.hasClass('ng-invalid-time')).toBe(false); }); }); describe('use with `ng-required` directive', function() { beforeEach(inject(function() { $rootScope.time = null; element = $compile('<timepicker ng-model="$parent.time" ng-required="true"></timepicker>')($rootScope); $rootScope.$digest(); })); it('should be invalid initially', function() { expect(element.hasClass('ng-invalid')).toBe(true); }); it('should be valid if model has been specified', function() { $rootScope.time = new Date(); $rootScope.$digest(); expect(element.hasClass('ng-invalid')).toBe(false); }); }); describe('use with `ng-change` directive', function() { beforeEach(inject(function() { $rootScope.changeHandler = jasmine.createSpy('changeHandler'); $rootScope.time = new Date(); element = $compile('<timepicker ng-model="$parent.time" ng-change="$parent.changeHandler()"></timepicker>')($rootScope); $rootScope.$digest(); })); it('should not be called initially', function() { expect($rootScope.changeHandler).not.toHaveBeenCalled(); }); it('should be called when hours / minutes buttons clicked', function() { var btn1 = getHoursButton(true); var btn2 = getMinutesButton(false); doClick(btn1, 2); doClick(btn2, 3); $rootScope.$digest(); expect($rootScope.changeHandler.callCount).toBe(5); }); it('should not be called when model changes programatically', function() { $rootScope.time = new Date(); $rootScope.$digest(); expect($rootScope.changeHandler).not.toHaveBeenCalled(); }); }); });
/*! * froala_editor v2.7.1 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms/ * Copyright 2014-2017 Froala Labs */ (function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof module === 'object' && module.exports) { // Node/CommonJS module.exports = function( root, jQuery ) { if ( jQuery === undefined ) { // require('jQuery') returns a factory that requires window to // build a jQuery instance, we normalize how we use modules // that require this pattern but the window provided is a noop // if it's defined (how jquery works) if ( typeof window !== 'undefined' ) { jQuery = require('jquery'); } else { jQuery = require('jquery')(root); } } return factory(jQuery); }; } else { // Browser globals factory(window.jQuery); } }(function ($) { /** * Norwegian */ $.FE.LANGUAGE['nb'] = { translation: { // Place holder "Type something": "Skriv noe", // Basic formatting "Bold": "Fet", "Italic": "Kursiv", "Underline": "Understreket", "Strikethrough": "Gjennomstreket", // Main buttons "Insert": "Sett", "Delete": "Slett", "Cancel": "Avbryt", "OK": "OK", "Back": "Tilbake", "Remove": "Fjern", "More": "Mer", "Update": "Oppdatering", "Style": "Stil", // Font "Font Family": "Skriftsnitt", "Font Size": "St\u00f8rrelse", // Colors "Colors": "Farger", "Background": "Bakgrunn", "Text": "Tekst", "HEX Color": "Heksefarge", // Paragraphs "Paragraph Format": "Stiler", "Normal": "Normal", "Code": "Kode", "Heading 1": "Overskrift 1", "Heading 2": "Overskrift 2", "Heading 3": "Overskrift 3", "Heading 4": "Overskrift 4", // Style "Paragraph Style": "Avsnittsstil", "Inline Style": "P\u00e5 linje stil", // Alignment "Align": "Justering", "Align Left": "Venstrejustert", "Align Center": "Midtstilt", "Align Right": "H\u00f8yrejustert", "Align Justify": "Juster alle linjer", "None": "None", // Lists "Ordered List": "Ordnet liste", "Unordered List": "Uordnet liste", // Indent "Decrease Indent": "Reduser innrykk", "Increase Indent": "\u00d8k innrykk", // Links "Insert Link": "Sett inn lenke", "Open in new tab": "\u00c5pne i ny fane", "Open Link": "\u00c5pne lenke", "Edit Link": "Rediger lenke", "Unlink": "Fjern lenke", "Choose Link": "Velge lenke", // Images "Insert Image": "Sett inn bilde", "Upload Image": "Last opp bilde", "By URL": "Ved URL", "Browse": "Bla", "Drop image": "Slippe bilde", "or click": "eller klikk", "Manage Images": "Bildebehandling", "Loading": "Lasting", "Deleting": "Slette", "Tags": "Tags", "Are you sure? Image will be deleted.": "Er du sikker? Bildet vil bli slettet.", "Replace": "Erstatte", "Uploading": "Opplasting", "Loading image": "Lasting bilde", "Display": "Utstilling", "Inline": "P\u00e5 linje", "Break Text": "Brudd tekst", "Alternate Text": "Alternativ tekst", "Change Size": "Endre st\u00f8rrelse", "Width": "Bredde", "Height": "H\u00f8yde", "Something went wrong. Please try again.": "Noe gikk galt. V\u00e6r s\u00e5 snill, pr\u00f8v p\u00e5 nytt.", "Image Caption": "Bilde bildetekst", "Advanced Edit": "Avansert redigering", // Video "Insert Video": "Sett inn video", "Embedded Code": "Embedded kode", // Tables "Insert Table": "Sett inn tabell", "Table Header": "Tabell header", "Remove Table": "Fjern tabell", "Table Style": "Tabell stil", "Horizontal Align": "Horisontal justering", "Row": "Rad", "Insert row above": "Sett inn rad f\u00f8r", "Insert row below": "Sett in rad etter", "Delete row": "Slett rad", "Column": "Kolonne", "Insert column before": "Sett inn kolonne f\u00f8r", "Insert column after": "Sett inn kolonne etter", "Delete column": "Slett kolonne", "Cell": "Celle", "Merge cells": "Sl\u00e5 sammen celler", "Horizontal split": "Horisontalt delt", "Vertical split": "Vertikal split", "Cell Background": "Celle bakgrunn", "Vertical Align": "Vertikal justering", "Top": "Topp", "Middle": "Midten", "Bottom": "Bunn", "Align Top": "Justere toppen", "Align Middle": "Justere midten", "Align Bottom": "Justere bunnen", "Cell Style": "Celle stil", // Files "Upload File": "Opplastingsfil", "Drop file": "Slippe fil", // Emoticons "Emoticons": "Emoticons", "Grinning face": "Flirer ansikt", "Grinning face with smiling eyes": "Flirer ansikt med smilende \u00f8yne", "Face with tears of joy": "Ansikt med t\u00e5rer av glede", "Smiling face with open mouth": "Smilende ansikt med \u00e5pen munn", "Smiling face with open mouth and smiling eyes": "Smilende ansikt med \u00e5pen munn og smilende \u00f8yne", "Smiling face with open mouth and cold sweat": "Smilende ansikt med \u00e5pen munn og kald svette", "Smiling face with open mouth and tightly-closed eyes": "Smilende ansikt med \u00e5pen munn og tett lukkede \u00f8yne", "Smiling face with halo": "Smilende ansikt med glorie", "Smiling face with horns": "Smilende ansikt med horn", "Winking face": "Blunk ansikt", "Smiling face with smiling eyes": "Smilende ansikt med smilende \u00f8yne", "Face savoring delicious food": "M\u00f8te nyter deilig mat", "Relieved face": "Lettet ansikt", "Smiling face with heart-shaped eyes": "Smilende ansikt med hjerteformede \u00f8yne", "Smiling face with sunglasses": "Smilende ansikt med solbriller", "Smirking face": "Tilfreds ansikt", "Neutral face": "N\u00f8ytral ansikt", "Expressionless face": "Uttrykksl\u00f8st ansikt", "Unamused face": "Ikke moret ansikt", "Face with cold sweat": "Ansikt med kald svette", "Pensive face": "Tankefull ansikt", "Confused face": "Forvirret ansikt", "Confounded face": "Skamme ansikt", "Kissing face": "Kyssing ansikt", "Face throwing a kiss": "Ansikt kaste et kyss", "Kissing face with smiling eyes": "Kyssing ansikt med smilende \u00f8yne", "Kissing face with closed eyes": "Kyssing ansiktet med lukkede \u00f8yne", "Face with stuck out tongue": "Ansikt med stakk ut tungen", "Face with stuck out tongue and winking eye": "Ansikt med stakk ut tungen og blunke \u00f8ye", "Face with stuck out tongue and tightly-closed eyes": "Ansikt med fast ut tungen og tett lukket \u00f8yne", "Disappointed face": "Skuffet ansikt", "Worried face": "Bekymret ansikt", "Angry face": "Sint ansikt", "Pouting face": "Trutmunn ansikt", "Crying face": "Gr\u00e5ter ansikt", "Persevering face": "Utholdende ansikt", "Face with look of triumph": "Ansikt med utseendet til triumf", "Disappointed but relieved face": "Skuffet men lettet ansikt", "Frowning face with open mouth": "Rynke ansikt med \u00e5pen munn", "Anguished face": "Forpint ansikt", "Fearful face": "Engstelig ansikt", "Weary face": "Slitne ansiktet", "Sleepy face": "S\u00f8vnig ansikt", "Tired face": "Tr\u00f8tt ansikt", "Grimacing face": "Griner ansikt", "Loudly crying face": "H\u00f8ylytt gr\u00e5tende ansikt", "Face with open mouth": "Ansikt med \u00e5pen munn", "Hushed face": "Lavm\u00e6lt ansikt", "Face with open mouth and cold sweat": "Ansikt med \u00e5pen munn og kald svette", "Face screaming in fear": "Ansikt skriker i frykt", "Astonished face": "Forbauset ansikt", "Flushed face": "Flushed ansikt", "Sleeping face": "Sovende ansikt", "Dizzy face": "Svimmel ansikt", "Face without mouth": "Ansikt uten munn", "Face with medical mask": "Ansikt med medisinsk maske", // Line breaker "Break": "Brudd", // Math "Subscript": "Senket skrift", "Superscript": "Hevet skrift", // Full screen "Fullscreen": "Full skjerm", // Horizontal line "Insert Horizontal Line": "Sett inn horisontal linje", // Clear formatting "Clear Formatting": "Fjerne formatering", // Undo, redo "Undo": "Angre", "Redo": "Utf\u00f8r likevel", // Select all "Select All": "Marker alt", // Code view "Code View": "Kodevisning", // Quote "Quote": "Sitat", "Increase": "\u00d8ke", "Decrease": "Nedgang", // Quick Insert "Quick Insert": "Hurtiginnsats", // Spcial Characters "Special Characters": "Spesielle karakterer", "Latin": "Latin", "Greek": "Gresk", "Cyrillic": "Kyrilliske", "Punctuation": "Tegnsetting", "Currency": "Valuta", "Arrows": "Piler", "Math": "Matte", "Misc": "Misc", // Print. "Print": "Skrive ut", // Spell Checker. "Spell Checker": "Stavekontroll", // Help "Help": "Hjelp", "Shortcuts": "Snarveier", "Inline Editor": "Inline editor", "Show the editor": "Vis redaktøren", "Common actions": "Felles handlinger", "Copy": "Kopiere", "Cut": "Kutte opp", "Paste": "Lim inn", "Basic Formatting": "Grunnleggende formatering", "Increase quote level": "Øke tilbudsnivået", "Decrease quote level": "Redusere tilbudsnivå", "Image / Video": "Bilde / video", "Resize larger": "Endre størrelsen større", "Resize smaller": "Endre størrelsen mindre", "Table": "Bord", "Select table cell": "Velg tabellcelle", "Extend selection one cell": "Utvide valg en celle", "Extend selection one row": "Utvide valg en rad", "Navigation": "Navigasjon", "Focus popup / toolbar": "Fokus popup / verktøylinje", "Return focus to previous position": "Returnere fokus til tidligere posisjon", // Embed.ly "Embed URL": "Legge inn nettadressen", "Paste in a URL to embed": "Lim inn i en URL for å legge inn", // Word Paste. "The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?": "Det limte innholdet kommer fra et Microsoft Word-dokument. vil du beholde formatet eller rydde det opp?", "Keep": "Beholde", "Clean": "Ren", "Word Paste Detected": "Ordpasta oppdages" }, direction: "ltr" }; }));
/* DOM Level2 Events implemented as described here: * * http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html * */ var core = require("./core").dom.level2.core, utils = require("../utils"), defineGetter = utils.defineGetter, defineSetter = utils.defineSetter, inheritFrom = utils.inheritFrom; // modify cloned instance for more info check: https://github.com/tmpvar/jsdom/issues/325 core = Object.create(core); var events = {}; events.EventException = function() { if (arguments.length > 0) { this._code = arguments[0]; } else { this._code = 0; } if (arguments.length > 1) { this._message = arguments[1]; } else { this._message = "Unspecified event type"; } Error.call(this, this._message); if (Error.captureStackTrace) { Error.captureStackTrace(this, events.EventException); } }; inheritFrom(Error, events.EventException, { UNSPECIFIED_EVENT_TYPE_ERR : 0, get code() { return this._code;} }); events.Event = function(eventType) { this._eventType = eventType; this._type = null; this._bubbles = null; this._cancelable = null; this._target = null; this._currentTarget = null; this._eventPhase = 0; this._timeStamp = null; this._preventDefault = false; this._stopPropagation = false; }; events.Event.prototype = { initEvent: function(type, bubbles, cancelable) { this._type = type; this._bubbles = bubbles; this._cancelable = cancelable; }, preventDefault: function() { if (this._cancelable) { this._preventDefault = true; } }, stopPropagation: function() { this._stopPropagation = true; }, NONE : 0, CAPTURING_PHASE : 1, AT_TARGET : 2, BUBBLING_PHASE : 3, get eventType() { return this._eventType; }, get type() { return this._type; }, get bubbles() { return this._bubbles; }, get cancelable() { return this._cancelable; }, get target() { return this._target; }, get currentTarget() { return this._currentTarget; }, get eventPhase() { return this._eventPhase; }, get timeStamp() { return this._timeStamp; } }; events.UIEvent = function(eventType) { events.Event.call(this, eventType); this.view = null; this.detail = null; }; inheritFrom(events.Event, events.UIEvent, { initUIEvent: function(type, bubbles, cancelable, view, detail) { this.initEvent(type, bubbles, cancelable); this.view = view; this.detail = detail; }, }); events.MouseEvent = function(eventType) { events.UIEvent.call(this, eventType); this.screenX = null; this.screenY = null; this.clientX = null; this.clientY = null; this.ctrlKey = null; this.shiftKey = null; this.altKey = null; this.metaKey = null; this.button = null; this.relatedTarget = null; }; inheritFrom(events.UIEvent, events.MouseEvent, { initMouseEvent: function(type, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget) { this.initUIEvent(type, bubbles, cancelable, view, detail); this.screenX = screenX this.screenY = screenY this.clientX = clientX this.clientY = clientY this.ctrlKey = ctrlKey this.shiftKey = shiftKey this.altKey = altKey this.metaKey = metaKey this.button = button this.relatedTarget = relatedTarget } }); events.MutationEvent = function(eventType) { events.Event.call(this, eventType); this.relatedNode = null; this.prevValue = null; this.newValue = null; this.attrName = null; this.attrChange = null; }; inheritFrom(events.Event, events.MutationEvent, { initMutationEvent: function(type, bubbles, cancelable, relatedNode, prevValue, newValue, attrName, attrChange) { this.initEvent(type, bubbles, cancelable); this.relatedNode = relatedNode; this.prevValue = prevValue; this.newValue = newValue; this.attrName = attrName; this.attrChange = attrChange; }, MODIFICATION : 1, ADDITION : 2, REMOVAL : 3 }); events.EventTarget = function() {}; function getListeners(target, type, capturing) { var listeners = target._listeners && target._listeners[type] && target._listeners[type][capturing] || []; if (!capturing) { var traditionalHandler = target['on' + type]; if (traditionalHandler) { var implementation = (target._ownerDocument ? target._ownerDocument.implementation : target.document.implementation); if (implementation.hasFeature('ProcessExternalResources', 'script')) { if (listeners.indexOf(traditionalHandler) < 0) { listeners.push(traditionalHandler); } } } } return listeners; } function dispatchPhase(event, iterator) { var target = iterator(); while (target && !event._stopPropagation) { if (event._eventPhase === event.CAPTURING_PHASE || event._eventPhase === event.AT_TARGET) { callListeners(event, target, getListeners(target, event._type, true)); } if (event._eventPhase === event.AT_TARGET || event._eventPhase === event.BUBBLING_PHASE) { callListeners(event, target, getListeners(target, event._type, false)); } target = iterator(); } } function callListeners(event, target, listeners) { var currentListener = listeners.length; while (currentListener--) { event._currentTarget = target; try { listeners[currentListener].call(target, event); } catch (e) { target.raise( 'error', "Dispatching event '" + event._type + "' failed", {error: e, event: event} ); } } } function forwardIterator(list) { var i = 0, len = list.length; return function iterator() { return i < len ? list[i++] : null }; } function backwardIterator(list) { var i = list.length; return function iterator() { return i >=0 ? list[--i] : null }; } function singleIterator(obj) { var i = 1; return function iterator() { return i-- ? obj : null }; } events.EventTarget.prototype = { addEventListener: function(type, listener, capturing) { this._listeners = this._listeners || {}; var listeners = this._listeners[type] || {}; capturing = (capturing === true); var capturingListeners = listeners[capturing] || []; for (var i=0; i < capturingListeners.length; i++) { if (capturingListeners[i] === listener) { return; } } capturingListeners.push(listener); listeners[capturing] = capturingListeners; this._listeners[type] = listeners; }, removeEventListener: function(type, listener, capturing) { var listeners = this._listeners && this._listeners[type]; if (!listeners) return; var capturingListeners = listeners[(capturing === true)]; if (!capturingListeners) return; for (var i=0; i < capturingListeners.length; i++) { if (capturingListeners[i] === listener) { capturingListeners.splice(i, 1); return; } } }, dispatchEvent: function(event) { if (event == null) { throw new events.EventException(0, "Null event"); } if (event._type == null || event._type == "") { throw new events.EventException(0, "Uninitialized event"); } var targetList = []; event._target = this; //per the spec we gather the list of targets first to ensure //against dom modifications during actual event dispatch var target = this, targetParent = target._parentNode; while (targetParent) { targetList.push(targetParent); target = targetParent; targetParent = target._parentNode; } targetParent = target._parentWindow; if (targetParent) { targetList.push(targetParent); } var iterator = backwardIterator(targetList); event._eventPhase = event.CAPTURING_PHASE; dispatchPhase(event, iterator); iterator = singleIterator(event._target); event._eventPhase = event.AT_TARGET; dispatchPhase(event, iterator); if (event._bubbles) { iterator = forwardIterator(targetList); event._eventPhase = event.BUBBLING_PHASE; dispatchPhase(event, iterator); } event._currentTarget = null; event._eventPhase = event.NONE; return event._preventDefault; } }; // Reinherit class heirarchy with EventTarget at its root inheritFrom(events.EventTarget, core.Node, core.Node.prototype); // Node inheritFrom(core.Node, core.Attr, core.Attr.prototype); inheritFrom(core.Node, core.CharacterData, core.CharacterData.prototype); inheritFrom(core.Node, core.Document, core.Document.prototype); inheritFrom(core.Node, core.DocumentFragment, core.DocumentFragment.prototype); inheritFrom(core.Node, core.DocumentType, core.DocumentType.prototype); inheritFrom(core.Node, core.Element, core.Element.prototype); inheritFrom(core.Node, core.Entity, core.Entity.prototype); inheritFrom(core.Node, core.EntityReference, core.EntityReference.prototype); inheritFrom(core.Node, core.Notation, core.Notation.prototype); inheritFrom(core.Node, core.ProcessingInstruction, core.ProcessingInstruction.prototype); // CharacterData inheritFrom(core.CharacterData, core.Text, core.Text.prototype); // Text inheritFrom(core.Text, core.CDATASection, core.CDATASection.prototype); inheritFrom(core.Text, core.Comment, core.Comment.prototype); function getDocument(el) { return el.nodeType == core.Node.DOCUMENT_NODE ? el : el._ownerDocument; } function mutationEventsEnabled(el) { return el.nodeType != core.Node.ATTRIBUTE_NODE && getDocument(el).implementation.hasFeature('MutationEvents'); } utils.intercept(core.Node, 'insertBefore', function(_super, args, newChild, refChild) { var ret = _super.apply(this, args); if (mutationEventsEnabled(this)) { var doc = getDocument(this), ev = doc.createEvent("MutationEvents"); ev.initMutationEvent("DOMNodeInserted", true, false, this, null, null, null, null); newChild.dispatchEvent(ev); if (this.nodeType == core.Node.DOCUMENT_NODE || this._attachedToDocument) { ev = doc.createEvent("MutationEvents"); ev.initMutationEvent("DOMNodeInsertedIntoDocument", false, false, null, null, null, null, null); core.visitTree(newChild, function(el) { if (el.nodeType == core.Node.ELEMENT_NODE) { el.dispatchEvent(ev); el._attachedToDocument = true; } }); } } return ret; }); utils.intercept(core.Node, 'removeChild', function (_super, args, oldChild) { if (mutationEventsEnabled(this)) { var doc = getDocument(this), ev = doc.createEvent("MutationEvents"); ev.initMutationEvent("DOMNodeRemoved", true, false, this, null, null, null, null); oldChild.dispatchEvent(ev); ev = doc.createEvent("MutationEvents"); ev.initMutationEvent("DOMNodeRemovedFromDocument", false, false, null, null, null, null, null); core.visitTree(oldChild, function(el) { if (el.nodeType == core.Node.ELEMENT_NODE) { el.dispatchEvent(ev); el._attachedToDocument = false; } }); } return _super.apply(this, args); }); function dispatchAttrEvent(doc, target, prevVal, newVal, attrName, attrChange) { if (!newVal || newVal != prevVal) { var ev = doc.createEvent("MutationEvents"); ev.initMutationEvent("DOMAttrModified", true, false, target, prevVal, newVal, attrName, attrChange); target.dispatchEvent(ev); } } function attrNodeInterceptor(change) { return function(_super, args, node) { var target = this._parentNode, prev = _super.apply(this, args); if (mutationEventsEnabled(target)) { dispatchAttrEvent(target._ownerDocument, target, prev && prev.value || null, change == 'ADDITION' ? node.value : null, prev && prev.name || node.name, events.MutationEvent.prototype[change]); } return prev; }; } function attrInterceptor(ns) { return function(_super, args, localName, value, _name, _prefix, namespace) { var target = this._parentNode; if (!mutationEventsEnabled(target)) { _super.apply(this, args); return; } if (namespace === undefined) { namespace = null; } var prev = ns ? this.$getNode(namespace, localName) : this.$getNoNS(localName); var prevVal = prev && prev.value || null; _super.apply(this, args); var node = ns ? this.$getNode(namespace, localName): this.$getNoNS(localName); dispatchAttrEvent(target._ownerDocument, target, prevVal, node.value, node.name, events.MutationEvent.prototype.ADDITION); }; } utils.intercept(core.AttributeList, '$removeNode', attrNodeInterceptor('REMOVAL')); utils.intercept(core.AttributeList, '$setNode', attrNodeInterceptor('ADDITION')); utils.intercept(core.AttributeList, '$set', attrInterceptor(true)); utils.intercept(core.AttributeList, '$setNoNS', attrInterceptor(false)); defineGetter(core.CharacterData.prototype, "_nodeValue", function() { return this.__nodeValue; }); defineSetter(core.CharacterData.prototype, "_nodeValue", function(value) { var oldValue = this.__nodeValue; this.__nodeValue = value; if (this._ownerDocument && this._parentNode && mutationEventsEnabled(this)) { var ev = this._ownerDocument.createEvent("MutationEvents") ev.initMutationEvent("DOMCharacterDataModified", true, false, this, oldValue, value, null, null); this.dispatchEvent(ev); } }); core.Document.prototype.createEvent = function(eventType) { switch (eventType) { case "MutationEvents": return new events.MutationEvent(eventType); case "UIEvents": return new events.UIEvent(eventType); case "MouseEvents": return new events.MouseEvent(eventType); case "HTMLEvents": return new events.Event(eventType); } return new events.Event(eventType); }; exports.dom = { level2 : { core : core, events : events } };
el.addEventListener(eventName, eventHandler);
var _ = require('lodash'), util = require('util'), errors = require('ghost-ignition').errors; function GhostError(options) { options = options || {}; this.value = options.value; errors.IgnitionError.call(this, options); } // jscs:disable var ghostErrors = { DataExportError: function DataExportError(options) { GhostError.call(this, _.merge({ statusCode: 500, errorType: 'DataExportError' }, options)); }, DataImportError: function DataImportError(options) { GhostError.call(this, _.merge({ statusCode: 500, errorType: 'DataImportError' }, options)); }, DatabaseVersionError: function DatabaseVersionError(options) { GhostError.call(this, _.merge({ hideStack: true, statusCode: 500, errorType: 'DatabaseVersionError' }, options)); }, DatabaseNotPopulatedError: function DatabaseNotPopulatedError(options) { GhostError.call(this, _.merge({ statusCode: 500, errorType: 'DatabaseNotPopulatedError' }, options)); }, DatabaseNotSeededError: function DatabaseNotSeededError(options) { GhostError.call(this, _.merge({ statusCode: 500, errorType: 'DatabaseNotSeededError' }, options)); }, EmailError: function EmailError(options) { GhostError.call(this, _.merge({ statusCode: 500, errorType: 'EmailError' }, options)); }, ThemeValidationError: function ThemeValidationError(options) { GhostError.call(this, _.merge({ statusCode: 422, errorType: 'ThemeValidationError', errorDetails: {} }, options)); } }; util.inherits(GhostError, errors.IgnitionError); _.each(ghostErrors, function (error) { util.inherits(error, GhostError); }); // we need to inherit all general errors from GhostError, otherwise we have to check instanceof IgnitionError _.each(errors, function (error) { if (error.name === 'IgnitionError' || typeof error === 'object') { return; } util.inherits(error, GhostError); }); module.exports = _.merge(ghostErrors, errors); module.exports.GhostError = GhostError;
{ "VALIDATOR.FIELDREQUIRED": "Completare il campo \"%s\", che è obbligatorio.", "HASMANYFILEFIELD.UPLOADING": "Invio file... %s", "TABLEFIELD.DELETECONFIRMMESSAGE": "Si è sicuri di voler eliminare questo elemento?", "LOADING": "caricamento...", "UNIQUEFIELD.SUGGESTED": "Cambiare il valore di '%s': %s", "UNIQUEFIELD.ENTERNEWVALUE": "È necessario scegliere un'altro valore per questo campo", "UNIQUEFIELD.CANNOTLEAVEEMPTY": "Questo campo non può essere lasciato vuoto", "RESTRICTEDTEXTFIELD.CHARCANTBEUSED": "Il carattere '%s' non può essere utilizzato in questo campo", "UPDATEURL.CONFIRM": "Volete cambiare l'URL in:\n\n%s/\n\nClicca OK per cambiare l'URL, clicca Annuler per lasciarla a:\n\n%s", "UPDATEURL.CONFIRMURLCHANGED": "The URL has been changed to\n'%s'", "FILEIFRAMEFIELD.DELETEFILE": "Delete File", "FILEIFRAMEFIELD.UNATTACHFILE": "Un-Attach File", "FILEIFRAMEFIELD.DELETEIMAGE": "Delete Image", "FILEIFRAMEFIELD.CONFIRMDELETE": "Are you sure you want to delete this file?", "LeftAndMain.IncompatBrowserWarning": "Your browser is not compatible with the CMS interface. Please use Internet Explorer 7+, Google Chrome 10+ or Mozilla Firefox 3.5+.", "GRIDFIELD.ERRORINTRANSACTION": "An error occured while fetching data from the server\n Please try again later.", "HtmlEditorField.SelectAnchor": "Select an anchor", "UploadField.ConfirmDelete": "Are you sure you want to remove this file from the server filesystem?", "UploadField.PHP_MAXFILESIZE": "File exceeds upload_max_filesize (php.ini directive)", "UploadField.HTML_MAXFILESIZE": "File exceeds MAX_FILE_SIZE (HTML form directive)", "UploadField.ONLYPARTIALUPLOADED": "File was only partially uploaded", "UploadField.NOFILEUPLOADED": "No File was uploaded", "UploadField.NOTMPFOLDER": "Missing a temporary folder", "UploadField.WRITEFAILED": "Failed to write file to disk", "UploadField.STOPEDBYEXTENSION": "File upload stopped by extension", "UploadField.TOOLARGE": "Filesize is too large", "UploadField.TOOSMALL": "Filesize is too small", "UploadField.INVALIDEXTENSION": "Extension is not allowed", "UploadField.MAXNUMBEROFFILESSIMPLE": "Max number of files exceeded", "UploadField.UPLOADEDBYTES": "Uploaded bytes exceed file size", "UploadField.EMPTYRESULT": "Empty file upload result", "UploadField.LOADING": "Loading ...", "UploadField.Editing": "Editing ...", "UploadField.Uploaded": "Uploaded", "UploadField.OVERWRITEWARNING": "File with the same name already exists", "TreeDropdownField.ENTERTOSEARCH": "Press enter to search", "TreeDropdownField.OpenLink": "Open", "TreeDropdownField.FieldTitle": "Choose", "TreeDropdownField.SearchFieldTitle": "Choose or Search" }
"use strict"; exports.__esModule = true; exports.bar = exports.foo = void 0; var foo, bar; exports.bar = bar; exports.foo = foo;
var helpers = require('./helpers'), should = require('should'), needle = require('./../'), server; var port = 7707; describe('Basic Auth', function() { before(function(done) { server = helpers.server({ port: port }, done); }) after(function(done) { server.close(done); }) ///////////////// helpers var get_auth = function(header) { var token = header.split(/\s+/).pop(); return token && new Buffer(token, 'base64').toString().split(':'); } describe('when neither username or password are passed', function() { it('doesnt send any Authorization headers', function(done) { needle.get('localhost:' + port, { parse: true }, function(err, resp) { var sent_headers = resp.body.headers; Object.keys(sent_headers).should.not.include('authorization'); done(); }) }) }) describe('when username is an empty string, and password is a valid string', function() { var opts = { username: '', password: 'foobar', parse: true }; it('doesnt send any Authorization headers', function(done) { needle.get('localhost:' + port, { parse: true }, function(err, resp) { var sent_headers = resp.body.headers; Object.keys(sent_headers).should.not.include('authorization'); done(); }) }) }); describe('when username is a valid string, but no username is passed', function() { var opts = { username: 'foobar', parse: true }; it('sends Authorization header', function(done) { needle.get('localhost:' + port, opts, function(err, resp) { var sent_headers = resp.body.headers; Object.keys(sent_headers).should.include('authorization'); done(); }) }) it('Basic Auth only includes username, without colon', function(done) { needle.get('localhost:' + port, opts, function(err, resp) { var sent_headers = resp.body.headers; var auth = get_auth(sent_headers['authorization']); auth[0].should.equal('foobar'); auth.should.have.lengthOf(1); done(); }) }) }) describe('when username is a valid string, and password is null', function() { var opts = { username: 'foobar', password: null, parse: true }; it('sends Authorization header', function(done) { needle.get('localhost:' + port, opts, function(err, resp) { var sent_headers = resp.body.headers; Object.keys(sent_headers).should.include('authorization'); done(); }) }) it('Basic Auth only includes both username and password', function(done) { needle.get('localhost:' + port, opts, function(err, resp) { var sent_headers = resp.body.headers; var auth = get_auth(sent_headers['authorization']); auth[0].should.equal('foobar'); auth[1].should.equal(''); done(); }) }) }) describe('when username is a valid string, and password is an empty string', function() { var opts = { username: 'foobar', password: '', parse: true }; it('sends Authorization header', function(done) { needle.get('localhost:' + port, opts, function(err, resp) { var sent_headers = resp.body.headers; Object.keys(sent_headers).should.include('authorization'); done(); }) }) it('Basic Auth only includes both username and password', function(done) { needle.get('localhost:' + port, opts, function(err, resp) { var sent_headers = resp.body.headers; var auth = get_auth(sent_headers['authorization']); auth[0].should.equal('foobar'); auth[1].should.equal(''); auth.should.have.lengthOf(2); done(); }) }) }) describe('when username AND password are non empty strings', function() { var opts = { username: 'foobar', password: 'jakub', parse: true }; it('sends Authorization header', function(done) { needle.get('localhost:' + port, opts, function(err, resp) { var sent_headers = resp.body.headers; Object.keys(sent_headers).should.include('authorization'); done(); }) }) it('Basic Auth only includes both user and password', function(done) { needle.get('localhost:' + port, opts, function(err, resp) { var sent_headers = resp.body.headers; var auth = get_auth(sent_headers['authorization']); auth[0].should.equal('foobar'); auth[1].should.equal('jakub'); auth.should.have.lengthOf(2); done(); }) }) }) })
/// Copyright (c) 2009 Microsoft Corporation /// /// Redistribution and use in source and binary forms, with or without modification, are permitted provided /// that the following conditions are met: /// * Redistributions of source code must retain the above copyright notice, this list of conditions and /// the following disclaimer. /// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and /// the following disclaimer in the documentation and/or other materials provided with the distribution. /// * Neither the name of Microsoft nor the names of its contributors may be used to /// endorse or promote products derived from this software without specific prior written permission. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR /// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS /// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE /// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT /// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS /// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, /// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF /// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ES5Harness.registerTest( { id: "15.2.3.3-4-60", path: "TestCases/chapter15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-60.js", description: "Object.getOwnPropertyDescriptor returns data desc for functions on built-ins (Array.prototype.reduceRight)", test: function testcase() { var desc = Object.getOwnPropertyDescriptor(Array.prototype, "reduceRight"); if (desc.value === Array.prototype.reduceRight && desc.writable === true && desc.enumerable === false && desc.configurable === true) { return true; } }, precondition: function prereq() { return fnExists(Object.getOwnPropertyDescriptor); } });
var structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4 = [ [ "ContextFlags", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a09846f6f5a11420035387033fb27f60a", null ], [ "Dr0", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a9a3e08f9c5539bddf00b0438dc69b367", null ], [ "Dr1", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a5eb050ee34acb0d55b74bbf718553a64", null ], [ "Dr2", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a5e9674cfad61a624c3735c79e7d276f2", null ], [ "Dr3", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a38ad4c085f0fae6d77a7c56bb5cace5c", null ], [ "Dr6", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a7e0793401b349b517d0af206ac0ea37b", null ], [ "Dr7", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a0469900eef3caf2d7e3250d9173ec6b0", null ], [ "Eax", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a277533bc790130e91efcd37662911b53", null ], [ "Ebp", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a487cb692a2592261014dad45f3f582ad", null ], [ "Ebx", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a5ae785ff6b5fbe0a3b5f2bd339127a59", null ], [ "Ecx", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a38ab474223f6441f2aaf3d46db62f5e1", null ], [ "Edi", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#af441146941995c66eaf7bc1bca7a6ffa", null ], [ "Edx", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a7284ad0ad2132d50f44be4c668089e29", null ], [ "EFlags", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a857067fb4d41257428ec19bf55717bc1", null ], [ "Eip", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#ad781b1b803965f19854e74eef26a4f57", null ], [ "Esi", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a2203a11c252e2f92bfe9bdeeeff042aa", null ], [ "Esp", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a96cc26728b3f1aee8d8e9b32fa005f63", null ], [ "ExtendedRegisters", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a309a211fffd0d0d228ff7fe748103bea", null ], [ "FloatSave", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a0cbcba7d6aea40051d2044eb2eb1c372", null ], [ "SegCs", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#aa542571dc4e81eba2f91acd5f22aa379", null ], [ "SegDs", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a9be46c0c954d7663e1ec375c1499a5c8", null ], [ "SegEs", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a48b645139062caf6649868794a043fad", null ], [ "SegFs", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#abd01010c2d8fca51bcaa863ddc326638", null ], [ "SegGs", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a97c9f4f948994969d83677770dbf76f6", null ], [ "SegSs", "structblackbone_1_1___c_o_n_t_e_x_t___t_3_01_d_w_o_r_d_01_4.html#a0e4c4fe38707a803fc67eb4e70b54604", null ] ];
/** * Lo-Dash 2.3.0 (Custom Build) <http://lodash.com/> * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE> * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <http://lodash.com/license> */ var baseCreate = require('lodash._basecreate'), isObject = require('lodash.isobject'), setBindData = require('lodash._setbinddata'); /** * Used for `Array` method references. * * Normally `Array.prototype` would suffice, however, using an array literal * avoids issues in Narwhal. */ var arrayRef = []; /** Native method shortcuts */ var push = arrayRef.push; /** * The base implementation of `_.bind` that creates the bound function and * sets its meta data. * * @private * @param {Array} bindData The bind data array. * @returns {Function} Returns the new bound function. */ function baseBind(bindData) { var func = bindData[0], partialArgs = bindData[2], thisArg = bindData[4]; function bound() { // `Function#bind` spec // http://es5.github.io/#x15.3.4.5 if (partialArgs) { var args = partialArgs.slice(); push.apply(args, arguments); } // mimic the constructor's `return` behavior // http://es5.github.io/#x13.2.2 if (this instanceof bound) { // ensure `new bound` is an instance of `func` var thisBinding = baseCreate(func.prototype), result = func.apply(thisBinding, args || arguments); return isObject(result) ? result : thisBinding; } return func.apply(thisArg, args || arguments); } setBindData(bound, bindData); return bound; } module.exports = baseBind;
/** * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* jshint maxlen: false */ 'use strict'; var createAPIRequest = require('../../lib/apirequest'); /** * YouTube Analytics API * * @classdesc Retrieve your YouTube Analytics reports. * @namespace youtubeAnalytics * @version v1 * @variation v1 * @this Youtubeanalytics * @param {object=} options Options for Youtubeanalytics */ function Youtubeanalytics(options) { var self = this; this._options = options || {}; this.batchReportDefinitions = { /** * youtubeAnalytics.batchReportDefinitions.list * * @desc Retrieves a list of available batch report definitions. * * @alias youtubeAnalytics.batchReportDefinitions.list * @memberOf! youtubeAnalytics(v1) * * @param {object} params - Parameters for request * @param {string} params.onBehalfOfContentOwner - The onBehalfOfContentOwner parameter identifies the content owner that the user is acting on behalf of. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/youtube/analytics/v1/batchReportDefinitions', method: 'GET' }, params: params, requiredParams: ['onBehalfOfContentOwner'], pathParams: [], context: self }; return createAPIRequest(parameters, callback); } }; this.batchReports = { /** * youtubeAnalytics.batchReports.list * * @desc Retrieves a list of processed batch reports. * * @alias youtubeAnalytics.batchReports.list * @memberOf! youtubeAnalytics(v1) * * @param {object} params - Parameters for request * @param {string} params.batchReportDefinitionId - The batchReportDefinitionId parameter specifies the ID of the batch reportort definition for which you are retrieving reports. * @param {string} params.onBehalfOfContentOwner - The onBehalfOfContentOwner parameter identifies the content owner that the user is acting on behalf of. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/youtube/analytics/v1/batchReports', method: 'GET' }, params: params, requiredParams: ['batchReportDefinitionId', 'onBehalfOfContentOwner'], pathParams: [], context: self }; return createAPIRequest(parameters, callback); } }; this.groupItems = { /** * youtubeAnalytics.groupItems.delete * * @desc Removes an item from a group. * * @alias youtubeAnalytics.groupItems.delete * @memberOf! youtubeAnalytics(v1) * * @param {object} params - Parameters for request * @param {string} params.id - The id parameter specifies the YouTube group item ID for the group that is being deleted. * @param {string=} params.onBehalfOfContentOwner - Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/youtube/analytics/v1/groupItems', method: 'DELETE' }, params: params, requiredParams: ['id'], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * youtubeAnalytics.groupItems.insert * * @desc Creates a group item. * * @alias youtubeAnalytics.groupItems.insert * @memberOf! youtubeAnalytics(v1) * * @param {object} params - Parameters for request * @param {string=} params.onBehalfOfContentOwner - Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/youtube/analytics/v1/groupItems', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * youtubeAnalytics.groupItems.list * * @desc Returns a collection of group items that match the API request parameters. * * @alias youtubeAnalytics.groupItems.list * @memberOf! youtubeAnalytics(v1) * * @param {object} params - Parameters for request * @param {string} params.groupId - The id parameter specifies the unique ID of the group for which you want to retrieve group items. * @param {string=} params.onBehalfOfContentOwner - Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/youtube/analytics/v1/groupItems', method: 'GET' }, params: params, requiredParams: ['groupId'], pathParams: [], context: self }; return createAPIRequest(parameters, callback); } }; this.groups = { /** * youtubeAnalytics.groups.delete * * @desc Deletes a group. * * @alias youtubeAnalytics.groups.delete * @memberOf! youtubeAnalytics(v1) * * @param {object} params - Parameters for request * @param {string} params.id - The id parameter specifies the YouTube group ID for the group that is being deleted. * @param {string=} params.onBehalfOfContentOwner - Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/youtube/analytics/v1/groups', method: 'DELETE' }, params: params, requiredParams: ['id'], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * youtubeAnalytics.groups.insert * * @desc Creates a group. * * @alias youtubeAnalytics.groups.insert * @memberOf! youtubeAnalytics(v1) * * @param {object} params - Parameters for request * @param {string=} params.onBehalfOfContentOwner - Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/youtube/analytics/v1/groups', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * youtubeAnalytics.groups.list * * @desc Returns a collection of groups that match the API request parameters. For example, you can retrieve all groups that the authenticated user owns, or you can retrieve one or more groups by their unique IDs. * * @alias youtubeAnalytics.groups.list * @memberOf! youtubeAnalytics(v1) * * @param {object=} params - Parameters for request * @param {string=} params.id - The id parameter specifies a comma-separated list of the YouTube group ID(s) for the resource(s) that are being retrieved. In a group resource, the id property specifies the group's YouTube group ID. * @param {boolean=} params.mine - Set this parameter's value to true to instruct the API to only return groups owned by the authenticated user. * @param {string=} params.onBehalfOfContentOwner - Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/youtube/analytics/v1/groups', method: 'GET' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * youtubeAnalytics.groups.update * * @desc Modifies a group. For example, you could change a group's title. * * @alias youtubeAnalytics.groups.update * @memberOf! youtubeAnalytics(v1) * * @param {object} params - Parameters for request * @param {string=} params.onBehalfOfContentOwner - Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/youtube/analytics/v1/groups', method: 'PUT' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); } }; this.reports = { /** * youtubeAnalytics.reports.query * * @desc Retrieve your YouTube Analytics reports. * * @alias youtubeAnalytics.reports.query * @memberOf! youtubeAnalytics(v1) * * @param {object} params - Parameters for request * @param {string=} params.currency - The currency to which financial metrics should be converted. The default is US Dollar (USD). If the result contains no financial metrics, this flag will be ignored. Responds with an error if the specified currency is not recognized. * @param {string=} params.dimensions - A comma-separated list of YouTube Analytics dimensions, such as views or ageGroup,gender. See the Available Reports document for a list of the reports that you can retrieve and the dimensions used for those reports. Also see the Dimensions document for definitions of those dimensions. * @param {string} params.end-date - The end date for fetching YouTube Analytics data. The value should be in YYYY-MM-DD format. * @param {string=} params.filters - A list of filters that should be applied when retrieving YouTube Analytics data. The Available Reports document identifies the dimensions that can be used to filter each report, and the Dimensions document defines those dimensions. If a request uses multiple filters, join them together with a semicolon (;), and the returned result table will satisfy both filters. For example, a filters parameter value of video==dMH0bHeiRNg;country==IT restricts the result set to include data for the given video in Italy. * @param {string} params.ids - Identifies the YouTube channel or content owner for which you are retrieving YouTube Analytics data. - To request data for a YouTube user, set the ids parameter value to channel==CHANNEL_ID, where CHANNEL_ID specifies the unique YouTube channel ID. - To request data for a YouTube CMS content owner, set the ids parameter value to contentOwner==OWNER_NAME, where OWNER_NAME is the CMS name of the content owner. * @param {integer=} params.max-results - The maximum number of rows to include in the response. * @param {string} params.metrics - A comma-separated list of YouTube Analytics metrics, such as views or likes,dislikes. See the Available Reports document for a list of the reports that you can retrieve and the metrics available in each report, and see the Metrics document for definitions of those metrics. * @param {string=} params.sort - A comma-separated list of dimensions or metrics that determine the sort order for YouTube Analytics data. By default the sort order is ascending. The '-' prefix causes descending sort order. * @param {string} params.start-date - The start date for fetching YouTube Analytics data. The value should be in YYYY-MM-DD format. * @param {integer=} params.start-index - An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter (one-based, inclusive). * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ query: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/youtube/analytics/v1/reports', method: 'GET' }, params: params, requiredParams: ['ids', 'start-date', 'end-date', 'metrics'], pathParams: [], context: self }; return createAPIRequest(parameters, callback); } }; } /** * Exports Youtubeanalytics object * @type Youtubeanalytics */ module.exports = Youtubeanalytics;
$(document).ready(function() { pre_content = $("#jalpc_site_pv").html(); $("#jalpc_site_pv").html(pre_content); $.ajax({ type: "get", async: false, url: "https://vps.jack003.com:8443/api/v1.0/jalpc/pv_count", dataType: "jsonp", jsonp: "callback", jsonpCallback: "flightHandler", success: function(json) { var website_count = json.data; $("#jalpc_site_pv").html('<span class="navy">' + website_count + '</span>&nbsp;<span data-i18n="link.view">views</span>&nbsp;||&nbsp;' + pre_content); }, error: function() { console.log('fail'); } }); });
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v12.0.2 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; 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); }; Object.defineProperty(exports, "__esModule", { value: true }); var context_1 = require("../context/context"); var column_1 = require("../entities/column"); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var utils_1 = require("../utils"); var AutoGroupColService = (function () { function AutoGroupColService() { } AutoGroupColService_1 = AutoGroupColService; AutoGroupColService.prototype.createAutoGroupColumns = function (rowGroupColumns) { var _this = this; var groupAutoColumns = []; // if doing groupMultiAutoColumn, then we call the method multiple times, once // for each column we are grouping by if (this.gridOptionsWrapper.isGroupMultiAutoColumn()) { rowGroupColumns.forEach(function (rowGroupCol, index) { groupAutoColumns.push(_this.createOneAutoGroupColumn(rowGroupCol, index)); }); } else { groupAutoColumns.push(this.createOneAutoGroupColumn(null)); } return groupAutoColumns; }; // rowGroupCol and index are missing if groupMultiAutoColumn=false AutoGroupColService.prototype.createOneAutoGroupColumn = function (rowGroupCol, index) { // if one provided by user, use it, otherwise create one var defaultAutoColDef = this.generateDefaultColDef(rowGroupCol, index); var userAutoColDef = this.gridOptionsWrapper.getAutoGroupColumnDef(); // if doing multi, set the field var colId; if (rowGroupCol) { colId = AutoGroupColService_1.GROUP_AUTO_COLUMN_ID + "-" + rowGroupCol.getId(); } else { colId = AutoGroupColService_1.GROUP_AUTO_COLUMN_BUNDLE_ID; } utils_1._.mergeDeep(defaultAutoColDef, userAutoColDef); defaultAutoColDef.colId = colId; //If the user is not telling us his preference with regards wether the filtering //should be suppressed, we suppress it if there are no leaf nodes if (userAutoColDef == null || userAutoColDef.suppressFilter == null) { var produceLeafNodeValues = defaultAutoColDef.field != null || defaultAutoColDef.valueGetter != null; defaultAutoColDef.suppressFilter = !produceLeafNodeValues; } // if showing many cols, we don't want to show more than one with a checkbox for selection if (index > 0) { defaultAutoColDef.headerCheckboxSelection = false; } var newCol = new column_1.Column(defaultAutoColDef, colId, true); this.context.wireBean(newCol); return newCol; }; AutoGroupColService.prototype.generateDefaultColDef = function (rowGroupCol, index) { var localeTextFunc = this.gridOptionsWrapper.getLocaleTextFunc(); var defaultAutoColDef = { headerName: localeTextFunc('group', 'Group'), cellRenderer: 'group' }; // we never allow moving the group column defaultAutoColDef.suppressMovable = true; if (rowGroupCol) { var rowGroupColDef = rowGroupCol.getColDef(); utils_1._.assign(defaultAutoColDef, { // cellRendererParams.groupKey: colDefToCopy.field; headerName: rowGroupColDef.headerName, headerValueGetter: rowGroupColDef.headerValueGetter }); defaultAutoColDef.showRowGroup = rowGroupCol.getColId(); } else { defaultAutoColDef.showRowGroup = true; } return defaultAutoColDef; }; AutoGroupColService.GROUP_AUTO_COLUMN_ID = 'ag-Grid-AutoColumn'; AutoGroupColService.GROUP_AUTO_COLUMN_BUNDLE_ID = AutoGroupColService_1.GROUP_AUTO_COLUMN_ID; __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], AutoGroupColService.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('context'), __metadata("design:type", context_1.Context) ], AutoGroupColService.prototype, "context", void 0); AutoGroupColService = AutoGroupColService_1 = __decorate([ context_1.Bean('autoGroupColService') ], AutoGroupColService); return AutoGroupColService; var AutoGroupColService_1; }()); exports.AutoGroupColService = AutoGroupColService;
version https://git-lfs.github.com/spec/v1 oid sha256:0b4fbf0fb52fb83da41c6260b4a892ed640289c3aeea37becbf67d4337683b10 size 2424
// Tests that a library wrapper has to pass module("Library wrapper"); test("can.trim", function () { }); test("can.makeArray", function () { deepEqual([], can.makeArray(null), "Empty argument creates empty array"); var array = ['one', 'two', 'three']; var made = can.makeArray(array); notEqual(array, can.makeArray(array), "Should return a cloned version of the array"); }); test("can.isArray", function () { }); test("can.inArray", function () { equal(-1, can.inArray('test'), 'Passing an undefined array returns -1'); }) test("can.isPlainObject", function () { }); test("can.extend", function () { }); test("can.isEmptyObject", function () { });
module.exports={title:"Sentry",slug:"sentry",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Sentry icon</title><path d="M13.91 2.505c-.873-1.448-2.972-1.448-3.844 0L6.904 7.92a15.478 15.478 0 0 1 8.53 12.811h-2.221A13.301 13.301 0 0 0 5.784 9.814l-2.926 5.06a7.65 7.65 0 0 1 4.435 5.848H2.194a.365.365 0 0 1-.298-.534l1.413-2.402a5.16 5.16 0 0 0-1.614-.913L.296 19.275a2.182 2.182 0 0 0 .812 2.999 2.24 2.24 0 0 0 1.086.288h6.983a9.322 9.322 0 0 0-3.845-8.318l1.11-1.922a11.47 11.47 0 0 1 4.95 10.24h5.915a17.242 17.242 0 0 0-7.885-15.28l2.244-3.845a.37.37 0 0 1 .504-.13c.255.14 9.75 16.708 9.928 16.9a.365.365 0 0 1-.327.543h-2.287c.029.612.029 1.223 0 1.831h2.297a2.206 2.206 0 0 0 1.922-3.31z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://sentry.io/branding/",hex:"362D59"};
/** * @author sunag / http://www.sunag.com.br/ */ THREE.FloatNode = function( value ) { THREE.InputNode.call( this, 'fv1', { share: false } ); this.value = [ value || 0 ]; }; THREE.FloatNode.prototype = Object.create( THREE.InputNode.prototype ); THREE.FloatNode.prototype.constructor = THREE.FloatNode; Object.defineProperties( THREE.FloatNode.prototype, { number: { get: function() { return this.value[ 0 ]; }, set: function( val ) { this.value[ 0 ] = val; } } } );
/**************************************************************************** Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org 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. ****************************************************************************/ /** * plugin manager * @class * */ (function(){ if(cc === undefined){ return; } //Native plugin usage var PluginManager = function(){}; PluginManager.prototype = { constructor: PluginManager, /** * @returns {PluginManager} * @expose */ getInstance: function(){ return this; }, /** * @param {String} pluginName * @expose */ loadPlugin: function(pluginName){ }, /** * * @param pluginName * @expose */ unloadPlugin: function(pluginName){ } }; var PluginAssembly = function(){}; PluginAssembly.prototype = { constructor: PluginAssembly, /** * @param {Boolean} debug * @expose */ setDebugMode: function(debug){}, /** * @param {String} appKey * @expose */ startSession: function(appKey){}, /** * @param {Boolean} Capture * @expose */ setCaptureUncaughtException: function(Capture){}, /** * @param {String} funName * @param {All} Params * @expose */ callFuncWithParam: function(funName){ if(typeof this[funName] === 'function'){ return this[funName].apply(this, Array.prototype.splice.call(arguments, 1)); }else{ cc.log("function is not define"); } }, /** * @param {String} funName * @param {All} Params * @expose */ callStringFuncWithParam: function(funName){ this.callFuncWithParam.apply(arguments); }, /** * @returns {String} * @expose */ getPluginName: function(){ return this._name; }, /** * @returns {String} * @expose */ getPluginVersion: function(){ return this._version; } }; /** @expose */ PluginAssembly.extend = function(name, porp){ var p, prototype = {}; for(p in PluginAssembly.prototype){ prototype[p] = PluginAssembly.prototype[p]; } for(p in porp){ prototype[p] = porp[p]; } var tmp = eval("(function " + name + "Plugin(){})"); prototype.constructor = tmp; tmp.prototype = prototype; return tmp; }; //Param var Param = function(type, value){ var paramType = plugin.PluginParam.ParamType,tmpValue; switch(type){ case paramType.TypeInt: tmpValue = parseInt(value); break; case paramType.TypeFloat: tmpValue = parseFloat(value); break; case paramType.TypeBool: tmpValue = Boolean(value); break; case paramType.TypeString: tmpValue = String(value); break; case paramType.TypeStringMap: tmpValue = value//JSON.stringify(value); break; default: tmpValue = value; } return tmpValue }; /** @expose */ Param.ParamType = { /** @expose */ TypeInt:1, /** @expose */ TypeFloat:2, /** @expose */ TypeBool:3, /** @expose */ TypeString:4, /** @expose */ TypeStringMap:5 }; /** @expose */ Param.AdsResultCode = { /** @expose */ AdsReceived:0, /** @expose */ FullScreenViewShown:1, /** @expose */ FullScreenViewDismissed:2, /** @expose */ PointsSpendSucceed:3, /** @expose */ PointsSpendFailed:4, /** @expose */ NetworkError:5, /** @expose */ UnknownError:6 }; /** @expose */ Param.PayResultCode = { /** @expose */ PaySuccess:0, /** @expose */ PayFail:1, /** @expose */ PayCancel:2, /** @expose */ PayTimeOut:3 }; /** @expose */ Param.ShareResultCode = { /** @expose */ ShareSuccess:0, /** @expose */ ShareFail:1, /** @expose */ ShareCancel:2, /** @expose */ ShareTimeOut:3 }; /** @expose */ var PluginList = {}; /** @expose */ var Plugin = { /** @expose */ extend: function(name, extend){ var config = (cc.game.config && cc.game.config.plugin) || {}; PluginList[name] = new (PluginAssembly.extend(name, extend)); typeof PluginList[name].ctor === "function" && PluginList[name].ctor(config[name]); }, /** @expose */ PluginList: PluginList, /** @expose */ PluginParam: Param, /** @expose */ PluginManager: new PluginManager() }; /** @expose */ window.plugin = Plugin; })();
/** * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'button', 'it', { selectedLabel: '%1 (selezionato)' } );
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v11.0.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; 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 __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", { value: true }); var gridOptionsWrapper_1 = require("./gridOptionsWrapper"); var context_1 = require("./context/context"); var context_2 = require("./context/context"); var LoggerFactory = (function () { function LoggerFactory() { } LoggerFactory.prototype.setBeans = function (gridOptionsWrapper) { this.logging = gridOptionsWrapper.isDebug(); }; LoggerFactory.prototype.create = function (name) { return new Logger(name, this.isLogging.bind(this)); }; LoggerFactory.prototype.isLogging = function () { return this.logging; }; return LoggerFactory; }()); __decorate([ __param(0, context_2.Qualifier('gridOptionsWrapper')), __metadata("design:type", Function), __metadata("design:paramtypes", [gridOptionsWrapper_1.GridOptionsWrapper]), __metadata("design:returntype", void 0) ], LoggerFactory.prototype, "setBeans", null); LoggerFactory = __decorate([ context_1.Bean('loggerFactory') ], LoggerFactory); exports.LoggerFactory = LoggerFactory; var Logger = (function () { function Logger(name, isLoggingFunc) { this.name = name; this.isLoggingFunc = isLoggingFunc; } Logger.prototype.isLogging = function () { return this.isLoggingFunc(); }; Logger.prototype.log = function (message) { if (this.isLoggingFunc()) { console.log('ag-Grid.' + this.name + ': ' + message); } }; return Logger; }()); exports.Logger = Logger;
"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 async_1 = require('../scheduler/async'); var isDate_1 = require('../util/isDate'); var Subscriber_1 = require('../Subscriber'); var Notification_1 = require('../Notification'); /** * Delays the emission of items from the source Observable by a given timeout or * until a given Date. * * <span class="informal">Time shifts each item by some specified amount of * milliseconds.</span> * * <img src="./img/delay.png" width="100%"> * * If the delay argument is a Number, this operator time shifts the source * Observable by that amount of time expressed in milliseconds. The relative * time intervals between the values are preserved. * * If the delay argument is a Date, this operator time shifts the start of the * Observable execution until the given date occurs. * * @example <caption>Delay each click by one second</caption> * var clicks = Rx.Observable.fromEvent(document, 'click'); * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second * delayedClicks.subscribe(x => console.log(x)); * * @example <caption>Delay all clicks until a future date happens</caption> * var clicks = Rx.Observable.fromEvent(document, 'click'); * var date = new Date('March 15, 2050 12:00:00'); // in the future * var delayedClicks = clicks.delay(date); // click emitted only after that date * delayedClicks.subscribe(x => console.log(x)); * * @see {@link debounceTime} * @see {@link delayWhen} * * @param {number|Date} delay The delay duration in milliseconds (a `number`) or * a `Date` until which the emission of the source items is delayed. * @param {Scheduler} [scheduler=async] The IScheduler to use for * managing the timers that handle the time-shift for each item. * @return {Observable} An Observable that delays the emissions of the source * Observable by the specified timeout or Date. * @method delay * @owner Observable */ function delay(delay, scheduler) { if (scheduler === void 0) { scheduler = async_1.async; } var absoluteDelay = isDate_1.isDate(delay); var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay); return function (source) { return source.lift(new DelayOperator(delayFor, scheduler)); }; } exports.delay = delay; var DelayOperator = (function () { function DelayOperator(delay, scheduler) { this.delay = delay; this.scheduler = scheduler; } DelayOperator.prototype.call = function (subscriber, source) { return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler)); }; return DelayOperator; }()); /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ var DelaySubscriber = (function (_super) { __extends(DelaySubscriber, _super); function DelaySubscriber(destination, delay, scheduler) { _super.call(this, destination); this.delay = delay; this.scheduler = scheduler; this.queue = []; this.active = false; this.errored = false; } DelaySubscriber.dispatch = function (state) { var source = state.source; var queue = source.queue; var scheduler = state.scheduler; var destination = state.destination; while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) { queue.shift().notification.observe(destination); } if (queue.length > 0) { var delay_1 = Math.max(0, queue[0].time - scheduler.now()); this.schedule(state, delay_1); } else { this.unsubscribe(); source.active = false; } }; DelaySubscriber.prototype._schedule = function (scheduler) { this.active = true; this.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, { source: this, destination: this.destination, scheduler: scheduler })); }; DelaySubscriber.prototype.scheduleNotification = function (notification) { if (this.errored === true) { return; } var scheduler = this.scheduler; var message = new DelayMessage(scheduler.now() + this.delay, notification); this.queue.push(message); if (this.active === false) { this._schedule(scheduler); } }; DelaySubscriber.prototype._next = function (value) { this.scheduleNotification(Notification_1.Notification.createNext(value)); }; DelaySubscriber.prototype._error = function (err) { this.errored = true; this.queue = []; this.destination.error(err); }; DelaySubscriber.prototype._complete = function () { this.scheduleNotification(Notification_1.Notification.createComplete()); }; return DelaySubscriber; }(Subscriber_1.Subscriber)); var DelayMessage = (function () { function DelayMessage(time, notification) { this.time = time; this.notification = notification; } return DelayMessage; }()); //# sourceMappingURL=delay.js.map
/** * @author yamahigashi https://github.com/yamahigashi * * This loader loads FBX file in *ASCII and version 7 format*. * * Support * - mesh * - skinning * - normal / uv * * Not Support * - material * - texture * - morph */ ( function() { THREE.FBXLoader = function ( showStatus, manager ) { THREE.Loader.call( this, showStatus ); this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; this.textureLoader = null; this.textureBasePath = null; }; THREE.FBXLoader.prototype = Object.create( THREE.Loader.prototype ); THREE.FBXLoader.prototype.constructor = THREE.FBXLoader; THREE.FBXLoader.prototype.load = function ( url, onLoad, onProgress, onError ) { var scope = this; var loader = new THREE.XHRLoader( scope.manager ); // loader.setCrossOrigin( this.crossOrigin ); loader.load( url, function ( text ) { if ( ! scope.isFbxFormatASCII( text ) ) { console.warn( 'FBXLoader: !!! FBX Binary format not supported !!!' ); } else if ( ! scope.isFbxVersionSupported( text ) ) { console.warn( 'FBXLoader: !!! FBX Version below 7 not supported !!!' ); } else { scope.textureBasePath = scope.extractUrlBase( url ); onLoad( scope.parse( text ) ); } }, onProgress, onError ); }; THREE.FBXLoader.prototype.setCrossOrigin = function ( value ) { this.crossOrigin = value; }; THREE.FBXLoader.prototype.isFbxFormatASCII = function ( body ) { CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ]; var cursor = 0; var read = function ( offset ) { var result = body[ offset - 1 ]; body = body.slice( cursor + offset ); cursor ++; return result; }; for ( var i = 0; i < CORRECT.length; ++ i ) { num = read( 1 ); if ( num == CORRECT[ i ] ) { return false; } } return true; }; THREE.FBXLoader.prototype.isFbxVersionSupported = function ( body ) { var versionExp = /FBXVersion: (\d+)/; match = body.match( versionExp ); if ( match ) { var version = parseInt( match[ 1 ] ); console.log( 'FBXLoader: FBX version ' + version ); return version >= 7000; } return false; }; THREE.FBXLoader.prototype.parse = function ( text ) { var scope = this; console.time( 'FBXLoader' ); console.time( 'FBXLoader: TextParser' ); var nodes = new FBXParser().parse( text ); console.timeEnd( 'FBXLoader: TextParser' ); console.time( 'FBXLoader: ObjectParser' ); scope.hierarchy = ( new Bones() ).parseHierarchy( nodes ); scope.weights = ( new Weights() ).parse( nodes, scope.hierarchy ); scope.animations = ( new Animation() ).parse( nodes, scope.hierarchy ); scope.textures = ( new Textures() ).parse( nodes, scope.hierarchy ); console.timeEnd( 'FBXLoader: ObjectParser' ); console.time( 'FBXLoader: GeometryParser' ); geometries = this.parseGeometries( nodes ); console.timeEnd( 'FBXLoader: GeometryParser' ); var container = new THREE.Group(); for ( var i = 0; i < geometries.length; ++ i ) { if ( geometries[ i ] === undefined ) { continue; } container.add( geometries[ i ] ); //wireframe = new THREE.WireframeHelper( geometries[i], 0x00ff00 ); //container.add( wireframe ); //vnh = new THREE.VertexNormalsHelper( geometries[i], 0.6 ); //container.add( vnh ); //skh = new THREE.SkeletonHelper( geometries[i] ); //container.add( skh ); // container.add( new THREE.BoxHelper( geometries[i] ) ); } console.timeEnd( 'FBXLoader' ); return container; }; THREE.FBXLoader.prototype.parseGeometries = function ( node ) { // has not geo, return [] if ( ! ( 'Geometry' in node.Objects.subNodes ) ) { return []; } // has many var geoCount = 0; for ( var geo in node.Objects.subNodes.Geometry ) { if ( geo.match( /^\d+$/ ) ) { geoCount ++; } } var res = []; if ( geoCount > 0 ) { for ( geo in node.Objects.subNodes.Geometry ) { if ( node.Objects.subNodes.Geometry[ geo ].attrType === 'Mesh' ) { res.push( this.parseGeometry( node.Objects.subNodes.Geometry[ geo ], node ) ); } } } else { res.push( this.parseGeometry( node.Objects.subNodes.Geometry, node ) ); } return res; }; THREE.FBXLoader.prototype.parseGeometry = function ( node, nodes ) { geo = ( new Geometry() ).parse( node ); geo.addBones( this.hierarchy.hierarchy ); //* var geometry = new THREE.BufferGeometry(); geometry.name = geo.name; geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( geo.vertices ), 3 ) ); if ( geo.normals !== undefined && geo.normals.length > 0 ) { geometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( geo.normals ), 3 ) ); } if ( geo.uvs !== undefined && geo.uvs.length > 0 ) { geometry.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( geo.uvs ), 2 ) ); } if ( geo.indices !== undefined && geo.indices.length > 65535 ) { geometry.setIndex( new THREE.BufferAttribute( new Uint32Array( geo.indices ), 1 ) ); } else if ( geo.indices !== undefined ) { geometry.setIndex( new THREE.BufferAttribute( new Uint16Array( geo.indices ), 1 ) ); } geometry.verticesNeedUpdate = true; geometry.computeBoundingSphere(); geometry.computeBoundingBox(); // TODO: texture & material support var texture; var texs = this.textures.getById( nodes.searchConnectionParent( geo.id ) ); if ( texs !== undefined && texs.length > 0 ) { if ( this.textureLoader === null ) { this.textureLoader = new THREE.TextureLoader(); } texture = this.textureLoader.load( this.textureBasePath + '/' + texs[ 0 ].fileName ); } var material; if ( texture !== undefined ) { material = new THREE.MeshBasicMaterial( { map: texture } ); } else { material = new THREE.MeshBasicMaterial( { color: 0x3300ff } ); } geometry = new THREE.Geometry().fromBufferGeometry( geometry ); geometry.bones = geo.bones; geometry.skinIndices = this.weights.skinIndices; geometry.skinWeights = this.weights.skinWeights; var mesh = null; if ( geo.bones === undefined || geo.skins === undefined || this.animations === undefined || this.animations.length === 0 ) { mesh = new THREE.Mesh( geometry, material ); } else { material.skinning = true; mesh = new THREE.SkinnedMesh( geometry, material ); this.addAnimation( mesh, this.weights.matrices, this.animations ); } return mesh; }; THREE.FBXLoader.prototype.addAnimation = function ( mesh, matrices, animations ) { var animationdata = { "name": 'animationtest', "fps": 30, "length": animations.length, "hierarchy": [] }; for ( var i = 0; i < mesh.geometry.bones.length; ++ i ) { var name = mesh.geometry.bones[ i ].name; name = name.replace( /.*:/, '' ); animationdata.hierarchy.push( { parent: mesh.geometry.bones[ i ].parent, name: name, keys: [] } ); } var hasCurve = function ( animNode, attr ) { if ( animNode === undefined ) { return false; } var attrNode; switch ( attr ) { case 'S': if ( animNode.S === undefined ) { return false; } attrNode = animNode.S; break; case 'R': if ( animNode.R === undefined ) { return false; } attrNode = animNode.R; break; case 'T': if ( animNode.T === undefined ) { return false; } attrNode = animNode.T; break; } if ( attrNode.curves.x === undefined ) { return false; } if ( attrNode.curves.y === undefined ) { return false; } if ( attrNode.curves.z === undefined ) { return false; } return true; }; var hasKeyOnFrame = function ( attrNode, frame ) { var x = isKeyExistOnFrame( attrNode.curves.x, frame ); var y = isKeyExistOnFrame( attrNode.curves.y, frame ); var z = isKeyExistOnFrame( attrNode.curves.z, frame ); return x && y && z; }; var isKeyExistOnFrame = function ( curve, frame ) { var value = curve.values[ frame ]; return value !== undefined; }; var genKey = function ( animNode, bone ) { // key initialize with its bone's bind pose at first var key = {}; key.time = frame / animations.fps; // TODO: key.pos = bone.pos; key.rot = bone.rotq; key.scl = bone.scl; if ( animNode === undefined ) { return key; } try { if ( hasCurve( animNode, 'T' ) && hasKeyOnFrame( animNode.T, frame ) ) { var pos = new THREE.Vector3( animNode.T.curves.x.values[ frame ], animNode.T.curves.y.values[ frame ], animNode.T.curves.z.values[ frame ] ); key.pos = [ pos.x, pos.y, pos.z ]; } else { delete key.pos; } if ( hasCurve( animNode, 'R' ) && hasKeyOnFrame( animNode.R, frame ) ) { var rx = degToRad( animNode.R.curves.x.values[ frame ] ); var ry = degToRad( animNode.R.curves.y.values[ frame ] ); var rz = degToRad( animNode.R.curves.z.values[ frame ] ); var eul = new THREE.Vector3( rx, ry, rz ); var rot = quatFromVec( eul.x, eul.y, eul.z ); key.rot = [ rot.x, rot.y, rot.z, rot.w ]; } else { delete key.rot; } if ( hasCurve( animNode, 'S' ) && hasKeyOnFrame( animNode.S, frame ) ) { var scl = new THREE.Vector3( animNode.S.curves.x.values[ frame ], animNode.S.curves.y.values[ frame ], animNode.S.curves.z.values[ frame ] ); key.scl = [ scl.x, scl.y, scl.z ]; } else { delete key.scl; } } catch ( e ) { // curve is not full plotted console.log( bone ); console.log( e ); } return key; }; var bones = mesh.geometry.bones; for ( frame = 0; frame < animations.frames; frame ++ ) { for ( i = 0; i < bones.length; i ++ ) { var bone = bones[ i ]; var animNode = animations.curves[ i ]; for ( var j = 0; j < animationdata.hierarchy.length; j ++ ) { if ( animationdata.hierarchy[ j ].name === bone.name ) { animationdata.hierarchy[ j ].keys.push( genKey( animNode, bone ) ); } } } } if ( mesh.geometry.animations === undefined ) { mesh.geometry.animations = []; } mesh.geometry.animations.push( THREE.AnimationClip.parseAnimation( animationdata, mesh.geometry.bones ) ); }; THREE.FBXLoader.prototype.parseMaterials = function ( node ) { // has not mat, return [] if ( ! ( 'Material' in node.subNodes ) ) { return []; } // has many var matCount = 0; for ( var mat in node.subNodes.Materials ) { if ( mat.match( /^\d+$/ ) ) { matCount ++; } } var res = []; if ( matCount > 0 ) { for ( mat in node.subNodes.Material ) { res.push( parseMaterial( node.subNodes.Material[ mat ] ) ); } } else { res.push( parseMaterial( node.subNodes.Material ) ); } return res; }; // TODO THREE.FBXLoader.prototype.parseMaterial = function ( node ) { }; THREE.FBXLoader.prototype.loadFile = function ( url, onLoad, onProgress, onError, responseType ) { var loader = new THREE.XHRLoader( this.manager ); loader.setResponseType( responseType ); var request = loader.load( url, function ( result ) { onLoad( result ); }, onProgress, onError ); return request; }; THREE.FBXLoader.prototype.loadFileAsBuffer = function ( url, onload, onProgress, onError ) { this.loadFile( url, onLoad, onProgress, onError, 'arraybuffer' ); }; THREE.FBXLoader.prototype.loadFileAsText = function ( url, onLoad, onProgress, onError ) { this.loadFile( url, onLoad, onProgress, onError, 'text' ); }; /* ----------------------------------------------------------------- */ function FBXNodes() {} FBXNodes.prototype.add = function ( key, val ) { this[ key ] = val; }; FBXNodes.prototype.searchConnectionParent = function ( id ) { if ( this.__cache_search_connection_parent === undefined ) { this.__cache_search_connection_parent = []; } if ( this.__cache_search_connection_parent[ id ] !== undefined ) { return this.__cache_search_connection_parent[ id ]; } else { this.__cache_search_connection_parent[ id ] = []; } var conns = this.Connections.properties.connections; var results = []; for ( var i = 0; i < conns.length; ++ i ) { if ( conns[ i ][ 0 ] == id ) { // 0 means scene root var res = conns[ i ][ 1 ] === 0 ? - 1 : conns[ i ][ 1 ]; results.push( res ); } } if ( results.length > 0 ) { this.__cache_search_connection_parent[ id ] = this.__cache_search_connection_parent[ id ].concat( results ); return results; } else { this.__cache_search_connection_parent[ id ] = [ - 1 ]; return [ - 1 ]; } }; FBXNodes.prototype.searchConnectionChildren = function ( id ) { if ( this.__cache_search_connection_children === undefined ) { this.__cache_search_connection_children = []; } if ( this.__cache_search_connection_children[ id ] !== undefined ) { return this.__cache_search_connection_children[ id ]; } else { this.__cache_search_connection_children[ id ] = []; } var conns = this.Connections.properties.connections; var res = []; for ( var i = 0; i < conns.length; ++ i ) { if ( conns[ i ][ 1 ] == id ) { // 0 means scene root res.push( conns[ i ][ 0 ] === 0 ? - 1 : conns[ i ][ 0 ] ); // there may more than one kid, then search to the end } } if ( res.length > 0 ) { this.__cache_search_connection_children[ id ] = this.__cache_search_connection_children[ id ].concat( res ); return res; } else { this.__cache_search_connection_children[ id ] = [ - 1 ]; return [ - 1 ]; } }; FBXNodes.prototype.searchConnectionType = function ( id, to ) { var key = id + ',' + to; // TODO: to hash if ( this.__cache_search_connection_type === undefined ) { this.__cache_search_connection_type = ''; } if ( this.__cache_search_connection_type[ key ] !== undefined ) { return this.__cache_search_connection_type[ key ]; } else { this.__cache_search_connection_type[ key ] = ''; } var conns = this.Connections.properties.connections; for ( var i = 0; i < conns.length; ++ i ) { if ( conns[ i ][ 0 ] == id && conns[ i ][ 1 ] == to ) { // 0 means scene root this.__cache_search_connection_type[ key ] = conns[ i ][ 2 ]; return conns[ i ][ 2 ]; } } this.__cache_search_connection_type[ id ] = null; return null; }; function FBXParser() {} FBXParser.prototype = { // constructor: FBXParser, // ------------ node stack manipulations ---------------------------------- getPrevNode: function () { return this.nodeStack[ this.currentIndent - 2 ]; }, getCurrentNode: function () { return this.nodeStack[ this.currentIndent - 1 ]; }, getCurrentProp: function () { return this.currentProp; }, pushStack: function ( node ) { this.nodeStack.push( node ); this.currentIndent += 1; }, popStack: function () { this.nodeStack.pop(); this.currentIndent -= 1; }, setCurrentProp: function ( val, name ) { this.currentProp = val; this.currentPropName = name; }, // ----------parse --------------------------------------------------- parse: function ( text ) { this.currentIndent = 0; this.allNodes = new FBXNodes(); this.nodeStack = []; this.currentProp = []; this.currentPropName = ''; var split = text.split( "\n" ); for ( var line in split ) { var l = split[ line ]; // short cut if ( l.match( /^[\s\t]*;/ ) ) { continue; } // skip comment line if ( l.match( /^[\s\t]*$/ ) ) { continue; } // skip empty line // beginning of node var beginningOfNodeExp = new RegExp( "^\\t{" + this.currentIndent + "}(\\w+):(.*){", '' ); match = l.match( beginningOfNodeExp ); if ( match ) { var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, "" ); var nodeAttrs = match[ 2 ].split( ',' ).map( function ( element ) { return element.trim().replace( /^"/, '' ).replace( /"$/, '' ); } ); this.parseNodeBegin( l, nodeName, nodeAttrs || null ); continue; } // node's property var propExp = new RegExp( "^\\t{" + ( this.currentIndent ) + "}(\\w+):[\\s\\t\\r\\n](.*)" ); match = l.match( propExp ); if ( match ) { var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, "" ).trim(); var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, "" ).trim(); this.parseNodeProperty( l, propName, propValue ); continue; } // end of node var endOfNodeExp = new RegExp( "^\\t{" + ( this.currentIndent - 1 ) + "}}" ); if ( l.match( endOfNodeExp ) ) { this.nodeEnd(); continue; } // for special case, // // Vertices: *8670 { // a: 0.0356229953467846,13.9599733352661,-0.399196773.....(snip) // -0.0612030513584614,13.960485458374,-0.409748703241348,-0.10..... // 0.12490539252758,13.7450733184814,-0.454119384288788,0.09272..... // 0.0836158767342567,13.5432004928589,-0.435397416353226,0.028..... // // these case the lines must contiue with previous line if ( l.match( /^[^\s\t}]/ ) ) { this.parseNodePropertyContinued( l ); } } return this.allNodes; }, parseNodeBegin: function ( line, nodeName, nodeAttrs ) { // var nodeName = match[1]; var node = { 'name': nodeName, properties: {}, 'subNodes': {} }; var attrs = this.parseNodeAttr( nodeAttrs ); var currentNode = this.getCurrentNode(); // a top node if ( this.currentIndent === 0 ) { this.allNodes.add( nodeName, node ); } else { // a subnode // already exists subnode, then append it if ( nodeName in currentNode.subNodes ) { var tmp = currentNode.subNodes[ nodeName ]; // console.log( "duped entry found\nkey: " + nodeName + "\nvalue: " + propValue ); if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) { if ( attrs.id === '' ) { currentNode.subNodes[ nodeName ] = []; currentNode.subNodes[ nodeName ].push( tmp ); } else { currentNode.subNodes[ nodeName ] = {}; currentNode.subNodes[ nodeName ][ tmp.id ] = tmp; } } if ( attrs.id === '' ) { currentNode.subNodes[ nodeName ].push( node ); } else { currentNode.subNodes[ nodeName ][ attrs.id ] = node; } } else { currentNode.subNodes[ nodeName ] = node; } } // for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ // NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" { if ( nodeAttrs ) { node.id = attrs.id; node.attrName = attrs.name; node.attrType = attrs.type; } this.pushStack( node ); }, parseNodeAttr: function ( attrs ) { var id = attrs[ 0 ]; if ( attrs[ 0 ] !== "" ) { id = parseInt( attrs[ 0 ] ); if ( isNaN( id ) ) { // PolygonVertexIndex: *16380 { id = attrs[ 0 ]; } } var name; var type; if ( attrs.length > 1 ) { name = attrs[ 1 ].replace( /^(\w+)::/, '' ); type = attrs[ 2 ]; } return { id: id, name: name || '', type: type || '' }; }, parseNodeProperty: function ( line, propName, propValue ) { var currentNode = this.getCurrentNode(); var parentName = currentNode.name; // special case parent node's is like "Properties70" // these chilren nodes must treat with careful if ( parentName !== undefined ) { var propMatch = parentName.match( /Properties(\d)+/ ); if ( propMatch ) { this.parseNodeSpecialProperty( line, propName, propValue ); return; } } // special case Connections if ( propName == 'C' ) { var connProps = propValue.split( ',' ).slice( 1 ); var from = parseInt( connProps[ 0 ] ); var to = parseInt( connProps[ 1 ] ); var rest = propValue.split( ',' ).slice( 3 ); propName = 'connections'; propValue = [ from, to ]; propValue = propValue.concat( rest ); if ( currentNode.properties[ propName ] === undefined ) { currentNode.properties[ propName ] = []; } } // special case Connections if ( propName == 'Node' ) { var id = parseInt( propValue ); currentNode.properties.id = id; currentNode.id = id; } // already exists in properties, then append this if ( propName in currentNode.properties ) { // console.log( "duped entry found\nkey: " + propName + "\nvalue: " + propValue ); if ( Array.isArray( currentNode.properties[ propName ] ) ) { currentNode.properties[ propName ].push( propValue ); } else { currentNode.properties[ propName ] += propValue; } } else { // console.log( propName + ": " + propValue ); if ( Array.isArray( currentNode.properties[ propName ] ) ) { currentNode.properties[ propName ].push( propValue ); } else { currentNode.properties[ propName ] = propValue; } } this.setCurrentProp( currentNode.properties, propName ); }, // TODO: parseNodePropertyContinued: function ( line ) { this.currentProp[ this.currentPropName ] += line; }, parseNodeSpecialProperty: function ( line, propName, propValue ) { // split this // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1 // into array like below // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ] var props = propValue.split( '",' ).map( function ( element ) { return element.trim().replace( /^\"/, '' ).replace( /\s/, '_' ); } ); var innerPropName = props[ 0 ]; var innerPropType1 = props[ 1 ]; var innerPropType2 = props[ 2 ]; var innerPropFlag = props[ 3 ]; var innerPropValue = props[ 4 ]; /* if ( innerPropValue === undefined ) { innerPropValue = props[3]; } */ // cast value in its type switch ( innerPropType1 ) { case "int": innerPropValue = parseInt( innerPropValue ); break; case "double": innerPropValue = parseFloat( innerPropValue ); break; case "ColorRGB": case "Vector3D": var tmp = innerPropValue.split( ',' ); innerPropValue = new THREE.Vector3( tmp[ 0 ], tmp[ 1 ], tmp[ 2 ] ); break; } // CAUTION: these props must append to parent's parent this.getPrevNode().properties[ innerPropName ] = { 'type': innerPropType1, 'type2': innerPropType2, 'flag': innerPropFlag, 'value': innerPropValue }; this.setCurrentProp( this.getPrevNode().properties, innerPropName ); }, nodeEnd: function ( line ) { this.popStack(); }, /* ---------------------------------------------------------------- */ /* util */ isFlattenNode: function ( node ) { return ( 'subNodes' in node && 'properties' in node ) ? true : false; } }; function FBXAnalyzer() {} FBXAnalyzer.prototype = { }; // generate skinIndices, skinWeights // @skinIndices: per vertex data, this represents the bone indexes affects that vertex // @skinWeights: per vertex data, this represents the Weight Values affects that vertex // @matrices: per `bones` data function Weights() { this.skinIndices = []; this.skinWeights = []; this.matrices = []; } Weights.prototype.parseCluster = function ( node, id, entry ) { var _p = node.searchConnectionParent( id ); var _indices = toInt( entry.subNodes.Indexes.properties.a.split( ',' ) ); var _weights = toFloat( entry.subNodes.Weights.properties.a.split( ',' ) ); var _transform = toMat44( toFloat( entry.subNodes.Transform.properties.a.split( ',' ) ) ); var _link = toMat44( toFloat( entry.subNodes.TransformLink.properties.a.split( ',' ) ) ); return { 'parent': _p, 'id': parseInt( id ), 'indices': _indices, 'weights': _weights, 'transform': _transform, 'transformlink': _link, 'linkMode': entry.properties.Mode }; }; Weights.prototype.parse = function ( node, bones ) { this.skinIndices = []; this.skinWeights = []; this.matrices = []; var deformers = node.Objects.subNodes.Deformer; var clusters = {}; for ( var id in deformers ) { if ( deformers[ id ].attrType === 'Cluster' ) { if ( ! ( 'Indexes' in deformers[ id ].subNodes ) ) { continue; } //clusters.push( this.parseCluster( node, id, deformers[id] ) ); var cluster = this.parseCluster( node, id, deformers[ id ] ); var boneId = node.searchConnectionChildren( cluster.id )[ 0 ]; clusters[ boneId ] = cluster; } } // this clusters is per Bone data, thus we make this into per vertex data var weights = []; var hi = bones.hierarchy; for ( var b = 0; b < hi.length; ++ b ) { var bid = hi[ b ].internalId; if ( clusters[ bid ] === undefined ) { //console.log( bid ); this.matrices.push( new THREE.Matrix4() ); continue; } var clst = clusters[ bid ]; // store transform matrix per bones this.matrices.push( clst.transform ); //this.matrices.push( clst.transformlink ); for ( var v = 0; v < clst.indices.length; ++ v ) { if ( weights[ clst.indices[ v ] ] === undefined ) { weights[ clst.indices[ v ] ] = {}; weights[ clst.indices[ v ] ].joint = []; weights[ clst.indices[ v ] ].weight = []; } // indices var affect = node.searchConnectionChildren( clst.id ); if ( affect.length > 1 ) { console.warn( "FBXLoader: node " + clst.id + " have many weight kids: " + affect ); } weights[ clst.indices[ v ] ].joint.push( bones.getBoneIdfromInternalId( node, affect[ 0 ] ) ); // weight value weights[ clst.indices[ v ] ].weight.push( clst.weights[ v ] ); } } // normalize the skin weights // TODO - this might be a good place to choose greatest 4 weights for ( var i = 0; i < weights.length; i ++ ) { var indicies = new THREE.Vector4( weights[ i ].joint[ 0 ] ? weights[ i ].joint[ 0 ] : 0, weights[ i ].joint[ 1 ] ? weights[ i ].joint[ 1 ] : 0, weights[ i ].joint[ 2 ] ? weights[ i ].joint[ 2 ] : 0, weights[ i ].joint[ 3 ] ? weights[ i ].joint[ 3 ] : 0 ); var weight = new THREE.Vector4( weights[ i ].weight[ 0 ] ? weights[ i ].weight[ 0 ] : 0, weights[ i ].weight[ 1 ] ? weights[ i ].weight[ 1 ] : 0, weights[ i ].weight[ 2 ] ? weights[ i ].weight[ 2 ] : 0, weights[ i ].weight[ 3 ] ? weights[ i ].weight[ 3 ] : 0 ); this.skinIndices.push( indicies ); this.skinWeights.push( weight ); } //console.log( this ); return this; }; function Bones() { // returns bones hierarchy tree. // [ // { // "parent": id, // "name": name, // "pos": pos, // "rotq": quat // }, // ... // {}, // ... // ] // /* sample response "bones" : [ {"parent":-1, "name":"Fbx01", "pos":[-0.002, 98.739, 1.6e-05], "rotq":[0, 0, 0, 1]}, {"parent":0, "name":"Fbx01_Pelvis", "pos":[0.00015963, 0, 7.33107e-08], "rotq":[0, 0, 0, 1]}, {"parent":1, "name":"Fbx01_Spine", "pos":[6.577e-06, 10.216, 0.0106811], "rotq":[0, 0, 0, 1]}, {"parent":2, "name":"Fbx01_R_Thigh", "pos":[14.6537, -10.216, -0.00918758], "rotq":[0, 0, 0, 1]}, {"parent":3, "name":"Fbx01_R_Calf", "pos":[-3.70047, -42.9681, -7.78158], "rotq":[0, 0, 0, 1]}, {"parent":4, "name":"Fbx01_R_Foot", "pos":[-2.0696, -46.0488, 9.42052], "rotq":[0, 0, 0, 1]}, {"parent":5, "name":"Fbx01_R_Toe0", "pos":[-0.0234785, -9.46233, -15.3187], "rotq":[0, 0, 0, 1]}, {"parent":2, "name":"Fbx01_L_Thigh", "pos":[-14.6537, -10.216, -0.00918314], "rotq":[0, 0, 0, 1]}, {"parent":7, "name":"Fbx01_L_Calf", "pos":[3.70037, -42.968, -7.78155], "rotq":[0, 0, 0, 1]}, {"parent":8, "name":"Fbx01_L_Foot", "pos":[2.06954, -46.0488, 9.42052], "rotq":[0, 0, 0, 1]}, {"parent":9, "name":"Fbx01_L_Toe0", "pos":[0.0234566, -9.46235, -15.3187], "rotq":[0, 0, 0, 1]}, {"parent":2, "name":"Fbx01_Spine1", "pos":[-2.97523e-05, 11.5892, -9.81027e-05], "rotq":[0, 0, 0, 1]}, {"parent":11, "name":"Fbx01_Spine2", "pos":[-2.91292e-05, 11.4685, 8.27126e-05], "rotq":[0, 0, 0, 1]}, {"parent":12, "name":"Fbx01_Spine3", "pos":[-4.48857e-05, 11.5783, 8.35108e-05], "rotq":[0, 0, 0, 1]}, {"parent":13, "name":"Fbx01_Neck", "pos":[1.22987e-05, 11.5582, -0.0044775], "rotq":[0, 0, 0, 1]}, {"parent":14, "name":"Fbx01_Head", "pos":[-3.50709e-05, 6.62915, -0.00523254], "rotq":[0, 0, 0, 1]}, {"parent":15, "name":"Fbx01_R_Eye", "pos":[3.31681, 12.739, -10.5267], "rotq":[0, 0, 0, 1]}, {"parent":15, "name":"Fbx01_L_Eye", "pos":[-3.32038, 12.7391, -10.5267], "rotq":[0, 0, 0, 1]}, {"parent":15, "name":"Jaw", "pos":[-0.0017738, 7.43481, -4.08114], "rotq":[0, 0, 0, 1]}, {"parent":14, "name":"Fbx01_R_Clavicle", "pos":[3.10919, 2.46577, -0.0115284], "rotq":[0, 0, 0, 1]}, {"parent":19, "name":"Fbx01_R_UpperArm", "pos":[16.014, 4.57764e-05, 3.10405], "rotq":[0, 0, 0, 1]}, {"parent":20, "name":"Fbx01_R_Forearm", "pos":[22.7068, -1.66322, -2.13803], "rotq":[0, 0, 0, 1]}, {"parent":21, "name":"Fbx01_R_Hand", "pos":[25.5881, -0.80249, -6.37307], "rotq":[0, 0, 0, 1]}, ... {"parent":27, "name":"Fbx01_R_Finger32", "pos":[2.15572, -0.548737, -0.539604], "rotq":[0, 0, 0, 1]}, {"parent":22, "name":"Fbx01_R_Finger2", "pos":[9.79318, 0.132553, -2.97845], "rotq":[0, 0, 0, 1]}, {"parent":29, "name":"Fbx01_R_Finger21", "pos":[2.74037, 0.0483093, -0.650531], "rotq":[0, 0, 0, 1]}, {"parent":55, "name":"Fbx01_L_Finger02", "pos":[-1.65308, -1.43208, -1.82885], "rotq":[0, 0, 0, 1]} ] */ this.hierarchy = []; } Bones.prototype.parseHierarchy = function ( node ) { var objects = node.Objects; var models = objects.subNodes.Model; var bones = []; for ( var id in models ) { if ( models[ id ].attrType === undefined ) { continue; } bones.push( models[ id ] ); } this.hierarchy = []; for ( var i = 0; i < bones.length; ++ i ) { var bone = bones[ i ]; var p = node.searchConnectionParent( bone.id )[ 0 ]; var t = [ 0.0, 0.0, 0.0 ]; var r = [ 0.0, 0.0, 0.0, 1.0 ]; var s = [ 1.0, 1.0, 1.0 ]; if ( 'Lcl_Translation' in bone.properties ) { t = toFloat( bone.properties.Lcl_Translation.value.split( ',' ) ); } if ( 'Lcl_Rotation' in bone.properties ) { r = toRad( toFloat( bone.properties.Lcl_Rotation.value.split( ',' ) ) ); var q = new THREE.Quaternion(); q.setFromEuler( new THREE.Euler( r[ 0 ], r[ 1 ], r[ 2 ], 'ZYX' ) ); r = [ q.x, q.y, q.z, q.w ]; } if ( 'Lcl_Scaling' in bone.properties ) { s = toFloat( bone.properties.Lcl_Scaling.value.split( ',' ) ); } // replace unsafe character var name = bone.attrName; name = name.replace( /:/, '' ); name = name.replace( /_/, '' ); name = name.replace( /-/, '' ); this.hierarchy.push( { "parent": p, "name": name, "pos": t, "rotq": r, "scl": s, "internalId": bone.id } ); } this.reindexParentId(); this.restoreBindPose( node ); return this; }; Bones.prototype.reindexParentId = function () { for ( var h = 0; h < this.hierarchy.length; h ++ ) { for ( var ii = 0; ii < this.hierarchy.length; ++ ii ) { if ( this.hierarchy[ h ].parent == this.hierarchy[ ii ].internalId ) { this.hierarchy[ h ].parent = ii; break; } } } }; Bones.prototype.restoreBindPose = function ( node ) { var bindPoseNode = node.Objects.subNodes.Pose; if ( bindPoseNode === undefined ) { return; } var poseNode = bindPoseNode.subNodes.PoseNode; var localMatrices = {}; // store local matrices, modified later( initialy world space ) var worldMatrices = {}; // store world matrices for ( var i = 0; i < poseNode.length; ++ i ) { var rawMatLcl = toMat44( poseNode[ i ].subNodes.Matrix.properties.a.split( ',' ) ); var rawMatWrd = toMat44( poseNode[ i ].subNodes.Matrix.properties.a.split( ',' ) ); localMatrices[ poseNode[ i ].id ] = rawMatLcl; worldMatrices[ poseNode[ i ].id ] = rawMatWrd; } for ( var h = 0; h < this.hierarchy.length; ++ h ) { var bone = this.hierarchy[ h ]; var inId = bone.internalId; if ( worldMatrices[ inId ] === undefined ) { // has no bind pose node, possibly be mesh // console.log( bone ); continue; } var t = new THREE.Vector3( 0, 0, 0 ); var r = new THREE.Quaternion(); var s = new THREE.Vector3( 1, 1, 1 ); var parentId; var parentNodes = node.searchConnectionParent( inId ); for ( var pn = 0; pn < parentNodes.length; ++ pn ) { if ( this.isBoneNode( parentNodes[ pn ] ) ) { parentId = parentNodes[ pn ]; break; } } if ( parentId !== undefined && localMatrices[ parentId ] !== undefined ) { // convert world space matrix into local space var inv = new THREE.Matrix4(); inv.getInverse( worldMatrices[ parentId ] ); inv.multiply( localMatrices[ inId ] ); localMatrices[ inId ] = inv; } else { //console.log( bone ); } localMatrices[ inId ].decompose( t, r, s ); bone.pos = [ t.x, t.y, t.z ]; bone.rotq = [ r.x, r.y, r.z, r.w ]; bone.scl = [ s.x, s.y, s.z ]; } }; Bones.prototype.searchRealId = function ( internalId ) { for ( var h = 0; h < this.hierarchy.length; h ++ ) { if ( internalId == this.hierarchy[ h ].internalId ) { return h; } } // console.warn( 'FBXLoader: notfound internalId in bones: ' + internalId); return - 1; }; Bones.prototype.getByInternalId = function ( internalId ) { for ( var h = 0; h < this.hierarchy.length; h ++ ) { if ( internalId == this.hierarchy[ h ].internalId ) { return this.hierarchy[ h ]; } } return null; }; Bones.prototype.isBoneNode = function ( id ) { for ( var i = 0; i < this.hierarchy.length; ++ i ) { if ( id === this.hierarchy[ i ].internalId ) { return true; } } return false; }; Bones.prototype.getBoneIdfromInternalId = function ( node, id ) { if ( node.__cache_get_boneid_from_internalid === undefined ) { node.__cache_get_boneid_from_internalid = []; } if ( node.__cache_get_boneid_from_internalid[ id ] !== undefined ) { return node.__cache_get_boneid_from_internalid[ id ]; } for ( var i = 0; i < this.hierarchy.length; ++ i ) { if ( this.hierarchy[ i ].internalId == id ) { var res = i; node.__cache_get_boneid_from_internalid[ id ] = i; return i; } } // console.warn( 'FBXLoader: bone internalId(' + id + ') not found in bone hierarchy' ); return - 1; }; function Geometry() { this.node = null; this.name = null; this.id = null; this.vertices = []; this.indices = []; this.normals = []; this.uvs = []; this.bones = []; this.skins = null; } Geometry.prototype.parse = function ( geoNode ) { this.node = geoNode; this.name = geoNode.attrName; this.id = geoNode.id; this.vertices = this.getVertices(); if ( this.vertices === undefined ) { console.log( 'FBXLoader: Geometry.parse(): pass' + this.node.id ); return; } this.indices = this.getPolygonVertexIndices(); this.uvs = ( new UV() ).parse( this.node, this ); this.normals = ( new Normal() ).parse( this.node, this ); if ( this.getPolygonTopologyMax() > 3 ) { this.indices = this.convertPolyIndicesToTri( this.indices, this.getPolygonTopologyArray() ); } return this; }; Geometry.prototype.getVertices = function () { if ( this.node.__cache_vertices ) { return this.node.__cache_vertices; } if ( this.node.subNodes.Vertices === undefined ) { console.warn( 'this.node: ' + this.node.attrName + "(" + this.node.id + ") does not have Vertices" ); this.node.__cache_vertices = undefined; return null; } var rawTextVert = this.node.subNodes.Vertices.properties.a; var vertices = rawTextVert.split( ',' ).map( function ( element ) { return parseFloat( element ); } ); this.node.__cache_vertices = vertices; return this.node.__cache_vertices; }; Geometry.prototype.getPolygonVertexIndices = function () { if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) { return this.node.__cache_indices; } if ( this.node.subNodes === undefined ) { console.error( 'this.node.subNodes undefined' ); console.log( this.node ); return; } if ( this.node.subNodes.PolygonVertexIndex === undefined ) { console.warn( 'this.node: ' + this.node.attrName + "(" + this.node.id + ") does not have PolygonVertexIndex " ); this.node.__cache_indices = undefined; return; } var rawTextIndices = this.node.subNodes.PolygonVertexIndex.properties.a; var indices = rawTextIndices.split( ',' ); var currentTopo = 1; var topologyN = null; var topologyArr = []; // The indices that make up the polygon are in order and a negative index // means that it’s the last index of the polygon. That index needs // to be made positive and then you have to subtract 1 from it! for ( var i = 0; i < indices.length; ++ i ) { var tmpI = parseInt( indices[ i ] ); // found n if ( tmpI < 0 ) { if ( currentTopo > topologyN ) { topologyN = currentTopo; } indices[ i ] = tmpI ^ - 1; topologyArr.push( currentTopo ); currentTopo = 1; } else { indices[ i ] = tmpI; currentTopo ++; } } if ( topologyN === null ) { console.warn( "FBXLoader: topology N not found: " + this.node.attrName ); console.warn( this.node ); topologyN = 3; } this.node.__cache_poly_topology_max = topologyN; this.node.__cache_poly_topology_arr = topologyArr; this.node.__cache_indices = indices; return this.node.__cache_indices; }; Geometry.prototype.getPolygonTopologyMax = function () { if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) { return this.node.__cache_poly_topology_max; } this.getPolygonVertexIndices( this.node ); return this.node.__cache_poly_topology_max; }; Geometry.prototype.getPolygonTopologyArray = function () { if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) { return this.node.__cache_poly_topology_arr; } this.getPolygonVertexIndices( this.node ); return this.node.__cache_poly_topology_arr; }; // a - d // | | // b - c // // [( a, b, c, d ) ........... // [( a, b, c ), (a, c, d ).... Geometry.prototype.convertPolyIndicesToTri = function ( indices, strides ) { var res = []; var i = 0; var tmp = []; var currentPolyNum = 0; var currentStride = 0; while ( i < indices.length ) { currentStride = strides[ currentPolyNum ]; // CAUTIN: NG over 6gon for ( var j = 0; j <= ( currentStride - 3 ); j ++ ) { res.push( indices[ i ] ); res.push( indices[ i + ( currentStride - 2 - j ) ] ); res.push( indices[ i + ( currentStride - 1 - j ) ] ); } currentPolyNum ++; i += currentStride; } return res; }; Geometry.prototype.addBones = function ( bones ) { this.bones = bones; }; function UV() { this.uv = null; this.map = null; this.ref = null; this.node = null; this.index = null; } UV.prototype.getUV = function ( node ) { if ( this.node && this.uv && this.map && this.ref ) { return this.uv; } else { return this._parseText( node ); } }; UV.prototype.getMap = function ( node ) { if ( this.node && this.uv && this.map && this.ref ) { return this.map; } else { this._parseText( node ); return this.map; } }; UV.prototype.getRef = function ( node ) { if ( this.node && this.uv && this.map && this.ref ) { return this.ref; } else { this._parseText( node ); return this.ref; } }; UV.prototype.getIndex = function ( node ) { if ( this.node && this.uv && this.map && this.ref ) { return this.index; } else { this._parseText( node ); return this.index; } }; UV.prototype.getNode = function ( topnode ) { if ( this.node !== null ) { return this.node; } this.node = topnode.subNodes.LayerElementUV; return this.node; }; UV.prototype._parseText = function ( node ) { var uvNode = this.getNode( node ); if ( uvNode === undefined ) { // console.log( node.attrName + "(" + node.id + ")" + " has no LayerElementUV." ); return []; } var count = 0; var x = ''; for ( var n in uvNode ) { if ( n.match( /^\d+$/ ) ) { count ++; x = n; } } if ( count > 0 ) { console.warn( 'multi uv not supported' ); uvNode = uvNode[ n ]; } var uvIndex = uvNode.subNodes.UVIndex.properties.a; var uvs = uvNode.subNodes.UV.properties.a; var uvMap = uvNode.properties.MappingInformationType; var uvRef = uvNode.properties.ReferenceInformationType; this.uv = toFloat( uvs.split( ',' ) ); this.index = toInt( uvIndex.split( ',' ) ); this.map = uvMap; // TODO: normalize notation shaking... FOR BLENDER this.ref = uvRef; return this.uv; }; UV.prototype.parse = function ( node, geo ) { this.uvNode = this.getNode( node ); this.uv = this.getUV( node ); var mappingType = this.getMap( node ); var refType = this.getRef( node ); var indices = this.getIndex( node ); var strides = geo.getPolygonTopologyArray(); // it means that there is a normal for every vertex of every polygon of the model. // For example, if the models has 8 vertices that make up four quads, then there // will be 16 normals (one normal * 4 polygons * 4 vertices of the polygon). Note // that generally a game engine needs the vertices to have only one normal defined. // So, if you find a vertex has more tha one normal, you can either ignore the normals // you find after the first, or calculate the mean from all of them (normal smoothing). //if ( mappingType == "ByPolygonVertex" ){ switch ( mappingType ) { case "ByPolygonVertex": switch ( refType ) { // Direct // The this.uv are in order. case "Direct": this.uv = this.parseUV_ByPolygonVertex_Direct( this.uv, indices, strides, 2 ); break; // IndexToDirect // The order of the this.uv is given by the uvsIndex property. case "IndexToDirect": this.uv = this.parseUV_ByPolygonVertex_IndexToDirect( this.uv, indices ); break; } // convert from by polygon(vert) data into by verts data this.uv = mapByPolygonVertexToByVertex( this.uv, geo.getPolygonVertexIndices( node ), 2 ); break; case "ByPolygon": switch ( refType ) { // Direct // The this.uv are in order. case "Direct": this.uv = this.parseUV_ByPolygon_Direct(); break; // IndexToDirect // The order of the this.uv is given by the uvsIndex property. case "IndexToDirect": this.uv = this.parseUV_ByPolygon_IndexToDirect(); break; } break; } return this.uv; }; UV.prototype.parseUV_ByPolygonVertex_Direct = function ( node, indices, strides, itemSize ) { return parse_Data_ByPolygonVertex_Direct( node, indices, strides, itemSize ); }; UV.prototype.parseUV_ByPolygonVertex_IndexToDirect = function ( node, indices ) { return parse_Data_ByPolygonVertex_IndexToDirect( node, indices, 2 ); }; UV.prototype.parseUV_ByPolygon_Direct = function ( node ) { console.warn( "not implemented" ); return node; }; UV.prototype.parseUV_ByPolygon_IndexToDirect = function ( node ) { console.warn( "not implemented" ); return node; }; UV.prototype.parseUV_ByVertex_Direct = function ( node ) { console.warn( "not implemented" ); return node; }; function Normal() { this.normal = null; this.map = null; this.ref = null; this.node = null; this.index = null; } Normal.prototype.getNormal = function ( node ) { if ( this.node && this.normal && this.map && this.ref ) { return this.normal; } else { this._parseText( node ); return this.normal; } }; // mappingType: possible variant // ByPolygon // ByPolygonVertex // ByVertex (or also ByVertice, as the Blender exporter writes) // ByEdge // AllSame // var mappingType = node.properties.MappingInformationType; Normal.prototype.getMap = function ( node ) { if ( this.node && this.normal && this.map && this.ref ) { return this.map; } else { this._parseText( node ); return this.map; } }; // refType: possible variants // Direct // IndexToDirect (or Index for older versions) // var refType = node.properties.ReferenceInformationType; Normal.prototype.getRef = function ( node ) { if ( this.node && this.normal && this.map && this.ref ) { return this.ref; } else { this._parseText( node ); return this.ref; } }; Normal.prototype.getNode = function ( node ) { if ( this.node ) { return this.node; } this.node = node.subNodes.LayerElementNormal; return this.node; }; Normal.prototype._parseText = function ( node ) { var normalNode = this.getNode( node ); if ( normalNode === undefined ) { console.warn( 'node: ' + node.attrName + "(" + node.id + ") does not have LayerElementNormal" ); return; } var mappingType = normalNode.properties.MappingInformationType; var refType = normalNode.properties.ReferenceInformationType; var rawTextNormals = normalNode.subNodes.Normals.properties.a; this.normal = toFloat( rawTextNormals.split( ',' ) ); // TODO: normalize notation shaking, vertex / vertice... blender... this.map = mappingType; this.ref = refType; }; Normal.prototype.parse = function ( topnode, geo ) { var normals = this.getNormal( topnode ); var normalNode = this.getNode( topnode ); var mappingType = this.getMap( topnode ); var refType = this.getRef( topnode ); var indices = geo.getPolygonVertexIndices( topnode ); var strides = geo.getPolygonTopologyArray( topnode ); // it means that there is a normal for every vertex of every polygon of the model. // For example, if the models has 8 vertices that make up four quads, then there // will be 16 normals (one normal * 4 polygons * 4 vertices of the polygon). Note // that generally a game engine needs the vertices to have only one normal defined. // So, if you find a vertex has more tha one normal, you can either ignore the normals // you find after the first, or calculate the mean from all of them (normal smoothing). //if ( mappingType == "ByPolygonVertex" ){ switch ( mappingType ) { case "ByPolygonVertex": switch ( refType ) { // Direct // The normals are in order. case "Direct": normals = this.parseNormal_ByPolygonVertex_Direct( normals, indices, strides, 3 ); break; // IndexToDirect // The order of the normals is given by the NormalsIndex property. case "IndexToDirect": normals = this.parseNormal_ByPolygonVertex_IndexToDirect(); break; } break; case "ByPolygon": switch ( refType ) { // Direct // The normals are in order. case "Direct": normals = this.parseNormal_ByPolygon_Direct(); break; // IndexToDirect // The order of the normals is given by the NormalsIndex property. case "IndexToDirect": normals = this.parseNormal_ByPolygon_IndexToDirect(); break; } break; } return normals; }; Normal.prototype.parseNormal_ByPolygonVertex_Direct = function ( node, indices, strides, itemSize ) { return parse_Data_ByPolygonVertex_Direct( node, indices, strides, itemSize ); }; Normal.prototype.parseNormal_ByPolygonVertex_IndexToDirect = function ( node ) { console.warn( "not implemented" ); return node; }; Normal.prototype.parseNormal_ByPolygon_Direct = function ( node ) { console.warn( "not implemented" ); return node; }; Normal.prototype.parseNormal_ByPolygon_IndexToDirect = function ( node ) { console.warn( "not implemented" ); return node; }; Normal.prototype.parseNormal_ByVertex_Direct = function ( node ) { console.warn( "not implemented" ); return node; }; function AnimationCurve() { this.version = null; this.id = null; this.internalId = null; this.times = null; this.values = null; this.attrFlag = null; // tangeant this.attrData = null; // slope, weight } AnimationCurve.prototype.fromNode = function ( curveNode ) { this.id = curveNode.id; this.internalId = curveNode.id; this.times = curveNode.subNodes.KeyTime.properties.a; this.values = curveNode.subNodes.KeyValueFloat.properties.a; this.attrFlag = curveNode.subNodes.KeyAttrFlags.properties.a; this.attrData = curveNode.subNodes.KeyAttrDataFloat.properties.a; this.times = toFloat( this.times.split( ',' ) ); this.values = toFloat( this.values.split( ',' ) ); this.attrData = toFloat( this.attrData.split( ',' ) ); this.attrFlag = toInt( this.attrFlag.split( ',' ) ); this.times = this.times.map( function ( element ) { return FBXTimeToSeconds( element ); } ); return this; }; AnimationCurve.prototype.getLength = function () { return this.times[ this.times.length - 1 ]; }; function AnimationNode() { this.id = null; this.attr = null; // S, R, T this.attrX = false; this.attrY = false; this.attrZ = false; this.internalId = null; this.containerInternalId = null; // bone, null etc Id this.containerBoneId = null; // bone, null etc Id this.curveIdx = null; // AnimationCurve's indices this.curves = []; // AnimationCurve refs } AnimationNode.prototype.fromNode = function ( allNodes, node, bones ) { this.id = node.id; this.attr = node.attrName; this.internalId = node.id; if ( this.attr.match( /S|R|T/ ) ) { for ( var attrKey in node.properties ) { if ( attrKey.match( /X/ ) ) { this.attrX = true; } if ( attrKey.match( /Y/ ) ) { this.attrY = true; } if ( attrKey.match( /Z/ ) ) { this.attrZ = true; } } } else { // may be deform percent nodes return null; } this.containerIndices = allNodes.searchConnectionParent( this.id ); this.curveIdx = allNodes.searchConnectionChildren( this.id ); for ( var i = this.containerIndices.length - 1; i >= 0; -- i ) { var boneId = bones.searchRealId( this.containerIndices[ i ] ); if ( boneId >= 0 ) { this.containerBoneId = boneId; this.containerId = this.containerIndices [ i ]; } if ( boneId >= 0 ) { break; } } // this.containerBoneId = bones.searchRealId( this.containerIndices ); return this; }; AnimationNode.prototype.setCurve = function ( curve ) { this.curves.push( curve ); }; function Animation() { this.curves = {}; this.length = 0.0; this.fps = 30.0; this.frames = 0.0; } Animation.prototype.parse = function ( node, bones ) { var rawNodes = node.Objects.subNodes.AnimationCurveNode; var rawCurves = node.Objects.subNodes.AnimationCurve; // first: expand AnimationCurveNode into curve nodes var curveNodes = []; for ( var key in rawNodes ) { if ( key.match( /\d+/ ) ) { var a = ( new AnimationNode() ).fromNode( node, rawNodes[ key ], bones ); curveNodes.push( a ); } } // second: gen dict, mapped by internalId var tmp = {}; for ( var i = 0; i < curveNodes.length; ++ i ) { if ( curveNodes[ i ] === null ) { continue; } tmp[ curveNodes[ i ].id ] = curveNodes[ i ]; } // third: insert curves into the dict var ac = []; var max = 0.0; for ( key in rawCurves ) { if ( key.match( /\d+/ ) ) { var c = ( new AnimationCurve() ).fromNode( rawCurves[ key ] ); ac.push( c ); max = c.getLength() ? c.getLength() : max; var parentId = node.searchConnectionParent( c.id )[ 0 ]; var axis = node.searchConnectionType( c.id, parentId ); if ( axis.match( /X/ ) ) { axis = 'x'; } if ( axis.match( /Y/ ) ) { axis = 'y'; } if ( axis.match( /Z/ ) ) { axis = 'z'; } tmp[ parentId ].curves[ axis ] = c; } } // forth: for ( var t in tmp ) { var id = tmp[ t ].containerBoneId; if ( this.curves[ id ] === undefined ) { this.curves[ id ] = {}; } this.curves[ id ][ tmp[ t ].attr ] = tmp[ t ]; } this.length = max; this.frames = this.length * this.fps; return this; }; function Textures() { this.textures = []; this.perGeoMap = {}; } Textures.prototype.add = function ( tex ) { if ( this.textures === undefined ) { this.textures = []; } this.textures.push( tex ); for ( var i = 0; i < tex.parentIds.length; ++ i ) { if ( this.perGeoMap[ tex.parentIds[ i ] ] === undefined ) { this.perGeoMap[ tex.parentIds[ i ] ] = []; } this.perGeoMap[ tex.parentIds[ i ] ].push( this.textures[ this.textures.length - 1 ] ); } }; Textures.prototype.parse = function ( node, bones ) { var rawNodes = node.Objects.subNodes.Texture; for ( var n in rawNodes ) { var tex = ( new Texture() ).parse( rawNodes[ n ], node ); this.add( tex ); } return this; }; Textures.prototype.getById = function ( id ) { return this.perGeoMap[ id ]; }; function Texture() { this.fileName = ""; this.name = ""; this.id = null; this.parentIds = []; } Texture.prototype.parse = function ( node, nodes ) { this.id = node.id; this.name = node.attrName; this.fileName = this.parseFileName( node.properties.FileName ); this.parentIds = this.searchParents( this.id, nodes ); return this; }; // TODO: support directory Texture.prototype.parseFileName = function ( fname ) { if ( fname === undefined ) { return ""; } // ignore directory structure, flatten path var splitted = fname.split( /[\\\/]/ ); if ( splitted.length > 0 ) { return splitted[ splitted.length - 1 ]; } else { return fname; } }; Texture.prototype.searchParents = function ( id, nodes ) { var p = nodes.searchConnectionParent( id ); return p; }; /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ function loadTextureImage( texture, url ) { var loader = new THREE.ImageLoader(); loader.load( url, function ( image ) { } ); loader.load( url, function ( image ) { texture.image = image; texture.needUpdate = true; console.log( 'tex load done' ); }, // Function called when download progresses function ( xhr ) { console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ); }, // Function called when download errors function ( xhr ) { console.log( 'An error happened' ); } ); } // LayerElementUV: 0 { // Version: 101 // Name: "Texture_Projection" // MappingInformationType: "ByPolygonVertex" // ReferenceInformationType: "IndexToDirect" // UV: *1746 { // UVIndex: *7068 { // // The order of the uvs is given by the UVIndex property. function parse_Data_ByPolygonVertex_IndexToDirect( node, indices, itemSize ) { var res = []; for ( var i = 0; i < indices.length; ++ i ) { for ( var j = 0; j < itemSize; ++ j ) { res.push( node[ ( indices[ i ] * itemSize ) + j ] ); } } return res; } // what want: normal per vertex, order vertice // i have: normal per polygon // i have: indice per polygon parse_Data_ByPolygonVertex_Direct = function ( node, indices, strides, itemSize ) { // *21204 > 3573 // Geometry: 690680816, "Geometry::", "Mesh" { // Vertices: *3573 { // PolygonVertexIndex: *7068 { var tmp = []; var currentIndex = 0; // first: sort to per vertex for ( var i = 0; i < indices.length; ++ i ) { tmp[ indices[ i ] ] = []; // TODO: duped entry? blend or something? for ( var s = 0; s < itemSize; ++ s ) { tmp[ indices[ i ] ][ s ] = node[ currentIndex + s ]; } currentIndex += itemSize; } // second: expand x,y,z into serial array var res = []; for ( var jj = 0; jj < tmp.length; ++ jj ) { if ( tmp[ jj ] === undefined ) { continue; } for ( var t = 0; t < itemSize; ++ t ) { if ( tmp[ jj ][ t ] === undefined ) { continue; } res.push( tmp[ jj ][ t ] ); } } return res; }; // convert from by polygon(vert) data into by verts data function mapByPolygonVertexToByVertex( data, indices, stride ) { var tmp = {}; var res = []; var max = 0; for ( var i = 0; i < indices.length; ++ i ) { if ( indices[ i ] in tmp ) { continue; } tmp[ indices[ i ] ] = {}; for ( var j = 0; j < stride; ++ j ) { tmp[ indices[ i ] ][ j ] = data[ i * stride + j ]; } max = max < indices[ i ] ? indices[ i ] : max; } try { for ( i = 0; i <= max; i ++ ) { for ( var s = 0; s < stride; s ++ ) { res.push( tmp[ i ][ s ] ); } } } catch ( e ) { //console.log( max ); //console.log( tmp ); //console.log( i ); //console.log( e ); } return res; } // AUTODESK uses broken clock. i guess var FBXTimeToSeconds = function ( adskTime ) { return adskTime / 46186158000; }; degToRad = function ( degrees ) { return degrees * Math.PI / 180; }; radToDeg = function ( radians ) { return radians * 180 / Math.PI; }; quatFromVec = function ( x, y, z ) { var euler = new THREE.Euler( x, y, z, 'ZYX' ); var quat = new THREE.Quaternion(); quat.setFromEuler( euler ); return quat; }; // extend Array.prototype ? ....uuuh toInt = function ( arr ) { return arr.map( function ( element ) { return parseInt( element ); } ); }; toFloat = function ( arr ) { return arr.map( function ( element ) { return parseFloat( element ); } ); }; toRad = function ( arr ) { return arr.map( function ( element ) { return degToRad( element ); } ); }; toMat44 = function ( arr ) { var mat = new THREE.Matrix4(); mat.set( arr[ 0 ], arr[ 4 ], arr[ 8 ], arr[ 12 ], arr[ 1 ], arr[ 5 ], arr[ 9 ], arr[ 13 ], arr[ 2 ], arr[ 6 ], arr[ 10 ], arr[ 14 ], arr[ 3 ], arr[ 7 ], arr[ 11 ], arr[ 15 ] ); /* mat.set( arr[ 0], arr[ 1], arr[ 2], arr[ 3], arr[ 4], arr[ 5], arr[ 6], arr[ 7], arr[ 8], arr[ 9], arr[10], arr[11], arr[12], arr[13], arr[14], arr[15] ); // */ return mat; }; } )();
// IE8 doesn't like using var dnnModule = dnnModule || {} if (typeof dnnModule === "undefined" || dnnModule === null) { dnnModule = {}; }; dnnModule.DigitalAssetsSearchBox = function ($, $scope, servicesFramework) { var onSearchFunction = null; function search() { var newPattern = $("#dnnModuleDigitalAssetsSearchBox>input.searchInput", $scope).val(); newPattern = $.trim(newPattern); if (onSearchFunction) { onSearchFunction(newPattern); } } function clearSearch() { $("#dnnModuleDigitalAssetsSearchBox>input.searchInput", $scope).val(''); } function doSearch(currentFolderId, pattern, startIndex, numItems, sortExpression, before, done, fail, always) { var contentServiceUrl = servicesFramework.getServiceRoot('DigitalAssets') + 'ContentService/'; before(); $.ajax({ url: contentServiceUrl + "SearchFolderContent", data: { "folderId": currentFolderId, "pattern": pattern, "startIndex": startIndex, "numItems": numItems, "sortExpression": sortExpression }, type: "POST", beforeSend: servicesFramework.setModuleHeaders }).done(done).fail(fail).always(always); }; function init () { $("#dnnModuleDigitalAssetsSearchBox>input.searchInput", $scope).keypress(function(e) { if (e.which == 13) { e.preventDefault(); search(); return false; } return true; }); $("#dnnModuleDigitalAssetsSearchBox>a.searchButton", $scope).click(function(e) { e.preventDefault(); search(); return false; }); } function onSearch(onSearchFunc) { onSearchFunction = onSearchFunc; } function highlightItemName(pattern, itemName) { if (!pattern || pattern == "" || pattern.indexOf("?") != -1) { return itemName; } if (pattern.lastIndexOf("*") == pattern.length - 1) { // example* pattern = pattern.substring(0, pattern.length - 1); if (pattern.lastIndexOf("*") == 0) { // *example* --> Highlight al occurrences pattern = pattern.substring(1, pattern.length); if (pattern.indexOf("*") == -1) { var matches = itemName.match(new RegExp(pattern, "i")); if (matches) { for (var i = 0; i < matches.length; i++) { itemName = itemName.replace(matches[i], "<font class='dnnModuleDigitalAssetsHighlight'>" + matches[i] + "</font>"); } } } return itemName; } } if (pattern.indexOf("*") == -1) { // highlight the beginning itemName = "<font class='dnnModuleDigitalAssetsHighlight'>" + itemName.substring(0, pattern.length) + "</font>" + itemName.substring(pattern.length); } return itemName; } return { init: init, doSearch: doSearch, onSearch: onSearch, clearSearch: clearSearch, highlightItemName: highlightItemName, }; }
/*! * CanJS - 2.0.3 * http://canjs.us/ * Copyright (c) 2013 Bitovi * Tue, 26 Nov 2013 18:21:22 GMT * Licensed MIT * Includes: CanJS default build * Download from: http://canjs.us/ */ define(["can/util/library", "can/util/string", "can/util/object"], function (can) { // Get the URL from old Steal root, new Steal config or can.fixture.rootUrl var getUrl = function(url) { if(typeof steal !== 'undefined') { if(can.isFunction(steal.config)) { return steal.config().root.mapJoin(url).toString(); } return steal.root.join(url).toString(); } return (can.fixture.rootUrl || '') + url; } var updateSettings = function (settings, originalOptions) { if (!can.fixture.on) { return; } //simple wrapper for logging var _logger = function(type, arr){ if(console.log.apply){ Function.prototype.call.apply(console[type], [console].concat(arr)); // console[type].apply(console, arr) } else { console[type](arr) } }, log = function () { if(typeof steal !== 'undefined' && steal.dev) { steal.dev.log('fixture INFO: ' + Array.prototype.slice.call(arguments).join(' ')); } } // We always need the type which can also be called method, default to GET settings.type = settings.type || settings.method || 'GET'; // add the fixture option if programmed in var data = overwrite(settings); // if we don't have a fixture, do nothing if (!settings.fixture) { if (window.location.protocol === "file:") { log("ajax request to " + settings.url + ", no fixture found"); } return; } //if referencing something else, update the fixture option if (typeof settings.fixture === "string" && can.fixture[settings.fixture]) { settings.fixture = can.fixture[settings.fixture]; } // if a string, we just point to the right url if (typeof settings.fixture == "string") { var url = settings.fixture; if (/^\/\//.test(url)) { // this lets us use rootUrl w/o having steal... url = getUrl(settings.fixture.substr(2)); } if(data) { // Template static fixture URLs url = can.sub(url, data); } delete settings.fixture; settings.url = url; settings.data = null; settings.type = "GET"; if (!settings.error) { settings.error = function (xhr, error, message) { throw "fixtures.js Error " + error + " " + message; }; } } else { //it's a function ... add the fixture datatype so our fixture transport handles it // TODO: make everything go here for timing and other fun stuff // add to settings data from fixture ... settings.dataTypes && settings.dataTypes.splice(0, 0, "fixture"); if (data && originalOptions) { can.extend(originalOptions.data, data) } } }, // A helper function that takes what's called with response // and moves some common args around to make it easier to call extractResponse = function(status, statusText, responses, headers) { // if we get response(RESPONSES, HEADERS) if(typeof status != "number"){ headers = statusText; responses = status; statusText = "success" status = 200; } // if we get response(200, RESPONSES, HEADERS) if(typeof statusText != "string"){ headers = responses; responses = statusText; statusText = "success"; } if ( status >= 400 && status <= 599 ) { this.dataType = "text" } return [status, statusText, extractResponses(this, responses), headers]; }, // If we get data instead of responses, // make sure we provide a response type that matches the first datatype (typically json) extractResponses = function(settings, responses){ var next = settings.dataTypes ? settings.dataTypes[0] : (settings.dataType || 'json'); if (!responses || !responses[next]) { var tmp = {} tmp[next] = responses; responses = tmp; } return responses; }; //used to check urls // check if jQuery if (can.ajaxPrefilter && can.ajaxTransport) { // the pre-filter needs to re-route the url can.ajaxPrefilter(updateSettings); can.ajaxTransport("fixture", function (s, original) { // remove the fixture from the datatype s.dataTypes.shift(); //we'll return the result of the next data type var timeout, stopped = false; return { send: function (headers, callback) { // we'll immediately wait the delay time for all fixtures timeout = setTimeout(function () { // if the user wants to call success on their own, we allow it ... var success = function() { if(stopped === false) { callback.apply(null, extractResponse.apply(s, arguments) ); } }, // get the result form the fixture result = s.fixture(original, success, headers, s); if(result !== undefined) { // make sure the result has the right dataType callback(200, "success", extractResponses(s, result), {}); } }, can.fixture.delay); }, abort: function () { stopped = true; clearTimeout(timeout) } }; }); } else { var AJAX = can.ajax; can.ajax = function (settings) { updateSettings(settings, settings); if (settings.fixture) { var timeout, d = new can.Deferred(), stopped = false; //TODO this should work with response d.getResponseHeader = function () { } // call success and fail d.then(settings.success, settings.fail); // abort should stop the timeout and calling success d.abort = function () { clearTimeout(timeout); stopped = true; d.reject(d) } // set a timeout that simulates making a request .... timeout = setTimeout(function () { // if the user wants to call success on their own, we allow it ... var success = function() { var response = extractResponse.apply(settings, arguments), status = response[0]; if ( (status >= 200 && status < 300 || status === 304) && stopped === false) { d.resolve(response[2][settings.dataType]) } else { // TODO probably resolve better d.reject(d, 'error', response[1]); } }, // get the result form the fixture result = settings.fixture(settings, success, settings.headers, settings); if(result !== undefined) { d.resolve(result) } }, can.fixture.delay); return d; } else { return AJAX(settings); } } } var typeTest = /^(script|json|text|jsonp)$/, // a list of 'overwrite' settings object overwrites = [], // returns the index of an overwrite function find = function (settings, exact) { for (var i = 0; i < overwrites.length; i++) { if ($fixture._similar(settings, overwrites[i], exact)) { return i; } } return -1; }, // overwrites the settings fixture if an overwrite matches overwrite = function (settings) { var index = find(settings); if (index > -1) { settings.fixture = overwrites[index].fixture; return $fixture._getData(overwrites[index].url, settings.url) } }, // Makes an attempt to guess where the id is at in the url and returns it. getId = function (settings) { var id = settings.data.id; if (id === undefined && typeof settings.data === "number") { id = settings.data; } /* Check for id in params(if query string) If this is just a string representation of an id, parse if(id === undefined && typeof settings.data === "string") { id = settings.data; } //*/ if (id === undefined) { settings.url.replace(/\/(\d+)(\/|$|\.)/g, function (all, num) { id = num; }); } if (id === undefined) { id = settings.url.replace(/\/(\w+)(\/|$|\.)/g, function (all, num) { if (num != 'update') { id = num; } }) } if (id === undefined) { // if still not set, guess a random number id = Math.round(Math.random() * 1000) } return id; }; var $fixture = can.fixture = function (settings, fixture) { // if we provide a fixture ... if (fixture !== undefined) { if (typeof settings == 'string') { // handle url strings var matches = settings.match(/(GET|POST|PUT|DELETE) (.+)/i); if (!matches) { settings = { url : settings }; } else { settings = { url : matches[2], type : matches[1] }; } } //handle removing. An exact match if fixture was provided, otherwise, anything similar var index = find(settings, !!fixture); if (index > -1) { overwrites.splice(index, 1) } if (fixture == null) { return } settings.fixture = fixture; overwrites.push(settings) } else { can.each(settings, function(fixture, url){ $fixture(url, fixture); }) } }; var replacer = can.replacer; can.extend(can.fixture, { // given ajax settings, find an overwrite _similar : function (settings, overwrite, exact) { if (exact) { return can.Object.same(settings, overwrite, {fixture : null}) } else { return can.Object.subset(settings, overwrite, can.fixture._compare) } }, _compare : { url : function (a, b) { return !!$fixture._getData(b, a) }, fixture : null, type : "i" }, // gets data from a url like "/todo/{id}" given "todo/5" _getData : function (fixtureUrl, url) { var order = [], fixtureUrlAdjusted = fixtureUrl.replace('.', '\\.').replace('?', '\\?'), res = new RegExp(fixtureUrlAdjusted.replace(replacer, function (whole, part) { order.push(part) return "([^\/]+)" }) + "$").exec(url), data = {}; if (!res) { return null; } res.shift(); can.each(order, function (name) { data[name] = res.shift() }) return data; }, /** * @description Make a store of objects to use when making requests against fixtures. * @function can.fixture.store store * @parent can.fixture * * @signature `can.fixture.store(count, make[, filter])` * * @param {Number} count The number of items to create. * * @param {Function} make A function that will return the JavaScript object. The * make function is called back with the id and the current array of items. * * @param {Function} [filter] A function used to further filter results. Used for to simulate * server params like searchText or startDate. * The function should return true if the item passes the filter, * false otherwise. For example: * * * function(item, settings){ * if(settings.data.searchText){ * var regex = new RegExp("^"+settings.data.searchText) * return regex.test(item.name); * } * } * * @return {can.fixture.Store} A generator object providing fixture functions for *findAll*, *findOne*, *create*, * *update* and *destroy*. * * @body * `can.fixture.store(count, generator(index,items))` is used * to create a store of items that can simulate a full CRUD service. Furthermore, * the store can do filtering, grouping, sorting, and paging. * * ## Basic Example * * The following creates a store for 100 todos: * * var todoStore = can.fixture.store(100, function(i){ * return { * id: i, * name: "todo number "+i, * description: "a description of some todo", * ownerId: can.fixture.rand(10) * } * }) * * `todoStore`'s methods: * * - [can.fixture.types.Store.findAll findAll], * - [can.fixture.types.Store.findOne findOne], * - [can.fixture.types.Store.create create], * - [can.fixture.types.Store.update update], and * - [can.fixture.types.Store.destroy destroy] * * Can be used to simulate a REST service like: * * can.fixture({ * 'GET /todos': todoStore.findAll, * 'GET /todos/{id}': todoStore.findOne, * 'POST /todos': todoStore.create, * 'PUT /todos/{id}': todoStore.update, * 'DELETE /todos/{id}': todoStore.destroy * }); * * These fixtures, combined with a [can.Model] that connects to these services like: * * var Todo = can.Model.extend({ * findAll : 'GET /todos', * findOne : 'GET /todos/{id}', * create : 'POST /todos', * update : 'PUT /todos/{id}', * destroy : 'DELETE /todos/{id}' * }, {}); * * ... allows you to simulate requests for all of owner 5's todos like: * * Todo.findAll({ownerId: 5}, function(todos){ * * }) * * */ store: function (types, count, make, filter) { var items = [], // TODO: change this to a hash currentId = 0, findOne = function (id) { for (var i = 0; i < items.length; i++) { if (id == items[i].id) { return items[i]; } } }, methods = {}; if (typeof types === "string") { types = [types + "s", types ] } else if (!can.isArray(types)) { filter = make; make = count; count = types; } // make all items can.extend(methods, { /** * @description Simulate a findAll to a fixture. * @function can.fixture.types.Store.findAll * @parent can.fixture.types.Store * @signature `store.findAll(request)` * * `store.findAll(request)` simulates a request to * get a list items from the server. It supports the * following params: * * - order - `order=name ASC` * - group - `group=name` * - limit - `limit=20` * - offset - `offset=60` * - id filtering - `ownerId=5` * * * @param {{}} request The ajax request object. The available parameters are: * @option {String} order The order of the results. * `order: 'name ASC'` * @option {String} group How to group the results. * `group: 'name'` * @option {String} limit A limit on the number to retrieve. * `limit: 20` * @option {String} offset The offset of the results. * `offset: 60` * @option {String} id Filtering by ID. * `id: 5` * * @return {Object} a response object like: * * { * count: 1000, * limit: 20, * offset: 60, * data: [item1, item2, ...] * } * * where: * * - count - the number of items that match any filtering * before limit and offset is taken into account * - offset - the offset passed * - limit - the limit passed * - data - an array of JS objects with each item's properties * */ findAll: function (request) { request = request || {} //copy array of items var retArr = items.slice(0); request.data = request.data || {}; //sort using order //order looks like ["age ASC","gender DESC"] can.each((request.data.order || []).slice(0).reverse(), function (name) { var split = name.split(" "); retArr = retArr.sort(function (a, b) { if (split[1].toUpperCase() !== "ASC") { if (a[split[0]] < b[split[0]]) { return 1; } else if (a[split[0]] == b[split[0]]) { return 0 } else { return -1; } } else { if (a[split[0]] < b[split[0]]) { return -1; } else if (a[split[0]] == b[split[0]]) { return 0 } else { return 1; } } }); }); //group is just like a sort can.each((request.data.group || []).slice(0).reverse(), function (name) { var split = name.split(" "); retArr = retArr.sort(function (a, b) { return a[split[0]] > b[split[0]]; }); }); var offset = parseInt(request.data.offset, 10) || 0, limit = parseInt(request.data.limit, 10) || (items.length - offset), i = 0; //filter results if someone added an attr like parentId for (var param in request.data) { i = 0; if (request.data[param] !== undefined && // don't do this if the value of the param is null (ignore it) (param.indexOf("Id") != -1 || param.indexOf("_id") != -1)) { while (i < retArr.length) { if (request.data[param] != retArr[i][param]) { retArr.splice(i, 1); } else { i++; } } } } if (filter) { i = 0; while (i < retArr.length) { if (!filter(retArr[i], request)) { retArr.splice(i, 1); } else { i++; } } } //return data spliced with limit and offset return { "count" : retArr.length, "limit" : request.data.limit, "offset" : request.data.offset, "data" : retArr.slice(offset, offset + limit) }; }, /** * @description Simulate a findOne request on a fixture. * @function can.fixture.types.Store.findOne * @parent can.fixture.types.Store * @signature `store.findOne(request, callback)` * @param {Object} request Parameters for the request. * @param {Function} callback A function to call with the retrieved item. * * @body * `store.findOne(request, response(item))` simulates a request to * get a single item from the server by id. * * todosStore.findOne({ * url: "/todos/5" * }, function(todo){ * * }); * */ findOne : function (request, response) { var item = findOne(getId(request)); response(item ? item : undefined); }, /** * @description Simulate an update on a fixture. * @function can.fixture.types.Store.update * @parent can.fixture.types.Store * @signature `store.update(request, callback)` * @param {Object} request Parameters for the request. * @param {Function} callback A function to call with the updated item and headers. * * @body * `store.update(request, response(props,headers))` simulates * a request to update an items properties on a server. * * todosStore.update({ * url: "/todos/5" * }, function(props, headers){ * props.id //-> 5 * headers.location // "todos/5" * }); */ update: function (request,response) { var id = getId(request); // TODO: make it work with non-linear ids .. can.extend(findOne(id), request.data); response({ id : getId(request) }, { location : request.url || "/" + getId(request) }); }, /** * @description Simulate destroying a Model on a fixture. * @function can.fixture.types.Store.destroy * @parent can.fixture.types.Store * @signature `store.destroy(request, callback)` * @param {Object} request Parameters for the request. * @param {Function} callback A function to call after destruction. * * @body * `store.destroy(request, response())` simulates * a request to destroy an item from the server. * * @codestart * todosStore.destroy({ * url: "/todos/5" * }, function(){}); * @codeend */ destroy: function (request) { var id = getId(request); for (var i = 0; i < items.length; i++) { if (items[i].id == id) { items.splice(i, 1); break; } } // TODO: make it work with non-linear ids .. can.extend(findOne(id) || {}, request.data); return {}; }, /** * @description Simulate creating a Model with a fixture. * @function can.fixture.types.Store.create * @parent can.fixture.types.Store * @signature `store.create(request, callback)` * @param {Object} request Parameters for the request. * @param {Function} callback A function to call with the created item. * * @body * `store.destroy(request, callback)` simulates * a request to destroy an item from the server. * * @codestart * todosStore.create({ * url: "/todos" * }, function(){}); * @codeend */ create: function (settings, response) { var item = make(items.length, items); can.extend(item, settings.data); if (!item.id) { item.id = currentId++; } items.push(item); response({ id : item.id }, { location : settings.url + "/" + item.id }) } }); var reset = function(){ items = []; for (var i = 0; i < (count); i++) { //call back provided make var item = make(i, items); if (!item.id) { item.id = i; } currentId = Math.max(item.id+1, currentId+1) || items.length; items.push(item); } if(can.isArray(types)) { can.fixture["~" + types[0]] = items; can.fixture["-" + types[0]] = methods.findAll; can.fixture["-" + types[1]] = methods.findOne; can.fixture["-" + types[1]+"Update"] = methods.update; can.fixture["-" + types[1]+"Destroy"] = methods.destroy; can.fixture["-" + types[1]+"Create"] = methods.create; } } reset() // if we have types given add them to can.fixture return can.extend({ getId: getId, /** * @description Get an item from the store by ID. * @function can.fixture.types.Store.find * @parent can.fixture.types.Store * @signature `store.find(settings)` * @param {Object} settings An object containing an `id` key * corresponding to the item to find. * * @body * `store.find(settings)` * `store.destroy(request, callback)` simulates a request to * get a single item from the server. * * @codestart * todosStore.find({ * url: "/todos/5" * }, function(){}); * @codeend */ find: function(settings){ return findOne( getId(settings) ); }, /** * @description Reset the fixture store. * @function can.fixture.types.Store.reset * @parent can.fixture.types.Store * @signature `store.reset()` * * @body * `store.reset()` resets the store to contain its * original data. This is useful for making tests that * operate independently. * * ## Basic Example * * After creating a `taskStore` and hooking it up to a * `task` model in the "Basic Example" in [can.fixture.store store's docs], * a test might create several tasks like: * * new Task({name: "Take out trash", ownerId: 5}).save(); * * But, another test might need to operate on the original set of * tasks created by `can.fixture.store`. Reset the task store with: * * taskStore.reset() * */ reset: reset }, methods); }, /** * @description Create a random number or selection. * @function can.fixture.rand rand * @parent can.fixture * @signature `can.fixture.rand([min,] max)` * @param {Number} [min=0] The lower bound on integers to select. * @param {Number} max The upper bound on integers to select. * @return {Number} A random integer in the range [__min__, __max__). * * @signature `can.fixture.rand(choices, min[ ,max])` * @param {Array} choices An array of things to choose from. * @param {Number} min The minimum number of times to choose from __choices__. * @param {Number} [max=min] The maximum number of times to choose from __choices__. * @return {Array} An array of between __min__ and __max__ random choices from __choices__. * * @body * `can.fixture.rand` creates random integers or random arrays of * other arrays. * * ## Examples * * var rand = can.fixture.rand; * * // get a random integer between 0 and 10 (inclusive) * rand(11); * * // get a random number between -5 and 5 (inclusive) * rand(-5, 6); * * // pick a random item from an array * rand(["j","m","v","c"],1)[0] * * // pick a random number of items from an array * rand(["j","m","v","c"]) * * // pick 2 items from an array * rand(["j","m","v","c"],2) * * // pick between 2 and 3 items at random * rand(["j","m","v","c"],2,3) */ rand : function (arr, min, max) { if (typeof arr == 'number') { if (typeof min == 'number') { return arr + Math.floor(Math.random() * (min - arr)); } else { return Math.floor(Math.random() * arr); } } var rand = arguments.callee; // get a random set if (min === undefined) { return rand(arr, rand(arr.length + 1)) } // get a random selection of arr var res = []; arr = arr.slice(0); // set max if (!max) { max = min; } //random max max = min + Math.round(rand(max - min)) for (var i = 0; i < max; i++) { res.push(arr.splice(rand(arr.length), 1)[0]) } return res; }, /** * @hide * * Use can.fixture.xhr to create an object that looks like an xhr object. * * ## Example * * The following example shows how the -restCreate fixture uses xhr to return * a simulated xhr object: * @codestart * "-restCreate" : function( settings, cbType ) { * switch(cbType){ * case "success": * return [ * {id: parseInt(Math.random()*1000)}, * "success", * can.fixture.xhr()]; * case "complete": * return [ * can.fixture.xhr({ * getResponseHeader: function() { * return settings.url+"/"+parseInt(Math.random()*1000); * } * }), * "success"]; * } * } * @codeend * @param {Object} [xhr] properties that you want to overwrite * @return {Object} an object that looks like a successful XHR object. */ xhr : function (xhr) { return can.extend({}, { abort : can.noop, getAllResponseHeaders : function () { return ""; }, getResponseHeader : function () { return ""; }, open : can.noop, overrideMimeType : can.noop, readyState : 4, responseText : "", responseXML : null, send : can.noop, setRequestHeader : can.noop, status : 200, statusText : "OK" }, xhr); }, /** * @property {Boolean} can.fixture.on on * @parent can.fixture * * `can.fixture.on` lets you programatically turn off fixtures. This is mostly used for testing. * * can.fixture.on = false * Task.findAll({}, function(){ * can.fixture.on = true; * }) */ on : true }); /** * @property {Number} can.fixture.delay delay * @parent can.fixture * * `can.fixture.delay` indicates the delay in milliseconds between an ajax request is made and * the success and complete handlers are called. This only sets * functional synchronous fixtures that return a result. By default, the delay is 200ms. * * @codestart * steal('can/util/fixtures').then(function(){ * can.fixture.delay = 1000; * }) * @codeend */ can.fixture.delay = 200; /** * @property {String} can.fixture.rootUrl rootUrl * @parent can.fixture * * `can.fixture.rootUrl` contains the root URL for fixtures to use. * If you are using StealJS it will use the Steal root * URL by default. */ can.fixture.rootUrl = getUrl(''); can.fixture["-handleFunction"] = function (settings) { if (typeof settings.fixture === "string" && can.fixture[settings.fixture]) { settings.fixture = can.fixture[settings.fixture]; } if (typeof settings.fixture == "function") { setTimeout(function () { if (settings.success) { settings.success.apply(null, settings.fixture(settings, "success")); } if (settings.complete) { settings.complete.apply(null, settings.fixture(settings, "complete")); } }, can.fixture.delay); return true; } return false; }; //Expose this for fixture debugging can.fixture.overwrites = overwrites; can.fixture.make = can.fixture.store; return can.fixture; });
/*! * Module dependencies. */ var readPref = require('./drivers').ReadPreference; var EventEmitter = require('events').EventEmitter; var VirtualType = require('./virtualtype'); var utils = require('./utils'); var MongooseTypes; var Kareem = require('kareem'); var async = require('async'); var PromiseProvider = require('./promise_provider'); var IS_QUERY_HOOK = { count: true, find: true, findOne: true, findOneAndUpdate: true, findOneAndRemove: true, update: true }; /** * Schema constructor. * * ####Example: * * var child = new Schema({ name: String }); * var schema = new Schema({ name: String, age: Number, children: [child] }); * var Tree = mongoose.model('Tree', schema); * * // setting schema options * new Schema({ name: String }, { _id: false, autoIndex: false }) * * ####Options: * * - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option) * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true * - [capped](/docs/guide.html#capped): bool - defaults to false * - [collection](/docs/guide.html#collection): string - no default * - [emitIndexErrors](/docs/guide.html#emitIndexErrors): bool - defaults to false. * - [id](/docs/guide.html#id): bool - defaults to true * - [_id](/docs/guide.html#_id): bool - defaults to true * - `minimize`: bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true * - [read](/docs/guide.html#read): string * - [safe](/docs/guide.html#safe): bool - defaults to true. * - [shardKey](/docs/guide.html#shardKey): bool - defaults to `null` * - [strict](/docs/guide.html#strict): bool - defaults to true * - [toJSON](/docs/guide.html#toJSON) - object - no default * - [toObject](/docs/guide.html#toObject) - object - no default * - [typeKey](/docs/guide.html#typeKey) - string - defaults to 'type' * - [validateBeforeSave](/docs/guide.html#validateBeforeSave) - bool - defaults to `true` * - [versionKey](/docs/guide.html#versionKey): bool - defaults to "__v" * * ####Note: * * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._ * * @param {Object} definition * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter * @event `init`: Emitted after the schema is compiled into a `Model`. * @api public */ function Schema(obj, options) { if (!(this instanceof Schema)) return new Schema(obj, options); this.paths = {}; this.subpaths = {}; this.virtuals = {}; this.nested = {}; this.inherits = {}; this.callQueue = []; this._indexes = []; this.methods = {}; this.statics = {}; this.tree = {}; this._requiredpaths = undefined; this.discriminatorMapping = undefined; this._indexedpaths = undefined; this.s = { hooks: new Kareem(), queryHooks: IS_QUERY_HOOK }; this.options = this.defaultOptions(options); // build paths if (obj) { this.add(obj); } // check if _id's value is a subdocument (gh-2276) var _idSubDoc = obj && obj._id && utils.isObject(obj._id); // ensure the documents get an auto _id unless disabled var auto_id = !this.paths['_id'] && (!this.options.noId && this.options._id) && !_idSubDoc; if (auto_id) { obj = { _id: { auto: true } }; obj._id[this.options.typeKey] = Schema.ObjectId; this.add(obj); } // ensure the documents receive an id getter unless disabled var autoid = !this.paths['id'] && (!this.options.noVirtualId && this.options.id); if (autoid) { this.virtual('id').get(idGetter); } for (var i = 0; i < this._defaultMiddleware.length; ++i) { var m = this._defaultMiddleware[i]; this[m.kind](m.hook, !!m.isAsync, m.fn); } // adds updatedAt and createdAt timestamps to documents if enabled var timestamps = this.options.timestamps; if (timestamps) { var createdAt = timestamps.createdAt || 'createdAt', updatedAt = timestamps.updatedAt || 'updatedAt', schemaAdditions = {}; schemaAdditions[updatedAt] = Date; if (!this.paths[createdAt]) { schemaAdditions[createdAt] = Date; } this.add(schemaAdditions); this.pre('save', function(next) { var defaultTimestamp = new Date(); if (!this[createdAt]) { this[createdAt] = auto_id ? this._id.getTimestamp() : defaultTimestamp; } this[updatedAt] = this.isNew ? this[createdAt] : defaultTimestamp; next(); }); var genUpdates = function() { var now = new Date(); var updates = {$set: {}, $setOnInsert: {}}; updates.$set[updatedAt] = now; updates.$setOnInsert[createdAt] = now; return updates; }; this.pre('findOneAndUpdate', function(next) { this.findOneAndUpdate({}, genUpdates()); next(); }); this.pre('update', function(next) { this.update({}, genUpdates()); next(); }); } } /*! * Returns this documents _id cast to a string. */ function idGetter() { if (this.$__._id) { return this.$__._id; } return this.$__._id = null == this._id ? null : String(this._id); } /*! * Inherit from EventEmitter. */ Schema.prototype = Object.create( EventEmitter.prototype ); Schema.prototype.constructor = Schema; /** * Default middleware attached to a schema. Cannot be changed. * * This field is used to make sure discriminators don't get multiple copies of * built-in middleware. Declared as a constant because changing this at runtime * may lead to instability with Model.prototype.discriminator(). * * @api private * @property _defaultMiddleware */ Object.defineProperty(Schema.prototype, '_defaultMiddleware', { configurable: false, enumerable: false, writable: false, value: [{ kind: 'pre', hook: 'save', fn: function(next, options) { // Nested docs have their own presave if (this.ownerDocument) { return next(); } var hasValidateBeforeSaveOption = options && (typeof options === 'object') && ('validateBeforeSave' in options); var shouldValidate; if (hasValidateBeforeSaveOption) { shouldValidate = !!options.validateBeforeSave; } else { shouldValidate = this.schema.options.validateBeforeSave; } // Validate if (shouldValidate) { // HACK: use $__original_validate to avoid promises so bluebird doesn't // complain if (this.$__original_validate) { this.$__original_validate({ __noPromise: true }, function(error) { next(error); }); } else { this.validate({ __noPromise: true }, function(error) { next(error); }); } } else { next(); } } }, { kind: 'pre', hook: 'save', isAsync: true, fn: function(next, done) { var Promise = PromiseProvider.get(), subdocs = this.$__getAllSubdocs(); if (!subdocs.length || this.$__preSavingFromParent) { done(); next(); return; } new Promise.ES6(function(resolve, reject) { async.each(subdocs, function(subdoc, cb) { subdoc.$__preSavingFromParent = true; subdoc.save(function(err) { cb(err); }); }, function(error) { for (var i = 0; i < subdocs.length; ++i) { delete subdocs[i].$__preSavingFromParent; } if (error) { reject(error); return; } resolve(); }); }).then(function() { next(); done(); }, done); } }] }); /** * Schema as flat paths * * ####Example: * { * '_id' : SchemaType, * , 'nested.key' : SchemaType, * } * * @api private * @property paths */ Schema.prototype.paths; /** * Schema as a tree * * ####Example: * { * '_id' : ObjectId * , 'nested' : { * 'key' : String * } * } * * @api private * @property tree */ Schema.prototype.tree; /** * Returns default options for this schema, merged with `options`. * * @param {Object} options * @return {Object} * @api private */ Schema.prototype.defaultOptions = function(options) { if (options && false === options.safe) { options.safe = { w: 0 }; } if (options && options.safe && 0 === options.safe.w) { // if you turn off safe writes, then versioning goes off as well options.versionKey = false; } options = utils.options({ strict: true, bufferCommands: true, capped: false, // { size, max, autoIndexId } versionKey: '__v', discriminatorKey: '__t', minimize: true, autoIndex: null, shardKey: null, read: null, validateBeforeSave: true, // the following are only applied at construction time noId: false, // deprecated, use { _id: false } _id: true, noVirtualId: false, // deprecated, use { id: false } id: true, typeKey: 'type' }, options); if (options.read) { options.read = readPref(options.read); } return options; }; /** * Adds key path / schema type pairs to this schema. * * ####Example: * * var ToySchema = new Schema; * ToySchema.add({ name: 'string', color: 'string', price: 'number' }); * * @param {Object} obj * @param {String} prefix * @api public */ Schema.prototype.add = function add(obj, prefix) { prefix = prefix || ''; var keys = Object.keys(obj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (null == obj[key]) { throw new TypeError('Invalid value for schema path `' + prefix + key + '`'); } if (Array.isArray(obj[key]) && obj[key].length === 1 && null == obj[key][0]) { throw new TypeError('Invalid value for schema Array path `' + prefix + key + '`'); } if (utils.isObject(obj[key]) && (!obj[key].constructor || 'Object' == utils.getFunctionName(obj[key].constructor)) && (!obj[key][this.options.typeKey] || (this.options.typeKey === 'type' && obj[key].type.type))) { if (Object.keys(obj[key]).length) { // nested object { last: { name: String }} this.nested[prefix + key] = true; this.add(obj[key], prefix + key + '.'); } else { this.path(prefix + key, obj[key]); // mixed type } } else { this.path(prefix + key, obj[key]); } } }; /** * Reserved document keys. * * Keys in this object are names that are rejected in schema declarations b/c they conflict with mongoose functionality. Using these key name will throw an error. * * on, emit, _events, db, get, set, init, isNew, errors, schema, options, modelName, collection, _pres, _posts, toObject * * _NOTE:_ Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on. * * var schema = new Schema(..); * schema.methods.init = function () {} // potentially breaking */ Schema.reserved = Object.create(null); var reserved = Schema.reserved; // EventEmitter reserved.emit = reserved.on = reserved.once = // document properties and functions reserved.collection = reserved.db = reserved.errors = reserved.init = reserved.isModified = reserved.isNew = reserved.get = reserved.modelName = reserved.save = reserved.schema = reserved.set = reserved.toObject = reserved.validate = // hooks.js reserved._pres = reserved._posts = 1; /** * Document keys to print warnings for */ var warnings = {}; warnings.increment = '`increment` should not be used as a schema path name ' + 'unless you have disabled versioning.'; /** * Gets/sets schema paths. * * Sets a path (if arity 2) * Gets a path (if arity 1) * * ####Example * * schema.path('name') // returns a SchemaType * schema.path('name', Number) // changes the schemaType of `name` to Number * * @param {String} path * @param {Object} constructor * @api public */ Schema.prototype.path = function(path, obj) { if (obj == undefined) { if (this.paths[path]) return this.paths[path]; if (this.subpaths[path]) return this.subpaths[path]; // subpaths? return /\.\d+\.?.*$/.test(path) ? getPositionalPath(this, path) : undefined; } // some path names conflict with document methods if (reserved[path]) { throw new Error("`" + path + "` may not be used as a schema pathname"); } if (warnings[path]) { console.log('WARN: ' + warnings[path]); } // update the tree var subpaths = path.split(/\./), last = subpaths.pop(), branch = this.tree; subpaths.forEach(function(sub, i) { if (!branch[sub]) branch[sub] = {}; if ('object' != typeof branch[sub]) { var msg = 'Cannot set nested path `' + path + '`. ' + 'Parent path `' + subpaths.slice(0, i).concat([sub]).join('.') + '` already set to type ' + branch[sub].name + '.'; throw new Error(msg); } branch = branch[sub]; }); branch[last] = utils.clone(obj); this.paths[path] = Schema.interpretAsType(path, obj, this.options); return this; }; /** * Converts type arguments into Mongoose Types. * * @param {String} path * @param {Object} obj constructor * @api private */ Schema.interpretAsType = function(path, obj, options) { if (obj.constructor) { var constructorName = utils.getFunctionName(obj.constructor); if (constructorName != 'Object') { var oldObj = obj; obj = {}; obj[options.typeKey] = oldObj; } } // Get the type making sure to allow keys named "type" // and default to mixed if not specified. // { type: { type: String, default: 'freshcut' } } var type = obj[options.typeKey] && (options.typeKey !== 'type' || !obj.type.type) ? obj[options.typeKey] : {}; if ('Object' == utils.getFunctionName(type.constructor) || 'mixed' == type) { return new MongooseTypes.Mixed(path, obj); } if (Array.isArray(type) || Array == type || 'array' == type) { // if it was specified through { type } look for `cast` var cast = (Array == type || 'array' == type) ? obj.cast : type[0]; if (cast instanceof Schema) { return new MongooseTypes.DocumentArray(path, cast, obj); } if ('string' == typeof cast) { cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)]; } else if (cast && (!cast[options.typeKey] || (options.typeKey === 'type' && cast.type.type)) && 'Object' == utils.getFunctionName(cast.constructor) && Object.keys(cast).length) { // The `minimize` and `typeKey` options propagate to child schemas // declared inline, like `{ arr: [{ val: { $type: String } }] }`. // See gh-3560 var childSchemaOptions = { minimize: options.minimize }; if (options.typeKey) { childSchemaOptions.typeKey = options.typeKey; } var childSchema = new Schema(cast, childSchemaOptions); return new MongooseTypes.DocumentArray(path, childSchema, obj); } return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj); } if (type instanceof Schema) { return new MongooseTypes.Embedded(type, path, obj); } var name; if (Buffer.isBuffer(type)) { name = 'Buffer'; } else { name = 'string' == typeof type ? type // If not string, `type` is a function. Outside of IE, function.name // gives you the function name. In IE, you need to compute it : type.schemaName || utils.getFunctionName(type); } if (name) { name = name.charAt(0).toUpperCase() + name.substring(1); } if (undefined == MongooseTypes[name]) { throw new TypeError('Undefined type `' + name + '` at `' + path + '`\n Did you try nesting Schemas? ' + 'You can only nest using refs or arrays.'); } return new MongooseTypes[name](path, obj); }; /** * Iterates the schemas paths similar to Array#forEach. * * The callback is passed the pathname and schemaType as arguments on each iteration. * * @param {Function} fn callback function * @return {Schema} this * @api public */ Schema.prototype.eachPath = function(fn) { var keys = Object.keys(this.paths), len = keys.length; for (var i = 0; i < len; ++i) { fn(keys[i], this.paths[keys[i]]); } return this; }; /** * Returns an Array of path strings that are required by this schema. * * @api public * @param {Boolean} invalidate refresh the cache * @return {Array} */ Schema.prototype.requiredPaths = function requiredPaths(invalidate) { if (this._requiredpaths && !invalidate) return this._requiredpaths; var paths = Object.keys(this.paths), i = paths.length, ret = []; while (i--) { var path = paths[i]; if (this.paths[path].isRequired) ret.push(path); } return this._requiredpaths = ret; }; /** * Returns indexes from fields and schema-level indexes (cached). * * @api private * @return {Array} */ Schema.prototype.indexedPaths = function indexedPaths() { if (this._indexedpaths) return this._indexedpaths; return this._indexedpaths = this.indexes(); }; /** * Returns the pathType of `path` for this schema. * * Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path. * * @param {String} path * @return {String} * @api public */ Schema.prototype.pathType = function(path) { if (path in this.paths) return 'real'; if (path in this.virtuals) return 'virtual'; if (path in this.nested) return 'nested'; if (path in this.subpaths) return 'real'; if (/\.\d+\.|\.\d+$/.test(path)) { return getPositionalPathType(this, path); } else { return 'adhocOrUndefined'; } }; /** * Returns true iff this path is a child of a mixed schema. * * @param {String} path * @return {Boolean} * @api private */ Schema.prototype.hasMixedParent = function(path) { var subpaths = path.split(/\./g); path = ''; for (var i = 0; i < subpaths.length; ++i) { path = i > 0 ? path + '.' + subpaths[i] : subpaths[i]; if (path in this.paths && this.paths[path] instanceof MongooseTypes.Mixed) { return true; } } return false; }; /*! * ignore */ function getPositionalPathType(self, path) { var subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean); if (subpaths.length < 2) { return self.paths[subpaths[0]]; } var val = self.path(subpaths[0]); var isNested = false; if (!val) return val; var last = subpaths.length - 1, subpath, i = 1; for (; i < subpaths.length; ++i) { isNested = false; subpath = subpaths[i]; if (i === last && val && !val.schema && !/\D/.test(subpath)) { if (val instanceof MongooseTypes.Array) { // StringSchema, NumberSchema, etc val = val.caster; } else { val = undefined; } break; } // ignore if its just a position segment: path.0.subpath if (!/\D/.test(subpath)) continue; if (!(val && val.schema)) { val = undefined; break; } var type = val.schema.pathType(subpath); isNested = (type === 'nested'); val = val.schema.path(subpath); } self.subpaths[path] = val; if (val) { return 'real'; } if (isNested) { return 'nested'; } return 'adhocOrUndefined'; } /*! * ignore */ function getPositionalPath(self, path) { getPositionalPathType(self, path); return self.subpaths[path]; } /** * Adds a method call to the queue. * * @param {String} name name of the document method to call later * @param {Array} args arguments to pass to the method * @api public */ Schema.prototype.queue = function(name, args) { this.callQueue.push([name, args]); return this; }; /** * Defines a pre hook for the document. * * ####Example * * var toySchema = new Schema(..); * * toySchema.pre('save', function (next) { * if (!this.created) this.created = new Date; * next(); * }) * * toySchema.pre('validate', function (next) { * if (this.name != 'Woody') this.name = 'Woody'; * next(); * }) * * @param {String} method * @param {Function} callback * @see hooks.js https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3 * @api public */ Schema.prototype.pre = function() { var name = arguments[0]; if (IS_QUERY_HOOK[name]) { this.s.hooks.pre.apply(this.s.hooks, arguments); return this; } return this.queue('pre', arguments); }; /** * Defines a post hook for the document * * Post hooks fire `on` the event emitted from document instances of Models compiled from this schema. * * var schema = new Schema(..); * schema.post('save', function (doc) { * console.log('this fired after a document was saved'); * }); * * var Model = mongoose.model('Model', schema); * * var m = new Model(..); * m.save(function (err) { * console.log('this fires after the `post` hook'); * }); * * @param {String} method name of the method to hook * @param {Function} fn callback * @see hooks.js https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3 * @api public */ Schema.prototype.post = function(method, fn) { if (IS_QUERY_HOOK[method]) { this.s.hooks.post.apply(this.s.hooks, arguments); return this; } // assuming that all callbacks with arity < 2 are synchronous post hooks if (fn.length < 2) { return this.queue('on', [arguments[0], function(doc) { return fn.call(doc, doc); }]); } return this.queue('post', [arguments[0], function(next) { // wrap original function so that the callback goes last, // for compatibility with old code that is using synchronous post hooks var self = this; var args = Array.prototype.slice.call(arguments, 1); fn.call(this, this, function(err) { return next.apply(self, [err].concat(args)); }); }]); }; /** * Registers a plugin for this schema. * * @param {Function} plugin callback * @param {Object} [opts] * @see plugins * @api public */ Schema.prototype.plugin = function(fn, opts) { fn(this, opts); return this; }; /** * Adds an instance method to documents constructed from Models compiled from this schema. * * ####Example * * var schema = kittySchema = new Schema(..); * * schema.method('meow', function () { * console.log('meeeeeoooooooooooow'); * }) * * var Kitty = mongoose.model('Kitty', schema); * * var fizz = new Kitty; * fizz.meow(); // meeeeeooooooooooooow * * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. * * schema.method({ * purr: function () {} * , scratch: function () {} * }); * * // later * fizz.purr(); * fizz.scratch(); * * @param {String|Object} method name * @param {Function} [fn] * @api public */ Schema.prototype.method = function(name, fn) { if ('string' != typeof name) for (var i in name) this.methods[i] = name[i]; else this.methods[name] = fn; return this; }; /** * Adds static "class" methods to Models compiled from this schema. * * ####Example * * var schema = new Schema(..); * schema.static('findByName', function (name, callback) { * return this.find({ name: name }, callback); * }); * * var Drink = mongoose.model('Drink', schema); * Drink.findByName('sanpellegrino', function (err, drinks) { * // * }); * * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics. * * @param {String} name * @param {Function} fn * @api public */ Schema.prototype.static = function(name, fn) { if ('string' != typeof name) for (var i in name) this.statics[i] = name[i]; else this.statics[name] = fn; return this; }; /** * Defines an index (most likely compound) for this schema. * * ####Example * * schema.index({ first: 1, last: -1 }) * * @param {Object} fields * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#createIndex) * @param {String} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link. * @api public */ Schema.prototype.index = function(fields, options) { options || (options = {}); if (options.expires) utils.expires(options); this._indexes.push([fields, options]); return this; }; /** * Sets/gets a schema option. * * ####Example * * schema.set('strict'); // 'true' by default * schema.set('strict', false); // Sets 'strict' to false * schema.set('strict'); // 'false' * * @param {String} key option name * @param {Object} [value] if not passed, the current option value is returned * @see Schema ./ * @api public */ Schema.prototype.set = function(key, value, _tags) { if (1 === arguments.length) { return this.options[key]; } switch (key) { case 'read': this.options[key] = readPref(value, _tags); break; case 'safe': this.options[key] = false === value ? { w: 0 } : value; break; default: this.options[key] = value; } return this; }; /** * Gets a schema option. * * @param {String} key option name * @api public */ Schema.prototype.get = function(key) { return this.options[key]; }; /** * The allowed index types * * @static indexTypes * @receiver Schema * @api public */ var indexTypes = '2d 2dsphere hashed text'.split(' '); Object.defineProperty(Schema, 'indexTypes', { get: function() { return indexTypes; }, set: function() { throw new Error('Cannot overwrite Schema.indexTypes'); } }); /** * Compiles indexes from fields and schema-level indexes * * @api public */ Schema.prototype.indexes = function() { 'use strict'; var indexes = []; var seenPrefix = {}; var collectIndexes = function(schema, prefix) { if (seenPrefix[prefix]) { return; } seenPrefix[prefix] = true; prefix = prefix || ''; var key, path, index, field, isObject, options, type; var keys = Object.keys(schema.paths); for (var i = 0; i < keys.length; ++i) { key = keys[i]; path = schema.paths[key]; if (path instanceof MongooseTypes.DocumentArray) { collectIndexes(path.schema, key + '.'); } else if (path.$isSingleNested) { collectIndexes(path.schema, key + '.'); } else { index = path._index; if (false !== index && null != index) { field = {}; isObject = utils.isObject(index); options = isObject ? index : {}; type = 'string' == typeof index ? index : isObject ? index.type : false; if (type && ~Schema.indexTypes.indexOf(type)) { field[prefix + key] = type; } else { field[prefix + key] = 1; } delete options.type; if (!('background' in options)) { options.background = true; } indexes.push([field, options]); } } } if (prefix) { fixSubIndexPaths(schema, prefix); } else { schema._indexes.forEach(function(index) { if (!('background' in index[1])) index[1].background = true; }); indexes = indexes.concat(schema._indexes); } }; collectIndexes(this); return indexes; /*! * Checks for indexes added to subdocs using Schema.index(). * These indexes need their paths prefixed properly. * * schema._indexes = [ [indexObj, options], [indexObj, options] ..] */ function fixSubIndexPaths(schema, prefix) { var subindexes = schema._indexes, len = subindexes.length, indexObj, newindex, klen, keys, key, i = 0, j; for (i = 0; i < len; ++i) { indexObj = subindexes[i][0]; keys = Object.keys(indexObj); klen = keys.length; newindex = {}; // use forward iteration, order matters for (j = 0; j < klen; ++j) { key = keys[j]; newindex[prefix + key] = indexObj[key]; } indexes.push([newindex, subindexes[i][1]]); } } }; /** * Creates a virtual type with the given name. * * @param {String} name * @param {Object} [options] * @return {VirtualType} */ Schema.prototype.virtual = function(name, options) { var virtuals = this.virtuals; var parts = name.split('.'); return virtuals[name] = parts.reduce(function(mem, part, i) { mem[part] || (mem[part] = (i === parts.length - 1) ? new VirtualType(options, name) : {}); return mem[part]; }, this.tree); }; /** * Returns the virtual type with the given `name`. * * @param {String} name * @return {VirtualType} */ Schema.prototype.virtualpath = function(name) { return this.virtuals[name]; }; /** * Removes the given `path` (or [`paths`]). * * @param {String|Array} path * * @api public */ Schema.prototype.remove = function(path) { if (typeof path === 'string') { path = [path]; } if (Array.isArray(path)) { path.forEach(function(name) { if (this.path(name)) { delete this.paths[name]; } }, this); } }; /*! * ignore */ Schema.prototype._getSchema = function(path) { var schema = this; var pathschema = schema.path(path); if (pathschema) { return pathschema; } // look for arrays return (function search(parts, schema) { var p = parts.length + 1, foundschema, trypath; while (p--) { trypath = parts.slice(0, p).join('.'); foundschema = schema.path(trypath); if (foundschema) { if (foundschema.caster) { // array of Mixed? if (foundschema.caster instanceof MongooseTypes.Mixed) { return foundschema.caster; } // Now that we found the array, we need to check if there // are remaining document paths to look up for casting. // Also we need to handle array.$.path since schema.path // doesn't work for that. // If there is no foundschema.schema we are dealing with // a path like array.$ if (p !== parts.length && foundschema.schema) { if ('$' === parts[p]) { // comments.$.comments.$.title return search(parts.slice(p + 1), foundschema.schema); } else { // this is the last path of the selector return search(parts.slice(p), foundschema.schema); } } } return foundschema; } } })(path.split('.'), schema); }; /*! * Module exports. */ module.exports = exports = Schema; // require down here because of reference issues /** * The various built-in Mongoose Schema Types. * * ####Example: * * var mongoose = require('mongoose'); * var ObjectId = mongoose.Schema.Types.ObjectId; * * ####Types: * * - [String](#schema-string-js) * - [Number](#schema-number-js) * - [Boolean](#schema-boolean-js) | Bool * - [Array](#schema-array-js) * - [Buffer](#schema-buffer-js) * - [Date](#schema-date-js) * - [ObjectId](#schema-objectid-js) | Oid * - [Mixed](#schema-mixed-js) * * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema. * * var Mixed = mongoose.Schema.Types.Mixed; * new mongoose.Schema({ _user: Mixed }) * * @api public */ Schema.Types = MongooseTypes = require('./schema/index'); /*! * ignore */ exports.ObjectId = MongooseTypes.ObjectId;
'use strict'; var warn = require('./lib/warning'); var hasLocalStorage = 'localStorage' in global; var ls, testKey; if (hasLocalStorage) { testKey = 'react-localstorage.mixin.test-key'; try { // Access to global `localStorage` property must be guarded as it // fails under iOS private session mode. ls = global.localStorage; ls.setItem(testKey, 'foo'); ls.removeItem(testKey); } catch (e) { hasLocalStorage = false; } } // Warn if localStorage cannot be found or accessed. if (process.browser) { warn( hasLocalStorage, 'localStorage not found. Component state will not be stored to localStorage.' ); } module.exports = { /** * Error checking. On update, ensure that the last state stored in localStorage is equal * to the state on the component. We skip the check the first time around as state is left * alone until mount to keep server rendering working. * * If it is not consistent, we know that someone else is modifying localStorage out from under us, so we throw * an error. * * There are a lot of ways this can happen, so it is worth throwing the error. */ componentWillUpdate: function(nextProps, nextState) { if (!hasLocalStorage || !this.__stateLoadedFromLS) return; var key = getLocalStorageKey(this); if (key === false) return; var prevStoredState = ls.getItem(key); if (prevStoredState && process.env.NODE_ENV !== "production") { warn( prevStoredState === JSON.stringify(getSyncState(this, this.state)), 'While component ' + getDisplayName(this) + ' was saving state to localStorage, ' + 'the localStorage entry was modified by another actor. This can happen when multiple ' + 'components are using the same localStorage key. Set the property `localStorageKey` ' + 'on ' + getDisplayName(this) + '.' ); } // Since setState() can't be called in CWU, it's a fine time to save the state. ls.setItem(key, JSON.stringify(getSyncState(this, nextState))); }, /** * Load data. * This seems odd to do this on componentDidMount, but it prevents server checksum errors. * This is because the server has no way to know what is in your localStorage. So instead * of breaking the checksum and causing a full rerender, we instead change the component after mount * for an efficient diff. */ componentDidMount: function () { if (!hasLocalStorage) return; var me = this; loadStateFromLocalStorage(this, function() { // After setting state, mirror back to localstorage. // This prevents invariants if the developer has changed the initial state of the component. ls.setItem(getLocalStorageKey(me), JSON.stringify(getSyncState(me, me.state))); }); } }; function loadStateFromLocalStorage(component, cb) { if (!ls) return; var key = getLocalStorageKey(component); if (key === false) return; var settingState = false; try { var storedState = JSON.parse(ls.getItem(key)); if (storedState) { settingState = true; component.setState(storedState, done); } } catch(e) { // eslint-disable-next-line no-console if (console) console.warn("Unable to load state for", getDisplayName(component), "from localStorage."); } // If we didn't set state, run the callback right away. if (!settingState) done(); function done() { // Flag this component as loaded. component.__stateLoadedFromLS = true; cb(); } } function getDisplayName(component) { // at least, we cannot get displayname // via this.displayname in react 0.12 return component.displayName || component.constructor.displayName || component.constructor.name; } function getLocalStorageKey(component) { if (component.getLocalStorageKey) return component.getLocalStorageKey(); if (component.props.localStorageKey === false) return false; if (typeof component.props.localStorageKey === 'function') return component.props.localStorageKey.call(component); return component.props.localStorageKey || getDisplayName(component) || 'react-localstorage'; } function getStateFilterKeys(component) { if (component.getStateFilterKeys) { return typeof component.getStateFilterKeys() === 'string' ? [component.getStateFilterKeys()] : component.getStateFilterKeys(); } return typeof component.props.stateFilterKeys === 'string' ? [component.props.stateFilterKeys] : component.props.stateFilterKeys; } /** * Filters state to only save keys defined in stateFilterKeys. * If stateFilterKeys is not set, returns full state. */ function getSyncState(component, state) { var stateFilterKeys = getStateFilterKeys(component); if (!stateFilterKeys || !state) return state; var result = {}, key; for (var i = 0; i < stateFilterKeys.length; i++) { key = stateFilterKeys[i]; if (state.hasOwnProperty(key)) result[key] = state[key]; } return result; }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict'; module.metadata = { "stability": "experimental", "engines": { "Firefox": "*" } }; const { Cc, Ci } = require('chrome'); const { Class } = require('../core/heritage'); const { method } = require('../lang/functional'); const { defer, promised, all } = require('../core/promise'); const { send } = require('../addon/events'); const { EventTarget } = require('../event/target'); const { merge } = require('../util/object'); const bmsrv = Cc["@mozilla.org/browser/nav-bookmarks-service;1"]. getService(Ci.nsINavBookmarksService); /* * TreeNodes are used to construct dependency trees * for BookmarkItems */ let TreeNode = Class({ initialize: function (value) { this.value = value; this.children = []; }, add: function (values) { [].concat(values).forEach(value => { this.children.push(value instanceof TreeNode ? value : TreeNode(value)); }); }, get length () { let count = 0; this.walk(() => count++); // Do not count the current node return --count; }, get: method(get), walk: method(walk), toString: function () '[object TreeNode]' }); exports.TreeNode = TreeNode; /* * Descends down from `node` applying `fn` to each in order. * Can be asynchronous if `fn` returns a promise. `fn` is passed * one argument, the current node, `curr` */ function walk (curr, fn) { return promised(fn)(curr).then(val => { return all(curr.children.map(child => walk(child, fn))); }); } /* * Descends from the TreeNode `node`, returning * the node with value `value` if found or `null` * otherwise */ function get (node, value) { if (node.value === value) return node; for (let child of node.children) { let found = get(child, value); if (found) return found; } return null; } /* * Constructs a tree of bookmark nodes * returning the root (value: null); */ function constructTree (items) { let root = TreeNode(null); items.forEach(treeify.bind(null, root)); function treeify (root, item) { // If node already exists, skip let node = root.get(item); if (node) return node; node = TreeNode(item); let parentNode = item.group ? treeify(root, item.group) : root; parentNode.add(node); return node; } return root; } exports.constructTree = constructTree; /* * Shortcut for converting an id, or an object with an id, into * an object with corresponding bookmark data */ function fetchItem (item) send('sdk-places-bookmarks-get', { id: item.id || item }) exports.fetchItem = fetchItem; /* * Takes an ID or an object with ID and checks it against * the root bookmark folders */ function isRootGroup (id) { id = id && id.id; return ~[bmsrv.bookmarksMenuFolder, bmsrv.toolbarFolder, bmsrv.unfiledBookmarksFolder ].indexOf(id); } exports.isRootGroup = isRootGroup; /* * Merges appropriate options into query based off of url * 4 scenarios: * * 'moz.com' // domain: moz.com, domainIsHost: true * --> 'http://moz.com', 'http://moz.com/thunderbird' * '*.moz.com' // domain: moz.com, domainIsHost: false * --> 'http://moz.com', 'http://moz.com/index', 'http://ff.moz.com/test' * 'http://moz.com' // url: http://moz.com/, urlIsPrefix: false * --> 'http://moz.com/' * 'http://moz.com/*' // url: http://moz.com/, urlIsPrefix: true * --> 'http://moz.com/', 'http://moz.com/thunderbird' */ function urlQueryParser (query, url) { if (!url) return; if (/^https?:\/\//.test(url)) { query.uri = url.charAt(url.length - 1) === '/' ? url : url + '/'; if (/\*$/.test(url)) { query.uri = url.replace(/\*$/, ''); query.uriIsPrefix = true; } } else { if (/^\*/.test(url)) { query.domain = url.replace(/^\*\./, ''); query.domainIsHost = false; } else { query.domain = url; query.domainIsHost = true; } } } exports.urlQueryParser = urlQueryParser; /* * Takes an EventEmitter and returns a promise that * aggregates results and handles a bulk resolve and reject */ function promisedEmitter (emitter) { let { promise, resolve, reject } = defer(); let errors = []; emitter.on('error', error => errors.push(error)); emitter.on('end', (items) => { if (errors.length) reject(errors[0]); else resolve(items); }); return promise; } exports.promisedEmitter = promisedEmitter; // https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsINavHistoryQueryOptions function createQuery (type, query) { query = query || {}; let qObj = { searchTerms: query.query }; urlQueryParser(qObj, query.url); // 0 === history if (type === 0) { // PRTime used by query is in microseconds, not milliseconds qObj.beginTime = (query.from || 0) * 1000; qObj.endTime = (query.to || new Date()) * 1000; // Set reference time to Epoch qObj.beginTimeReference = 0; qObj.endTimeReference = 0; } // 1 === bookmarks else if (type === 1) { qObj.tags = query.tags; qObj.folder = query.group && query.group.id; } // 2 === unified (not implemented on platform) else if (type === 2) { } return qObj; } exports.createQuery = createQuery; // https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsINavHistoryQueryOptions const SORT_MAP = { title: 1, date: 3, // sort by visit date url: 5, visitCount: 7, // keywords currently unsupported // keyword: 9, dateAdded: 11, // bookmarks only lastModified: 13 // bookmarks only }; function createQueryOptions (type, options) { options = options || {}; let oObj = {}; oObj.sortingMode = SORT_MAP[options.sort] || 0; if (options.descending && options.sort) oObj.sortingMode++; // Resolve to default sort if ineligible based on query type if (type === 0 && // history (options.sort === 'dateAdded' || options.sort === 'lastModified')) oObj.sortingMode = 0; oObj.maxResults = typeof options.count === 'number' ? options.count : 0; oObj.queryType = type; return oObj; } exports.createQueryOptions = createQueryOptions; function mapBookmarkItemType (type) { if (typeof type === 'number') { if (bmsrv.TYPE_BOOKMARK === type) return 'bookmark'; if (bmsrv.TYPE_FOLDER === type) return 'group'; if (bmsrv.TYPE_SEPARATOR === type) return 'separator'; } else { if ('bookmark' === type) return bmsrv.TYPE_BOOKMARK; if ('group' === type) return bmsrv.TYPE_FOLDER; if ('separator' === type) return bmsrv.TYPE_SEPARATOR; } } exports.mapBookmarkItemType = mapBookmarkItemType;
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'pastetext', 'gu', { button: 'પેસ્ટ (ટેક્સ્ટ)', title: 'પેસ્ટ (ટેક્સ્ટ)' } );
/*! * froala_editor v2.4.0-rc.1 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms/ * Copyright 2014-2016 Froala Labs */ /** * Indonesian */ $.FE.LANGUAGE['id'] = { translation: { // Place holder "Type something": "Ketik sesuatu", // Basic formatting "Bold": "Tebal", "Italic": "Miring", "Underline": "Garis bawah", "Strikethrough": "Coret", // Main buttons "Insert": "Memasukkan", "Delete": "Hapus", "Cancel": "Batal", "OK": "Ok", "Back": "Kembali", "Remove": "Hapus", "More": "Lebih", "Update": "Memperbarui", "Style": "Gaya", // Font "Font Family": "Jenis Huruf", "Font Size": "Ukuran leter", // Colors "Colors": "Warna", "Background": "Latar belakang", "Text": "Teks", // Paragraphs "Paragraph Format": "Format", "Normal": "Normal", "Code": "Kode", "Heading 1": "Header 1", "Heading 2": "Header 2", "Heading 3": "Header 3", "Heading 4": "Header 4", // Style "Paragraph Style": "Paragraf gaya", "Inline Style": "Di barisan gaya", // Alignment "Align": "Rate", "Align Left": "Rate kiri", "Align Center": "Rate tengah", "Align Right": "Rata kanan", "Align Justify": "Justifi", "None": "Tak satupun", // Lists "Ordered List": "List nomor", "Unordered List": "List simbol", // Indent "Decrease Indent": "Turunkan inden", "Increase Indent": "Tambah inden", // Links "Insert Link": "Memasukkan link", "Open in new tab": "Buka di tab baru", "Open Link": "Buka tautan", "Edit Link": "Mengedit link", "Unlink": "Menghapus link", "Choose Link": "Memilih link", // Images "Insert Image": "Memasukkan gambar", "Upload Image": "Meng-upload gambar", "By URL": "Oleh URL", "Browse": "Melihat-lihat", "Drop image": "Jatuhkan gambar", "or click": "atau klik", "Manage Images": "Mengelola gambar", "Loading": "Pemuatan", "Deleting": "Menghapus", "Tags": "Label", "Are you sure? Image will be deleted.": "Apakah Anda yakin? Gambar akan dihapus.", "Replace": "Mengganti", "Uploading": "Gambar upload", "Loading image": "Pemuatan gambar", "Display": "Pameran", "Inline": "Di barisan", "Break Text": "Memecah teks", "Alternate Text": "Teks alternatif", "Change Size": "Ukuran perubahan", "Width": "Lebar", "Height": "Tinggi", "Something went wrong. Please try again.": "Ada yang salah. Silakan coba lagi.", // Video "Insert Video": "Memasukkan video", "Embedded Code": "Kode tertanam", // Tables "Insert Table": "Sisipkan tabel", "Table Header": "Header tabel", "Remove Table": "Hapus tabel", "Table Style": "Gaya tabel", "Horizontal Align": "Menyelaraskan horisontal", "Row": "Baris", "Insert row above": "Sisipkan baris di atas", "Insert row below": "Sisipkan baris di bawah", "Delete row": "Hapus baris", "Column": "Kolom", "Insert column before": "Sisipkan kolom sebelumSisipkan kolom sebelum", "Insert column after": "Sisipkan kolom setelah", "Delete column": "Hapus kolom", "Cell": "Sel", "Merge cells": "Menggabungkan sel", "Horizontal split": "Perpecahan horisontal", "Vertical split": "Perpecahan vertikal", "Cell Background": "Latar belakang sel", "Vertical Align": "Menyelaraskan vertikal", "Top": "Teratas", "Middle": "Tengah", "Bottom": "Bagian bawah", "Align Top": "Menyelaraskan atas", "Align Middle": "Menyelaraskan tengah", "Align Bottom": "Menyelaraskan bawah", "Cell Style": "Gaya sel", // Files "Upload File": "Meng-upload berkas", "Drop file": "Jatuhkan berkas", // Emoticons "Emoticons": "Emoticon", "Grinning face": "Sambil tersenyum wajah", "Grinning face with smiling eyes": "Sambil tersenyum wajah dengan mata tersenyum", "Face with tears of joy": "Hadapi dengan air mata sukacita", "Smiling face with open mouth": "Tersenyum wajah dengan mulut terbuka", "Smiling face with open mouth and smiling eyes": "Tersenyum wajah dengan mulut terbuka dan tersenyum mata", "Smiling face with open mouth and cold sweat": "Tersenyum wajah dengan mulut terbuka dan keringat dingin", "Smiling face with open mouth and tightly-closed eyes": "Tersenyum wajah dengan mulut terbuka dan mata tertutup rapat", "Smiling face with halo": "Tersenyum wajah dengan halo", "Smiling face with horns": "Tersenyum wajah dengan tanduk", "Winking face": "Mengedip wajah", "Smiling face with smiling eyes": "Tersenyum wajah dengan mata tersenyum", "Face savoring delicious food": "Wajah menikmati makanan lezat", "Relieved face": "Wajah Lega", "Smiling face with heart-shaped eyes": "Tersenyum wajah dengan mata berbentuk hati", "Smiling face with sunglasses": "Tersenyum wajah dengan kacamata hitam", "Smirking face": "Menyeringai wajah", "Neutral face": "Wajah Netral", "Expressionless face": "Wajah tanpa ekspresi", "Unamused face": "Wajah tidak senang", "Face with cold sweat": "Muka dengan keringat dingin", "Pensive face": "Wajah termenung", "Confused face": "Wajah Bingung", "Confounded face": "Wajah kesal", "Kissing face": "wajah mencium", "Face throwing a kiss": "Wajah melempar ciuman", "Kissing face with smiling eyes": "Berciuman wajah dengan mata tersenyum", "Kissing face with closed eyes": "Berciuman wajah dengan mata tertutup", "Face with stuck out tongue": "Muka dengan menjulurkan lidah", "Face with stuck out tongue and winking eye": "Muka dengan menjulurkan lidah dan mengedip mata", "Face with stuck out tongue and tightly-closed eyes": "Wajah dengan lidah terjebak dan mata erat-tertutup", "Disappointed face": "Wajah kecewa", "Worried face": "Wajah Khawatir", "Angry face": "Wajah Marah", "Pouting face": "Cemberut wajah", "Crying face": "Menangis wajah", "Persevering face": "Tekun wajah", "Face with look of triumph": "Hadapi dengan tampilan kemenangan", "Disappointed but relieved face": "Kecewa tapi lega wajah", "Frowning face with open mouth": "Sambil mengerutkan kening wajah dengan mulut terbuka", "Anguished face": "Wajah sedih", "Fearful face": "Wajah Takut", "Weary face": "Wajah lelah", "Sleepy face": "wajah mengantuk", "Tired face": "Wajah Lelah", "Grimacing face": "Sambil meringis wajah", "Loudly crying face": "Keras menangis wajah", "Face with open mouth": "Hadapi dengan mulut terbuka", "Hushed face": "Wajah dipetieskan", "Face with open mouth and cold sweat": "Hadapi dengan mulut terbuka dan keringat dingin", "Face screaming in fear": "Hadapi berteriak dalam ketakutan", "Astonished face": "Wajah Kaget", "Flushed face": "Wajah memerah", "Sleeping face": "Tidur face", "Dizzy face": "Wajah pusing", "Face without mouth": "Wajah tanpa mulut", "Face with medical mask": "Hadapi dengan masker medis", // Line breaker "Break": "Memecah", // Math "Subscript": "Subskrip", "Superscript": "Superskrip", // Full screen "Fullscreen": "Layar penuh", // Horizontal line "Insert Horizontal Line": "Sisipkan Garis Horizontal", // Clear formatting "Clear Formatting": "Menghapus format", // Undo, redo "Undo": "Batal", "Redo": "Ulang", // Select all "Select All": "Pilih semua", // Code view "Code View": "Melihat kode", // Quote "Quote": "Kutipan", "Increase": "Meningkat", "Decrease": "Penurunan", // Quick Insert "Quick Insert": "Memasukkan cepat" }, direction: "ltr" };
(function(w,t,J){function D(a,b){function e(){}e.prototype=a;var c=new e,E;for(E in b)c[E]=b[E];b.toString!==Object.prototype.toString&&(c.toString=b.toString);return c}function d(a,b){if(null==b)return null;null==b.__id__&&(b.__id__=K++);var e;null==a.hx__closures__?a.hx__closures__={}:e=a.hx__closures__[b.__id__];null==e&&(e=function(){return e.method.apply(e.scope,arguments)},e.scope=a,e.method=b,a.hx__closures__[b.__id__]=e);return e}var B=function(){this.bufferList=new p;this.types=new p;this.types.set("mp3", "audio/mpeg");this.types.set("ogg","audio/ogg");this.types.set("wav","audio/wav");this.types.set("aac","audio/aac");this.types.set("m4a","audio/x-m4a")};B.__name__=!0;B.prototype={checkWebAudioAPISupport:function(){return null!=g.field(window,"AudioContext")||null!=g.field(window,"webkitAudioContext")},unlockAudio:function(){if(null!=this.audioContext){var a=this.audioContext.createBuffer(1,1,c.preferredSampleRate),b=this.audioContext.createBufferSource();b.buffer=a;b.connect(this.audioContext.destination); null!=g.field(b,"start")?b.start(0):b.noteOn(0);null!=b.onended?b.onended=d(this,this._unlockCallback):q.delay(d(this,this._unlockCallback),1)}else a=window.document.createElement("audio"),b=window.document.createElement("source"),b.src="data:audio/wave;base64,UklGRjIAAABXQVZFZm10IBIAAAABAAEAQB8AAEAfAAABAAgAAABmYWN0BAAAAAAAAABkYXRhAAAAAA==",a.appendChild(b),window.document.appendChild(a),a.play(),null!=c.__touchUnlockCallback&&c.__touchUnlockCallback(),c.dom.ontouchend=null},_unlockCallback:function(){null!= c.__touchUnlockCallback&&c.__touchUnlockCallback();c.dom.ontouchend=null},createAudioContext:function(){if(null==this.audioContext)try{null!=g.field(window,"AudioContext")?this.audioContext=new AudioContext:null!=g.field(window,"webkitAudioContext")&&(this.audioContext=new webkitAudioContext)}catch(a){a instanceof m&&(a=a.val),this.audioContext=null}return this.audioContext},destroy:function(){null!=this.audioContext&&null!=this.audioContext.close&&""!=this.audioContext.close&&this.audioContext.close(); this.types=this.bufferList=this.audioContext=null},__class__:B};var r=function(a,b){this._b64=new k("(^data:audio).*(;base64,)","i");null!=a&&""!=a&&null!=c.audioManager&&(this.isSpriteSound=!1,this.url=a,this._muted=this._isPlaying=this._isLoaded=!1,this._duration=0,this.rate=1,null==b&&(b={}),b.autoplay=null!=b.autoplay?b.autoplay:c.defaults.autoplay,b.autostop=null!=b.autostop?b.autostop:c.defaults.autostop,b.webaudio=null!=b.webaudio?b.webaudio:c.defaults.webaudio,b.preload=null!=b.preload?b.preload: c.defaults.preload,b.loop=null!=b.loop?b.loop:c.defaults.loop,b.volume=null!=b.volume&&0<=b.volume&&1>=b.volume?b.volume:c.defaults.volume,b.onload=null!=b.onload?b.onload:c.defaults.onload,b.onend=null!=b.onend?b.onend:c.defaults.onend,b.onerror=null!=b.onerror?b.onerror:c.defaults.onerror,this._options=b)};r.__name__=!0;r.prototype={isReady:function(){return this._isLoaded},__class__:r};var k=function(a,b){b=b.split("u").join("");this.r=new RegExp(a,b)};k.__name__=!0;k.prototype={match:function(a){this.r.global&& (this.r.lastIndex=0);this.r.m=this.r.exec(a);this.r.s=a;return null!=this.r.m},matched:function(a){if(null!=this.r.m&&0<=a&&a<this.r.m.length)return this.r.m[a];throw new m("EReg::matched");},__class__:k};w=function(){};w.__name__=!0;w.prototype={__class__:w};var x=function(a,b,e){r.call(this,a,b);this._snd=c.dom.createElement("audio");null==e?this._addSource(a):this._snd.appendChild(e);this._options.preload&&this.load();this._b64.match(a)};x.__name__=!0;x.__interfaces__=[w];x.__super__=r;x.prototype= D(r.prototype,{load:function(a){var b=this;this._isLoaded||(this._snd.autoplay=this._options.autoplay,this._snd.loop=this._options.loop,this._snd.volume=this._options.volume,this._snd.playbackRate=this.rate,null!=a&&(this._options.onload=a),this._snd.preload=this._options.preload?"auto":"metadata",null!=this._options.onload&&(this._isLoaded=!0,this._snd.onloadeddata=function(){b._options.onload(b)}),this._snd.onplaying=function(){b._isPlaying=!0},this._snd.onended=function(){b._isPlaying=!1;if(null!= b._options.onend)b._options.onend(b)},null!=this._options.onerror&&(this._snd.onerror=function(){b._options.onerror(b)}),this._snd.load());return this},getDuration:function(){return this._isLoaded?this._duration=this._snd.duration:0},_addSource:function(a){this.source=c.dom.createElement("source");this.source.src=a;var b=this._getExt(a);null!=c.audioManager.types.get(b)&&(a=this._getExt(a),this.source.type=c.audioManager.types.get(a));this._snd.appendChild(this.source);return this.source},_getExt:function(a){return a.split(".").pop()}, setVolume:function(a,b){0<=a&&1>=a&&(this._options.volume=a);this._isLoaded&&(this._snd.volume=this._options.volume)},getVolume:function(a){return this._options.volume},mute:function(a,b){this._isLoaded&&(this._snd.muted=a,n.isiOS()&&(a&&this.isPlaying()?(this._muted=!0,this._snd.pause()):this._muted&&(this._muted=!1,this._snd.play())))},toggleMute:function(a){this.mute(!this._muted)},play:function(a,b){var e=this;this.spriteName=a;if(!this._isLoaded||null==this._snd)return-1;if(this._isPlaying)if(this._options.autostop)this.stop(this.spriteName); else{var c;c=h.__cast(this._snd.cloneNode(!0),HTMLAudioElement);q.delay(d(c,c.play),100)}if(this._muted)return-1;this.isSpriteSound&&null!=b&&(this._snd.currentTime=null==this._pauseTime?b.start:this._pauseTime,null!=this._tmr&&this._tmr.stop(),this._tmr=q.delay(function(){null!=b.loop&&b.loop?e.play(e.spriteName,b):e.stop(e.spriteName)},Math.ceil(1E3*b.duration)));q.delay((z=this._snd,d(z,z.play)),100);this._pauseTime=null;return 0},togglePlay:function(a){this._isPlaying?this.pause():this.play()}, isPlaying:function(a){return this._isPlaying},loop:function(a){this._isLoaded&&null!=this._snd&&(this._snd.loop=a)},autoStop:function(a){this._options.autostop=a},stop:function(a){this._isLoaded&&null!=this._snd&&(this._snd.currentTime=0,this._snd.pause(),this._isPlaying=!1,null!=this._tmr&&this._tmr.stop())},pause:function(a){this._isLoaded&&null!=this._snd&&(this._snd.pause(),this._pauseTime=this._snd.currentTime,this._isPlaying=!1,null!=this._tmr&&this._tmr.stop())},playbackRate:function(a,b){return null== a?this.rate:this.rate=this._snd.playbackRate=a},setTime:function(a){!this._isLoaded||null==this._snd||a>this._snd.duration||(this._snd.currentTime=a)},getTime:function(){return null!=this._snd&&this._isLoaded&&this._isPlaying?this._snd.currentTime:0},onEnd:function(a,b){this._options.onend=a;return this},onLoad:function(a){this._options.onload=a;return this},onError:function(a){this._options.onerror=a;return this},destroy:function(){null!=this._snd&&(this._snd.pause(),this._snd.removeChild(this.source), this._snd=this.source=null);this._isPlaying=!1},__class__:x});var u=function(){};u.__name__=!0;u.cca=function(a,b){var e=a.charCodeAt(b);return e!=e?void 0:e};u.indexOf=function(a,b,e){var c=a.length;0>e&&(e+=c,0>e&&(e=0));for(;e<c;){if(a[e]===b)return e;e++}return-1};Math.__name__=!0;var g=function(){};g.__name__=!0;g.field=function(a,b){try{return a[b]}catch(e){return e instanceof m&&(e=e.val),null}};g.fields=function(a){var b=[];if(null!=a){var e=Object.prototype.hasOwnProperty,c;for(c in a)"__id__"!= c&&"hx__closures__"!=c&&e.call(a,c)&&b.push(c)}return b};var v=function(){};v.__name__=!0;v.string=function(a){return h.__string_rec(a,"")};v.parseInt=function(a){var b=parseInt(a,10);0!=b||120!=u.cca(a,1)&&88!=u.cca(a,1)||(b=parseInt(a));return isNaN(b)?null:b};var c=t.Waud=function(){};c.__name__=!0;c.init=function(a){null==c.__audioElement&&(null==a&&(a=window.document),c.dom=a,c.__audioElement=c.dom.createElement("audio"),null==c.audioManager&&(c.audioManager=new B),c.isWebAudioSupported=c.audioManager.checkWebAudioAPISupport(), c.isHTML5AudioSupported=null!=g.field(window,"Audio"),c.isWebAudioSupported&&(c.audioContext=c.audioManager.createAudioContext()),c.sounds=new p)};c.autoMute=function(){c._focusManager=new l;c._focusManager.focus=function(){if(!c.isMuted&&null!=c.sounds)for(var a=c.sounds.iterator();a.hasNext();)a.next().mute(!1)};c._focusManager.blur=function(){if(null!=c.sounds)for(var a=c.sounds.iterator();a.hasNext();)a.next().mute(!0)}};c.enableTouchUnlock=function(a){c.__touchUnlockCallback=a;c.dom.ontouchend= (z=c.audioManager,d(z,z.unlockAudio))};c.mute=function(a){null==a&&(a=!0);c.isMuted=a;if(null!=c.sounds)for(var b=c.sounds.iterator();b.hasNext();)b.next().mute(a)};c.playbackRate=function(a){if(null==a)return c._playbackRate;if(null!=c.sounds)for(var b=c.sounds.iterator();b.hasNext();)b.next().playbackRate(a);return c._playbackRate=a};c.stop=function(){if(null!=c.sounds)for(var a=c.sounds.iterator();a.hasNext();)a.next().stop()};c.pause=function(){if(null!=c.sounds)for(var a=c.sounds.iterator();a.hasNext();)a.next().pause()}; c.getFormatSupportString=function(){var a="OGG: "+c.__audioElement.canPlayType('audio/ogg; codecs="vorbis"'),a=a+(", WAV: "+c.__audioElement.canPlayType('audio/wav; codecs="1"')),a=a+(", MP3: "+c.__audioElement.canPlayType("audio/mpeg;")),a=a+(", AAC: "+c.__audioElement.canPlayType("audio/aac;"));return a+=", M4A: "+c.__audioElement.canPlayType("audio/x-m4a;")};c.isSupported=function(){if(null==c.isWebAudioSupported||null==c.isHTML5AudioSupported)c.isWebAudioSupported=c.audioManager.checkWebAudioAPISupport(), c.isHTML5AudioSupported=null!=g.field(window,"Audio");return c.isWebAudioSupported||c.isHTML5AudioSupported};c.isOGGSupported=function(){var a=c.__audioElement.canPlayType('audio/ogg; codecs="vorbis"');return c.isHTML5AudioSupported&&null!=a&&("probably"==a||"maybe"==a)};c.isWAVSupported=function(){var a=c.__audioElement.canPlayType('audio/wav; codecs="1"');return c.isHTML5AudioSupported&&null!=a&&("probably"==a||"maybe"==a)};c.isMP3Supported=function(){var a=c.__audioElement.canPlayType("audio/mpeg;"); return c.isHTML5AudioSupported&&null!=a&&("probably"==a||"maybe"==a)};c.isAACSupported=function(){var a=c.__audioElement.canPlayType("audio/aac;");return c.isHTML5AudioSupported&&null!=a&&("probably"==a||"maybe"==a)};c.isM4ASupported=function(){var a=c.__audioElement.canPlayType("audio/x-m4a;");return c.isHTML5AudioSupported&&null!=a&&("probably"==a||"maybe"==a)};c.get_sampleRate=function(){return null!=c.audioContext?c.audioContext.sampleRate:0};c.destroy=function(){if(null!=c.sounds)for(var a=c.sounds.iterator();a.hasNext();)a.next().destroy(); c.sounds=null;null!=c.audioManager&&c.audioManager.destroy();c.audioManager=null;c.audioContext=null;c.__audioElement=null;null!=c._focusManager&&(c._focusManager.clearEvents(),c._focusManager.blur=null,c._focusManager.focus=null,c._focusManager=null)};var F=t.WaudBase64Pack=function(a,b,e,f){null!=c.audioManager&&0<a.indexOf(".json")&&(this._loadCount=this._soundCount=this._totalSize=this.progress=0,this._onLoaded=b,this._onProgress=e,this._onError=f,this._sounds=new p,this._loadBase64Json(a))}; F.__name__=!0;F.prototype={_loadBase64Json:function(a){var b=this,c=new k('"meta":.[0-9]*,[0-9]*.',"i"),f=new XMLHttpRequest;f.open("GET",a,!0);null!=this._onProgress&&(f.onprogress=function(a){if(c.match(f.responseText)&&0==b._totalSize){var d=JSON.parse("{"+c.matched(0)+"}");b._totalSize=d.meta[1]}b.progress=a.lengthComputable?a.loaded/a.total:a.loaded/b._totalSize;1<b.progress&&(b.progress=1);b._onProgress(b.progress,a.loaded)});f.onreadystatechange=function(){if(4==f.readyState&&200==f.status)for(var a= JSON.parse(f.responseText),c=0,e=g.fields(a);c<e.length;){var d=e[c];++c;"meta"!=d&&(b._soundCount++,a instanceof Array&&null==a.__enum__?b._createSound(g.field(a,d).name,"data:"+v.string(g.field(a,d).mime)+";base64,"+v.string(g.field(a,d).data)):b._createSound(d,g.field(a,d)))}};f.send(null)},_createSound:function(a,b){var e=this;new A(b,{onload:function(b){e._sounds.set(a,b);c.sounds.set(a,b);e._checkProgress()},onerror:function(b){e._sounds.set(a,null);e._checkProgress()&&null!=e._onError&&e._onError()}})}, _checkProgress:function(){this._loadCount++;return this._loadCount==this._soundCount?(null!=this._onLoaded&&this._onLoaded(this._sounds),0==this.progress&&null!=this._onProgress&&(this.progress=1,this._onProgress(this.progress,this._totalSize)),!0):!1},__class__:F};var l=t.WaudFocusManager=function(){var a=this;this._currentState=this._visibilityChange=this._hidden="";null!=g.field(window.document,"hidden")?(this._hidden="hidden",this._visibilityChange="visibilitychange"):null!=g.field(window.document, "mozHidden")?(this._hidden="mozHidden",this._visibilityChange="mozvisibilitychange"):null!=g.field(window.document,"msHidden")?(this._hidden="msHidden",this._visibilityChange="msvisibilitychange"):null!=g.field(window.document,"webkitHidden")&&(this._hidden="webkitHidden",this._visibilityChange="webkitvisibilitychange");null!=g.field(window,"addEventListener")?(window.addEventListener("focus",d(this,this._focus)),window.addEventListener("blur",d(this,this._blur)),window.addEventListener("pageshow", d(this,this._focus)),window.addEventListener("pagehide",d(this,this._blur)),document.addEventListener(this._visibilityChange,d(this,this._handleVisibilityChange))):null!=g.field(window,"attachEvent")?(window.attachEvent("onfocus",d(this,this._focus)),window.attachEvent("onblur",d(this,this._blur)),window.attachEvent("pageshow",d(this,this._focus)),window.attachEvent("pagehide",d(this,this._blur)),document.attachEvent(this._visibilityChange,d(this,this._handleVisibilityChange))):window.onload=function(){window.onfocus= d(a,a._focus);window.onblur=d(a,a._blur);window.onpageshow=d(a,a._focus);window.onpagehide=d(a,a._blur)}};l.__name__=!0;l.prototype={_handleVisibilityChange:function(){null!=g.field(window.document,this._hidden)&&g.field(window.document,this._hidden)&&null!=this.blur?this.blur():null!=this.focus&&this.focus()},_focus:function(){"focus"!=this._currentState&&null!=this.focus&&this.focus();this._currentState="focus"},_blur:function(){"blur"!=this._currentState&&null!=this.blur&&this.blur();this._currentState= "blur"},clearEvents:function(){null!=g.field(window,"removeEventListener")?(window.removeEventListener("focus",d(this,this._focus)),window.removeEventListener("blur",d(this,this._blur)),window.removeEventListener("pageshow",d(this,this._focus)),window.removeEventListener("pagehide",d(this,this._blur)),window.removeEventListener(this._visibilityChange,d(this,this._handleVisibilityChange))):null!=g.field(window,"removeEvent")?(window.removeEvent("onfocus",d(this,this._focus)),window.removeEvent("onblur", d(this,this._blur)),window.removeEvent("pageshow",d(this,this._focus)),window.removeEvent("pagehide",d(this,this._blur)),window.removeEvent(this._visibilityChange,d(this,this._handleVisibilityChange))):(window.onfocus=null,window.onblur=null,window.onpageshow=null,window.onpagehide=null)},__class__:l};var A=t.WaudSound=function(a,b){if(null!=c.audioManager)if(this.rate=1,this._options=b,0<a.indexOf(".json")?(this.isSpriteSound=!0,this._spriteDuration=0,this._spriteSounds=new p,this._spriteSoundEndCallbacks= new p,this._loadSpriteJson(a)):(this.isSpriteSound=!1,this._init(a)),(new k("(^data:audio).*(;base64,)","i")).match(a)){var e="snd"+(new Date).getTime();c.sounds.set(e,this)}else c.sounds.set(a,this)};A.__name__=!0;A.__interfaces__=[w];A.prototype={_loadSpriteJson:function(a){var b=this,c=new XMLHttpRequest;c.open("GET",a,!0);c.onreadystatechange=function(){if(4==c.readyState&&200==c.status){b._spriteData=JSON.parse(c.responseText);var f=b._spriteData.src;-1<a.indexOf("/")&&(f=a.substring(0,a.lastIndexOf("/")+ 1)+f);b._init(f)}};c.send(null)},_init:function(a){this.url=a;if(c.isWebAudioSupported&&c.useWebAudio&&(null==this._options||null==this._options.webaudio||this._options.webaudio))this.isSpriteSound?this._loadSpriteSound(this.url):this._snd=new y(this.url,this._options);else if(c.isHTML5AudioSupported)if(null!=this._spriteData&&null!=this._spriteData.sprite){a=0;for(var b=this._spriteData.sprite;a<b.length;){var e=b[a];++a;var f=new x(this.url,this._options);f.isSpriteSound=!0;this._spriteSounds.set(e.name, f)}}else this._snd=new x(this.url,this._options)},getDuration:function(){return this.isSpriteSound?this._spriteDuration:null==this._snd?0:this._snd.getDuration()},setVolume:function(a,b){this.isSpriteSound?null!=b&&null!=this._spriteSounds.get(b)&&this._spriteSounds.get(b).setVolume(a):null!=this._snd&&this._snd.setVolume(a)},getVolume:function(a){return this.isSpriteSound?null!=a&&null!=this._spriteSounds.get(a)?this._spriteSounds.get(a).getVolume():0:null==this._snd?0:this._snd.getVolume()},mute:function(a, b){if(this.isSpriteSound)if(null!=b&&null!=this._spriteSounds.get(b))this._spriteSounds.get(b).mute(a);else for(var c=this._spriteSounds.iterator();c.hasNext();)c.next().mute(a);else null!=this._snd&&this._snd.mute(a)},toggleMute:function(a){if(this.isSpriteSound)if(null!=a&&null!=this._spriteSounds.get(a))this._spriteSounds.get(a).toggleMute();else for(a=this._spriteSounds.iterator();a.hasNext();)a.next().toggleMute();else null!=this._snd&&this._snd.toggleMute()},load:function(a){if(null==this._snd|| this.isSpriteSound)return null;this._snd.load(a);return this},isReady:function(){if(this.isSpriteSound)for(var a=this._spriteSounds.iterator();a.hasNext();)return a.next().isReady();return this._snd.isReady()},play:function(a,b){if(this.isSpriteSound)if(null!=a){for(var c=0,f=this._spriteData.sprite;c<f.length;){var d=f[c];++c;if(d.name==a){b=d;break}}if(null==b)return null;if(null!=this._spriteSounds.get(a))return this._spriteSounds.get(a).stop(),this._spriteSounds.get(a).play(a,b)}else return null; return null==this._snd?null:this._snd.play(a,b)},togglePlay:function(a){this.isSpriteSound?null!=a&&null!=this._spriteSounds.get(a)&&this._spriteSounds.get(a).togglePlay():null!=this._snd&&this._snd.togglePlay()},isPlaying:function(a){return this.isSpriteSound?null!=a&&null!=this._spriteSounds.get(a)?this._spriteSounds.get(a).isPlaying():!1:null==this._snd?!1:this._snd.isPlaying()},loop:function(a){null==this._snd||this.isSpriteSound||this._snd.loop(a)},autoStop:function(a){null!=this._snd&&this._snd.autoStop(a)}, stop:function(a){if(this.isSpriteSound)if(null!=a&&null!=this._spriteSounds.get(a))this._spriteSounds.get(a).stop();else for(a=this._spriteSounds.iterator();a.hasNext();)a.next().stop();else null!=this._snd&&this._snd.stop()},pause:function(a){if(this.isSpriteSound)if(null!=a&&null!=this._spriteSounds.get(a))this._spriteSounds.get(a).pause();else for(a=this._spriteSounds.iterator();a.hasNext();)a.next().pause();else null!=this._snd&&this._snd.pause()},playbackRate:function(a,b){if(null!=a){if(this.isSpriteSound)if(null!= b&&null!=this._spriteSounds.get(b))this._spriteSounds.get(b).playbackRate(a);else for(var c=this._spriteSounds.iterator();c.hasNext();)c.next().playbackRate(a);else null!=this._snd&&this._snd.playbackRate(a);return this.rate=a}return this.rate},setTime:function(a){null==this._snd||this.isSpriteSound||this._snd.setTime(a)},getTime:function(){return null==this._snd||this.isSpriteSound?0:this._snd.getTime()},onEnd:function(a,b){return this.isSpriteSound?(null!=b&&this._spriteSoundEndCallbacks.set(b, a),this):null!=this._snd?(this._snd.onEnd(a),this):null},onLoad:function(a){if(null==this._snd||this.isSpriteSound)return null;this._snd.onLoad(a);return this},onError:function(a){if(null==this._snd||this.isSpriteSound)return null;this._snd.onError(a);return this},destroy:function(){if(this.isSpriteSound)for(var a=this._spriteSounds.iterator();a.hasNext();)a.next().destroy();else null!=this._snd&&(this._snd.destroy(),this._snd=null)},_loadSpriteSound:function(a){var b=new XMLHttpRequest;b.open("GET", a,!0);b.responseType="arraybuffer";b.onload=d(this,this._onSpriteSoundLoaded);b.onerror=d(this,this._onSpriteSoundError);b.send()},_onSpriteSoundLoaded:function(a){c.audioManager.audioContext.decodeAudioData(a.target.response,d(this,this._decodeSuccess),d(this,this._onSpriteSoundError))},_onSpriteSoundError:function(){if(null!=this._options&&null!=this._options.onerror)this._options.onerror(this)},_decodeSuccess:function(a){if(null==a)this._onSpriteSoundError();else{c.audioManager.bufferList.set(this.url, a);this._spriteDuration=a.duration;if(null!=this._options&&null!=this._options.onload)this._options.onload(this);for(var b=0,e=this._spriteData.sprite;b<e.length;){var f=e[b];++b;var g=new y(this.url,this._options,!0,a.duration);g.isSpriteSound=!0;this._spriteSounds.set(f.name,g);g.onEnd(d(this,this._spriteOnEnd),f.name)}}},_spriteOnEnd:function(a){null!=this._spriteSoundEndCallbacks.get(a.spriteName)&&this._spriteSoundEndCallbacks.get(a.spriteName)(a)},__class__:A};var n=t.WaudUtils=function(){}; n.__name__=!0;n.isAndroid=function(a){null==a&&(a=window.navigator.userAgent);return(new k("Android","i")).match(a)};n.isiOS=function(a){null==a&&(a=window.navigator.userAgent);return(new k("(iPad|iPhone|iPod)","i")).match(a)};n.isWindowsPhone=function(a){null==a&&(a=window.navigator.userAgent);return(new k("(IEMobile|Windows Phone)","i")).match(a)};n.isFirefox=function(a){null==a&&(a=window.navigator.userAgent);return(new k("Firefox","i")).match(a)};n.isOpera=function(a){null==a&&(a=window.navigator.userAgent); return(new k("Opera","i")).match(a)||null!=g.field(window,"opera")};n.isChrome=function(a){null==a&&(a=window.navigator.userAgent);return(new k("Chrome","i")).match(a)};n.isSafari=function(a){null==a&&(a=window.navigator.userAgent);return(new k("Safari","i")).match(a)};n.isMobile=function(a){null==a&&(a=window.navigator.userAgent);return(new k("(iPad|iPhone|iPod|Android|webOS|BlackBerry|Windows Phone|IEMobile)","i")).match(a)};n.getiOSVersion=function(a){null==a&&(a=window.navigator.userAgent);var b= new k("[0-9_]+?[0-9_]+?[0-9_]+","i"),c=[];if(b.match(a)){a=b.matched(0).split("_");b=[];for(c=0;c<a.length;){var f=a[c];++c;b.push(v.parseInt(f))}c=b}return c};var y=function(a,b,e,f){null==f&&(f=0);null==e&&(e=!1);r.call(this,a,b);this._pauseTime=this._playStartTime=0;this._srcNodes=[];this._gainNodes=[];this._currentSoundProps=null;this._isLoaded=e;this._duration=f;this._manager=c.audioManager;this._b64.match(a)?this._decodeAudio(this._base64ToArrayBuffer(a)):this._options.preload&&!e&&this.load()}; y.__name__=!0;y.__interfaces__=[w];y.__super__=r;y.prototype=D(r.prototype,{load:function(a){if(!this._isLoaded){var b=new XMLHttpRequest;b.open("GET",this.url,!0);b.responseType="arraybuffer";b.onload=d(this,this._onSoundLoaded);b.onerror=d(this,this._error);b.send();null!=a&&(this._options.onload=a)}return this},_base64ToArrayBuffer:function(a){a=window.atob(a.split(",")[1]);for(var b=a.length,c=new Uint8Array(new ArrayBuffer(b)),f=0;f<b;){var d=f++;c[d]=u.cca(a,d)}return c.buffer},_onSoundLoaded:function(a){this._manager.audioContext.decodeAudioData(a.target.response, d(this,this._decodeSuccess),d(this,this._error))},_decodeAudio:function(a){this._manager.audioContext.decodeAudioData(a,d(this,this._decodeSuccess),d(this,this._error))},_error:function(){if(null!=this._options.onerror)this._options.onerror(this)},_decodeSuccess:function(a){if(null==a)this._error();else{this._manager.bufferList.set(this.url,a);this._isLoaded=!0;this._duration=a.duration;if(null!=this._options.onload)this._options.onload(this);this._options.autoplay&&this.play()}},_makeSource:function(a){var b= this._manager.audioContext.createBufferSource();b.buffer=a;this._gainNode=null!=this._manager.audioContext.createGain?this._manager.audioContext.createGain():this._manager.audioContext.createGainNode();b.connect(this._gainNode);b.playbackRate.value=this.rate;this._gainNode.connect(this._manager.audioContext.destination);this._srcNodes.push(b);this._gainNodes.push(this._gainNode);this._gainNode.gain.value=this._muted?0:this._options.volume;return b},getDuration:function(){return this._isLoaded?this._duration: 0},play:function(a,b){var c=this;this.spriteName=a;this._isPlaying&&this._options.autostop&&this.stop(this.spriteName);if(!this._isLoaded)return-1;var f=0,d=-1;this.isSpriteSound&&null!=b&&(this._currentSoundProps=b,f=b.start+this._pauseTime,d=b.duration);var h=this._manager.bufferList.get(this.url);null!=h&&(this.source=this._makeSource(h),0<=f&&-1<d?null!=g.field(this.source,"start")?this.source.start(0,f,d):this._snd.noteGrainOn(0,f,d):(null!=g.field(this.source,"start")?this.source.start(0,this._pauseTime, this.source.buffer.duration):this._snd.noteGrainOn(0,this._pauseTime,this.source.buffer.duration),this.source.loop=this._options.loop),this._playStartTime=this._manager.audioContext.currentTime,this._isPlaying=!0,this.source.onended=function(){c._pauseTime=0;c._isPlaying=!1;if(c.isSpriteSound&&null!=b&&null!=b.loop&&b.loop&&0<=f&&-1<d)c.destroy(),c.play(c.spriteName,b);else if(null!=c._options.onend)c._options.onend(c)});return u.indexOf(this._srcNodes,this.source,0)},togglePlay:function(a){this._isPlaying? this.pause():this.play()},isPlaying:function(a){return this._isPlaying},loop:function(a){this._options.loop=a;null!=this.source&&(this.source.loop=a)},setVolume:function(a,b){this._options.volume=a;null!=this._gainNode&&this._isLoaded&&(this._gainNode.gain.value=this._options.volume)},getVolume:function(a){return this._options.volume},mute:function(a,b){this._muted=a;null!=this._gainNode&&this._isLoaded&&(this._gainNode.gain.value=a?0:this._options.volume)},toggleMute:function(a){this.mute(!this._muted)}, autoStop:function(a){this._options.autostop=a},stop:function(a){this._pauseTime=0;null!=this.source&&this._isLoaded&&this._isPlaying&&this.destroy()},pause:function(a){null!=this.source&&this._isLoaded&&this._isPlaying&&(this.destroy(),this._pauseTime+=this._manager.audioContext.currentTime-this._playStartTime)},playbackRate:function(a,b){if(null==a)return this.rate;for(var c=0,f=this._srcNodes;c<f.length;){var d=f[c];++c;d.playbackRate.value=a}return this.rate=a},setTime:function(a){!this._isLoaded|| a>this._duration||(this._isPlaying?(this.stop(),this._pauseTime=a,this.play()):this._pauseTime=a)},getTime:function(){return null!=this.source&&this._isLoaded&&this._isPlaying?this._manager.audioContext.currentTime-this._playStartTime+this._pauseTime:0},onEnd:function(a,b){this._options.onend=a;return this},onLoad:function(a){this._options.onload=a;return this},onError:function(a){this._options.onerror=a;return this},destroy:function(){for(var a=0,b=this._srcNodes;a<b.length;){var c=b[a];++a;if(null!= g.field(c,"stop"))c.stop(0);else if(null!=g.field(c,"noteOff"))try{this.src.noteOff(0)}catch(f){f instanceof m&&(f=f.val)}c.disconnect()}a=0;for(b=this._gainNodes;a<b.length;)c=b[a],++a,c.disconnect();this._srcNodes=[];this._gainNodes=[];this._isPlaying=!1},__class__:y});t=function(){};t.__name__=!0;var q=function(a){var b=this;this.id=setInterval(function(){b.run()},a)};q.__name__=!0;q.delay=function(a,b){var c=new q(b);c.run=function(){c.stop();a()};return c};q.prototype={stop:function(){null!= this.id&&(clearInterval(this.id),this.id=null)},run:function(){},__class__:q};var C=function(a,b){this.map=a;this.keys=b;this.index=0;this.count=b.length};C.__name__=!0;C.prototype={hasNext:function(){return this.index<this.count},next:function(){return this.map.get(this.keys[this.index++])},__class__:C};var p=function(){this.h={}};p.__name__=!0;p.__interfaces__=[t];p.prototype={set:function(a,b){null!=G[a]?this.setReserved(a,b):this.h[a]=b},get:function(a){return null!=G[a]?this.getReserved(a):this.h[a]}, setReserved:function(a,b){null==this.rh&&(this.rh={});this.rh["$"+a]=b},getReserved:function(a){return null==this.rh?null:this.rh["$"+a]},arrayKeys:function(){var a=[],b;for(b in this.h)this.h.hasOwnProperty(b)&&a.push(b);if(null!=this.rh)for(b in this.rh)36==b.charCodeAt(0)&&a.push(b.substr(1));return a},iterator:function(){return new C(this,this.arrayKeys())},__class__:p};var m=function(a){Error.call(this);this.val=a;this.message=String(a);Error.captureStackTrace&&Error.captureStackTrace(this,m)}; m.__name__=!0;m.__super__=Error;m.prototype=D(Error.prototype,{__class__:m});var h=function(){};h.__name__=!0;h.getClass=function(a){if(a instanceof Array&&null==a.__enum__)return Array;var b=a.__class__;if(null!=b)return b;a=h.__nativeClassName(a);return null!=a?h.__resolveNativeClass(a):null};h.__string_rec=function(a,b){if(null==a)return"null";if(5<=b.length)return"<...>";var c=typeof a;"function"==c&&(a.__name__||a.__ename__)&&(c="object");switch(c){case "object":if(a instanceof Array){if(a.__enum__){if(2== a.length)return a[0];c=a[0]+"(";b+="\t";for(var f=2,d=a.length;f<d;)var g=f++,c=2!=g?c+(","+h.__string_rec(a[g],b)):c+h.__string_rec(a[g],b);return c+")"}c=a.length;f="[";b+="\t";for(d=0;d<c;)g=d++,f+=(0<g?",":"")+h.__string_rec(a[g],b);return f+"]"}try{f=a.toString}catch(k){return k instanceof m&&(k=k.val),"???"}if(null!=f&&f!=Object.toString&&"function"==typeof f&&(c=a.toString(),"[object Object]"!=c))return c;c=null;f="{\n";b+="\t";d=null!=a.hasOwnProperty;for(c in a)d&&!a.hasOwnProperty(c)||"prototype"== c||"__class__"==c||"__super__"==c||"__interfaces__"==c||"__properties__"==c||(2!=f.length&&(f+=", \n"),f+=b+c+" : "+h.__string_rec(a[c],b));b=b.substring(1);return f+("\n"+b+"}");case "function":return"<function>";case "string":return a;default:return String(a)}};h.__interfLoop=function(a,b){if(null==a)return!1;if(a==b)return!0;var c=a.__interfaces__;if(null!=c)for(var d=0,g=c.length;d<g;){var k=d++,k=c[k];if(k==b||h.__interfLoop(k,b))return!0}return h.__interfLoop(a.__super__,b)};h.__instanceof= function(a,b){if(null==b)return!1;switch(b){case L:return(a|0)===a;case H:return"number"==typeof a;case I:return"boolean"==typeof a;case String:return"string"==typeof a;case Array:return a instanceof Array&&null==a.__enum__;case M:return!0;default:if(null!=a)if("function"==typeof b){if(a instanceof b||h.__interfLoop(h.getClass(a),b))return!0}else{if("object"==typeof b&&h.__isNativeObj(b)&&a instanceof b)return!0}else return!1;return b==N&&null!=a.__name__||b==O&&null!=a.__ename__?!0:a.__enum__==b}}; h.__cast=function(a,b){if(h.__instanceof(a,b))return a;throw new m("Cannot cast "+v.string(a)+" to "+v.string(b));};h.__nativeClassName=function(a){a=h.__toStr.call(a).slice(8,-1);return"Object"==a||"Function"==a||"Math"==a||"JSON"==a?null:a};h.__isNativeObj=function(a){return null!=h.__nativeClassName(a)};h.__resolveNativeClass=function(a){return J[a]};var z,K=0;Array.prototype.indexOf&&(u.indexOf=function(a,b,c){return Array.prototype.indexOf.call(a,b,c)});String.prototype.__class__=String;String.__name__= !0;Array.__name__=!0;Date.prototype.__class__=Date;Date.__name__=["Date"];var L={__name__:["Int"]},M={__name__:["Dynamic"]},H=Number;H.__name__=["Float"];var I=Boolean;I.__ename__=["Bool"];var N={__name__:["Class"]},O={},G={};c.PROBABLY="probably";c.MAYBE="maybe";c.version="0.7.7";c.useWebAudio=!0;c.defaults={autoplay:!1,autostop:!0,loop:!1,preload:!0,webaudio:!0,volume:1};c.preferredSampleRate=44100;c.isMuted=!1;c._playbackRate=1;l.FOCUS_STATE="focus";l.BLUR_STATE="blur";l.ON_FOCUS="onfocus";l.ON_BLUR= "onblur";l.PAGE_SHOW="pageshow";l.PAGE_HIDE="pagehide";l.WINDOW="window";l.DOCUMENT="document";h.__toStr={}.toString})("undefined"!=typeof console?console:{log:function(){}},"undefined"!=typeof window?window:exports,"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this);
var Plates = (typeof process !== 'undefined' && typeof process.title !== 'undefined') ? exports : {}; !function(exports) { var _toString = Object.prototype.toString, isArray = Array.isArray || function (o) { return _toString.call(o) === "[object Array]"; }; var Merge = function Merge() {}; Merge.prototype = { nest: [], tag: new RegExp([ '<', '(/?)', // 2 - is closing '([-:\\w]+)', // 3 - name '((?:[-\\w]+(?:', '=', '(?:\\w+|["|\'](?:.*)["|\']))?)*)', // 4 - attributes '(/?)', // 5 - is self-closing '>' ].join('\\s*')), attr: /([\-\w]*)=(?:["\']([\-\.\w\s\/:;&#]*)["\'])/gi, hasClass: function(str, className) { return str.split(' ').indexOf(className) > -1; }, iterate: function(html, value, components, tagname, key) { var output = '', segment = html.slice( html.search(components.input), html.lastIndexOf(tagname) + tagname.length + 1 ), data = {}; // Is it an array? if (isArray(value)) { // Yes: set the output to the result of iterating through the array for (var i = 0, l = value.length; i < l; i++) { // If there is a key, then we have a simple object and // must construct a simple object to use as the data if (key) { data[key] = value[i]; } else { data = value[i]; } output += this.bind(segment, data); } return output; } // Is it an object? else if (typeof value === 'object') { // We need to refine the selection now that we know we're dealing with a // nested object segment = segment.slice(components.input.length, -(tagname.length + 3)); return output += this.bind(segment, value); } return value; }, bind: function bind(html, data, map) { if (isArray(data)) { var output = ''; for (var i = 0, l = data.length; i<l; i++) { output += this.bind(html, data[i], map); } return output; } html = html || ''; data = data || {}; var that = this; var openers = 0, components, attributes, mappings = map && map.mappings, intag = false, tagname = '', isClosing = false, isSelfClosing = false, matchmode = false, createAttribute = map && map.conf && map.conf.create, closing, tagbody; var c, buffer = '', left; for (var i = 0, l = html.length; i < l; i++) { c = html[i]; if (c === '!' && intag && !matchmode) { intag = false; buffer += html.slice(left, i+1); } else if (c === '<' && !intag) { closing = true; intag = true; left = i; } else if (c === '>' && intag) { intag = false; tagbody = html.slice(left, i+1); components = this.tag.exec(tagbody); if(!components) { intag = true; continue; } isClosing = components[1]; tagname = components[2]; attributes = components[3]; isSelfClosing = components[4]; if (matchmode) { // // and its a closing. // if (!!isClosing) { if (openers <= 0) { matchmode = false; } else { --openers; } } // // and its not a self-closing tag // else if (!isSelfClosing) { ++openers; } } if (!isClosing && !matchmode) { // // if there is a match in progress and // if (mappings && mappings.length > 0) { for (var ii = mappings.length - 1; ii >= 0; ii--) { var setAttribute = false , shouldSetAttribute = mappings[ii].re && attributes.match(mappings[ii].re); tagbody = tagbody.replace(this.attr, function(str, key, value, a) { var newdata = mappings[ii].dataKey ? data[mappings[ii].dataKey] : data[key]; if (shouldSetAttribute && mappings[ii].replace !== key) { return str; } else if (shouldSetAttribute || typeof mappings[ii].replacePartial1 !== 'undefined') { setAttribute = true; // // determine if we should use the replace argument or some value from the data object. // if (typeof mappings[ii].replacePartial2 !== 'undefined') { newdata = value.replace(mappings[ii].replacePartial1, mappings[ii].replacePartial2); } else if (typeof mappings[ii].replacePartial1 !== 'undefined' && mappings[ii].dataKey) { newdata = value.replace(mappings[ii].replacePartial1, data[mappings[ii].dataKey]); } return key + '="' + (newdata || '') + '"'; } else if (!mappings[ii].replace && mappings[ii].attribute === key) { if ( mappings[ii].value === value || that.hasClass(value, mappings[ii].value || mappings.conf.where === key) || ( ({}).toString.call(mappings[ii].value) === '[object RegExp]' && mappings[ii].value.exec(value) !== null) ) { var v = data[mappings[ii].dataKey]; newdata = tagbody + newdata; if (isArray(v)) { newdata = that.iterate(html, v, components, tagname, value); // If the item is an array, then we need to tell // Plates that we're dealing with nests that.nest.push(tagname); } else if (typeof v === 'object') { newdata = tagbody + that.iterate(html, v, components, tagname, value); } buffer += newdata || ''; matchmode = true; } } return str; }); if (createAttribute && shouldSetAttribute && !setAttribute) { var spliced = isSelfClosing? 2 : 1; var close = isSelfClosing? '/>': '>'; var left = tagbody.substr(0, tagbody.length - spliced); if (left[left.length - 1] == ' ') { left = left.substr(0, left.length - 1); if (isSelfClosing) { close = ' ' + close; } } tagbody = [ left, ' ', mappings[ii].replace, '="', data[mappings[ii].dataKey], '"', close ].join(''); } } } else { // // if there is no map, we are just looking to match // the specified id to a data key in the data object. // tagbody.replace( this.attr, function (attr, key, value, idx) { if (key === map && map.conf.where || 'id' && data[value]) { var v = data[value], nest = isArray(v), output = (nest || typeof v === 'object') ? that.iterate(html, v, components, tagname, value) : v; // If the item is an array, then we need to tell // Plates that we're dealing with nests if (nest) { that.nest.push(tagname); } buffer += nest ? output : tagbody + output; matchmode = true; } } ); } } // // if there is currently no match in progress // just write the tagbody to the buffer. // if (!matchmode && that.nest.length === 0) { buffer += tagbody; } else if (!matchmode && that.nest.length) { this.nest.pop(); } } else if (!intag && !matchmode) { // // currently not inside a tag and there is no // match in progress, we can write the char to // the buffer. // buffer += c; } } return buffer; } }; var Mapper = function Mapper(conf) { if (!(this instanceof Mapper)) { return new Mapper(conf); } this.mappings = []; this.conf = conf || {}; }; function last(newitem) { if (newitem) { this.mappings.push({}); } var m = this.mappings[this.mappings.length-1]; if (m && m.attribute && m.value && m.dataKey && m.replace) { m.re = new RegExp(m.attribute + '=([\'"]?)' + m.value + '\\1'); } else { delete m && m.re; } return m; } Mapper.prototype = { replace: function(val1, val2) { var l = last.call(this); l.replacePartial1 = val1; l.replacePartial2 = val2; return this; }, use: function(val) { last.call(this).dataKey = val; return last.call(this) && this; }, to: function(val) { return this.use(val); }, where: function(val) { last.call(this, true).attribute = val; return last.call(this) && this; }, class: function(val) { return this.where('class').is(val); }, tag: function(val) { last.call(this, true).tag = val; return this; }, is: function(val) { last.call(this).value = val; return last.call(this) && this; }, has: function(val) { last.call(this).value = val; this.replace(val); return last.call(this) && this; }, insert: function(val) { var l = last.call(this); l.replace = l.attribute; l.dataKey = val; return last.call(this) && this; }, as: function(val) { last.call(this).replace = val; return last.call(this) && this; } }; // where('class').is('foo').insert('bla') exports.bind = function (html, data, map) { var merge = new Merge(); return merge.bind(html, data, map); }; exports.Map = Mapper; }(Plates);
!function(a){a.fn.datepicker.dates.it={days:["Domenica","Lunedì","Martedì","Mercoledì","Giovedì","Venerdì","Sabato"],daysShort:["Dom","Lun","Mar","Mer","Gio","Ven","Sab"],daysMin:["Do","Lu","Ma","Me","Gi","Ve","Sa"],months:["Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"],monthsShort:["Gen","Feb","Mar","Apr","Mag","Giu","Lug","Ago","Set","Ott","Nov","Dic"],today:"Oggi",clear:"Cancella",weekStart:1,format:"dd/mm/yyyy"}}(jQuery);
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v5.0.2 * @link http://www.ag-grid.com/ * @license MIT */ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var context_1 = require("../../context/context"); var gridOptionsWrapper_1 = require("../../gridOptionsWrapper"); var sortController_1 = require("../../sortController"); var valueService_1 = require("../../valueService"); var utils_1 = require("../../utils"); var SortStage = (function () { function SortStage() { } SortStage.prototype.execute = function (rowNode) { var sortOptions; // if the sorting is already done by the server, then we should not do it here if (!this.gridOptionsWrapper.isEnableServerSideSorting()) { sortOptions = this.sortController.getSortForRowController(); } this.sortRowNode(rowNode, sortOptions); }; SortStage.prototype.sortRowNode = function (rowNode, sortOptions) { var _this = this; // sort any groups recursively rowNode.childrenAfterFilter.forEach(function (child) { if (child.group) { _this.sortRowNode(child, sortOptions); } }); rowNode.childrenAfterSort = rowNode.childrenAfterFilter.slice(0); var sortActive = utils_1.Utils.exists(sortOptions) && sortOptions.length > 0; if (sortActive) { rowNode.childrenAfterSort.sort(this.compareRowNodes.bind(this, sortOptions)); } this.updateChildIndexes(rowNode); }; SortStage.prototype.compareRowNodes = function (sortOptions, nodeA, nodeB) { // Iterate columns, return the first that doesn't match for (var i = 0, len = sortOptions.length; i < len; i++) { var sortOption = sortOptions[i]; // var compared = compare(nodeA, nodeB, sortOption.column, sortOption.inverter === -1); var isInverted = sortOption.inverter === -1; var valueA = this.valueService.getValue(sortOption.column, nodeA); var valueB = this.valueService.getValue(sortOption.column, nodeB); var comparatorResult; if (sortOption.column.getColDef().comparator) { //if comparator provided, use it comparatorResult = sortOption.column.getColDef().comparator(valueA, valueB, nodeA, nodeB, isInverted); } else { //otherwise do our own comparison comparatorResult = utils_1.Utils.defaultComparator(valueA, valueB); } if (comparatorResult !== 0) { return comparatorResult * sortOption.inverter; } } // All matched, these are identical as far as the sort is concerned: return 0; }; SortStage.prototype.updateChildIndexes = function (rowNode) { if (utils_1.Utils.missing(rowNode.childrenAfterSort)) { return; } rowNode.childrenAfterSort.forEach(function (child, index) { child.firstChild = index === 0; child.lastChild = index === rowNode.childrenAfterSort.length - 1; child.childIndex = index; }); }; __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper) ], SortStage.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('sortController'), __metadata('design:type', sortController_1.SortController) ], SortStage.prototype, "sortController", void 0); __decorate([ context_1.Autowired('valueService'), __metadata('design:type', valueService_1.ValueService) ], SortStage.prototype, "valueService", void 0); SortStage = __decorate([ context_1.Bean('sortStage'), __metadata('design:paramtypes', []) ], SortStage); return SortStage; })(); exports.SortStage = SortStage;
(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'), CollectionGroup = _dereq_('../lib/CollectionGroup'), View = _dereq_('../lib/View'), Highchart = _dereq_('../lib/Highchart'), Persist = _dereq_('../lib/Persist'), Document = _dereq_('../lib/Document'), Overview = _dereq_('../lib/Overview'), Grid = _dereq_('../lib/Grid'), NodeApiClient = _dereq_('../lib/NodeApiClient'), BinaryLog = _dereq_('../lib/BinaryLog'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/BinaryLog":4,"../lib/CollectionGroup":8,"../lib/Document":12,"../lib/Grid":14,"../lib/Highchart":15,"../lib/NodeApiClient":31,"../lib/Overview":34,"../lib/Persist":36,"../lib/View":43,"./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":10,"../lib/Shim.IE8":42}],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":35,"./Shared":41}],4:[function(_dereq_,module,exports){ "use strict"; var Shared, ReactorIO, Collection, CollectionInit, Db, DbInit, BinaryLog; Shared = _dereq_('./Shared'); BinaryLog = function () { this.init.apply(this, arguments); }; BinaryLog.prototype.init = function (parent) { var self = this; self._logCounter = 0; self._parent = parent; self.size(1000); }; Shared.addModule('BinaryLog', BinaryLog); Shared.mixin(BinaryLog.prototype, 'Mixin.Common'); Shared.mixin(BinaryLog.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryLog.prototype, 'Mixin.Events'); Collection = Shared.modules.Collection; Db = Shared.modules.Db; ReactorIO = Shared.modules.ReactorIO; CollectionInit = Collection.prototype.init; DbInit = Db.prototype.init; Shared.synthesize(BinaryLog.prototype, 'name'); Shared.synthesize(BinaryLog.prototype, 'size'); BinaryLog.prototype.attachIO = function () { var self = this; if (!self._io) { self._log = new Collection(self._parent.name() + '-BinaryLog', {capped: true, size: self.size()}); // Override the log collection's id generator so it is linear self._log.objectId = function (id) { if (!id) { id = ++self._logCounter; } return id; }; self._io = new ReactorIO(self._parent, self, function (chainPacket) { self._log.insert({ type: chainPacket.type, data: chainPacket.data }); // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; }); } }; BinaryLog.prototype.detachIO = function () { var self = this; if (self._io) { self._log.drop(); self._io.drop(); delete self._log; delete self._io; } }; Collection.prototype.init = function () { CollectionInit.apply(this, arguments); this._binaryLog = new BinaryLog(this); }; Shared.finishModule('BinaryLog'); module.exports = BinaryLog; },{"./Shared":41}],5:[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 {Object} data The data / document to use for lookups. * @param {Object} options An options object. * @param {Operation} op An optional operation instance. Pass undefined * if not being used. * @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, op, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, op, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, op, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, op, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, op, 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._visitedCount === undefined) { resultArr._visitedCount = 0; } resultArr._visitedCount++; resultArr._visitedNodes = resultArr._visitedNodes || []; resultArr._visitedNodes.push(thisDataPathVal); result = this.sortAsc(thisDataPathValSubStr, 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":35,"./Shared":41}],6:[function(_dereq_,module,exports){ "use strict"; var crcTable, checksum; crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); /** * Returns a checksum of a string. * @param {String} str The string to checksum. * @return {Number} The checksum generated. */ checksum = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; module.exports = checksum; },{}],7:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Overload, ReactorIO, Condition, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this.sharedPathSolver = sharedPathSolver; this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); Condition = _dereq_('./Condition'); sharedPathSolver = new Path(); /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. * @param {Object=} val The data to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. * @param {Boolean=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. * @param {Number=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'cappedSize'); /** * Adds a job id to the async queue to signal to other parts * of the application that some async work is currently being * done. * @param {String} key The id of the async job. * @private */ Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; /** * Removes a job id from the async queue to signal to other * parts of the application that some async work has been * completed. If no further async jobs exist on the queue then * the "ready" event is emitted from this collection instance. * @param {String} key The id of the async job. * @private */ 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. * @param {Function=} callback A callback method to call once the * operation has completed. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback.call(this, false, true); } return true; } } else { if (callback) { callback.call(this, false, true); } return true; } if (callback) { callback.call(this, false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', { keyName: keyName, oldData: oldKey }); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection by updating the * lastChange timestamp on the collection's metaData. This * only happens if the changeTimestamp option is enabled * on the collection (it is disabled by default). * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = this.serialiser.convert(new Date()); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); Collection.prototype.setData = new Overload('Collection.prototype.setData', { /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. */ '*': function (data) { return this.$main.call(this, data, {}); }, /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. */ '*, object': function (data, options) { return this.$main.call(this, data, options); }, /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Function} callback Optional callback function. */ '*, function': function (data, callback) { return this.$main.call(this, data, {}, callback); }, /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @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 {Function} callback Optional callback function. */ '*, *, function': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @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. */ '*, *, *': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. * @param {Function} callback Optional callback function. */ '$main': function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var deferredSetting = this.deferredCalls(), oldData = [].concat(this._data); // Switch off deferred calls since setData should be // a synchronous call this.deferredCalls(false); options = this.options(options); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } // Remove all items from the collection this.remove({}); // Insert the new data this.insert(data); // Switch deferred calls back to previous settings this.deferredCalls(deferredSetting); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback.call(this); } return this; } }); /** * Drops and rebuilds the primary key index for all documents * in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a hash string jString = this.hash(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This should use remove so that chain reactor events are properly // TODO: handled, but ensure that chunking is switched off this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.emit('immediateChange', {type: 'truncate'}); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Inserts a new document or updates an existing document in a * collection depending on if a matching primary key exists in * the collection already or not. * * 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 * document and the document is inserted. * * @param {Object} obj The document object to upsert or an array * containing documents to upsert. * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains * either "insert" or "update" depending on the type of operation * that was performed and "result" contains the return data from * the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback.call(this); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj, callback); break; case 'update': returnData.result = this.update(query, obj, {}, callback); break; default: break; } return returnData; } else { if (callback) { callback.call(this); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. * This will update all matches for 'query' with the data held * in 'update'. It will not overwrite the matched documents * with the update document. * * @param {Object} query The query that must be matched for a * document to be operated on. * @param {Object} update The object containing updated * key/values. Any keys that match keys on the existing document * will be overwritten with this data. Any keys that do not * currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } else { // Decouple the update data update = this.decouple(update); } // Handle transform update = this.transformIn(update); return this._handleUpdate(query, update, options, callback); }; /** * Handles the update operation that was initiated by a call to update(). * @param {Object} query The query that must be matched for a * document to be operated on. * @param {Object} update The object containing updated * key/values. Any keys that match keys on the existing document * will be overwritten with this data. Any keys that do not * currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. * @private */ Collection.prototype._handleUpdate = function (query, update, options, callback) { var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); if (this.chainWillSend()) { this.chainSend('update', { query: query, update: update, dataSet: this.decouple(updated) }, options); } op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); if (callback) { callback.call(this); } this.emit('immediateChange', {type: 'update', data: updated}); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. It does this by removing existing keys * from the base object and then adding the passed object's keys to * the existing base object, thereby maintaining any references to * the existing base object but effectively replacing the object with * the new one. * @param {Object} currentObj The base 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 via it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to * update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update * the document with. * @param {Object} query The query object that we need to match to * perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, * if none is specified default is to set new data against matching * fields. * @returns {Boolean} True if the document was updated with new / * changed data or false if it was not updated because the data was * the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark * (a dollar at the end of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search * query key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback.call(this, false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.emit('immediateChange', {type: 'remove', data: returnArr}); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback.call(this, false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback.call(this, resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Collection~insertCallback=} callback Optional callback called * once the insert is complete. */ 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); }; /** * The insert operation's callback. * @callback Collection~insertCallback * @param {Object} result The result object will contain two arrays (inserted * and failed) which represent the documents that did get inserted and those * that didn't for some reason (usually index violation). Failed items also * contain a reason. Inspect the failed array for further information. * * A third field called "deferred" is a boolean value to indicate if the * insert operation was deferred across more than one CPU cycle (to avoid * blocking the main thread). */ /** * 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 {Collection~insertCallback=} callback Optional callback called * once the insert is complete. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback.call(this, resultObj); } this._onChange(); this.emit('immediateChange', {type: 'insert', data: inserted, failed: failed}); this.deferEmit('change', {type: 'insert', data: inserted, failed: failed}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); if (self.chainWillSend()) { self.chainSend('insert', { dataSet: self.decouple([doc]) }, { index: index }); } //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, hash = this.hash(doc), pk = this._primaryKey; // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[pk], doc); this._primaryCrc.uniqueSet(doc[pk], hash); this._crcLookup.uniqueSet(hash, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, hash = this.hash(doc), pk = this._primaryKey; // Remove from primary key index this._primaryIndex.unSet(doc[pk]); this._primaryCrc.unSet(doc[pk]); this._crcLookup.unSet(hash); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param {String} search The string to search for. Case sensitive. * @param {Object=} options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinIndex, joinSource = {}, joinQuery, joinPath, joinSourceKey, joinSourceType, joinSourceIdentifier, joinSourceData, resultRemove = [], i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); // Check if the query tries to limit by data that would only exist after // the join operation has been completed if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get references to the join sources op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinSourceData = analysis.joinsOn[joinIndex]; joinSourceKey = joinSourceData.key; joinSourceType = joinSourceData.type; joinSourceIdentifier = joinSourceData.id; joinPath = new Path(analysis.joinQueries[joinSourceKey]); joinQuery = joinPath.value(query)[0]; joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinSourceKey]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource)); op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); this.spliceArrayByIndexList(resultArr, resultRemove); op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } // Now process any $groupBy clause if (options.$groupBy) { op.data('flag.group', true); op.time('group'); resultArr = this.group(options.$groupBy, resultArr); op.time('group'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; /** * Groups an array of documents into multiple array fields, named by the value * of the given group path. * @param {*} groupObj The key path the array objects should be grouped by. * @param {Array} arr The array of documents to group. * @returns {Object} */ Collection.prototype.group = function (groupObj, arr) { // Convert the index object to an array of key val objects var keys = sharedPathSolver.parse(groupObj, true), groupPathSolver = new Path(), groupValue, groupResult = {}, keyIndex, i; if (keys.length) { for (keyIndex = 0; keyIndex < keys.length; keyIndex++) { groupPathSolver.path(keys[keyIndex].path); // Execute group for (i = 0; i < arr.length; i++) { groupValue = groupPathSolver.get(arr[i]); groupResult[groupValue] = groupResult[groupValue] || []; groupResult[groupValue].push(arr[i]); } } } return groupResult; }; // 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); } };*/ /** * REMOVED AS SUPERCEDED BY BETTER SORT SYSTEMS * 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 {String} key The path to sort by. * @param {Array} arr The array of objects to sort. * @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 {Object} query The search query to analyse. * @param {Object} options The query options object. * @param {Operation} op The instance of the Operation class that * this operation is using to track things like performance and steps * taken etc. * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinSourceIndex, joinSourceKey, joinSourceType, joinSourceIdentifier, joinMatch, joinSources = [], joinSourceReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options, op); 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, op); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) { // Loop the join sources and keep a reference to them for (joinSourceKey in options.$join[joinSourceIndex]) { if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) { joinMatch = options.$join[joinSourceIndex][joinSourceKey]; joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; joinSources.push({ id: joinSourceIdentifier, type: joinSourceType, key: joinSourceKey }); // Check if the join uses an $as operator if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) { joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as); } else { joinSourceReferences.push(joinSourceKey); } } } } // Loop the join source references and determine if the query references // any of the sources that are used in the join. If there no queries against // joined sources the find method can use a code path optimised for this. // Queries against joined sources requires the joined sources to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinSourceReferences.length; index++) { // Check if the query references any source data that the join will create queryPath = this._queryReferencesSource(query, joinSourceReferences[index], ''); if (queryPath) { analysis.joinQueries[joinSources[index].key] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinSources; analysis.queriesOn = analysis.queriesOn.concat(joinSources); } return analysis; }; /** * Checks if the passed query references a source object (such * as a collection) by name. * @param {Object} query The query object to scan. * @param {String} sourceName The source name to scan for in the query. * @param {String=} path The path to scan from. * @returns {*} * @private */ Collection.prototype._queryReferencesSource = function (query, sourceName, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === sourceName) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesSource(query[i], sourceName, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching * parent documents from which the sub-documents are queried. * @param {String} path The path string used to identify the * key in which sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching * which sub-documents to return. * @param {Object=} subDocOptions The options object to use * when querying for sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents * that matches the subDocQuery parameter. * @param {Object} match The query object to use when matching * parent documents from which the sub-documents are queried. * @param {String} path The path string used to identify the * key in which sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching * which sub-documents to return. * @param {Object=} subDocOptions The options object to use * when querying for sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { if (options.type) { // Check if the specified type is available if (Shared.index[options.type]) { // We found the type, generate it index = new Shared.index[options.type](keys, options, this); } else { throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)'); } } else { // Create default index type index = new IndexHashMap(keys, options, this); } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', { /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data.dataSet); self.update({}, obj1); } else { self.insert(packet.data.dataSet); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data.dataSet); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; /** * Creates a condition handler that will react to changes in data on the * collection. * @example Create a condition handler that reacts when data changes. * var coll = db.collection('test'), * condition = coll.when({_id: 'test1', val: 1}) * .then(function () { * console.log('Condition met!'); * }) * .else(function () { * console.log('Condition un-met'); * }); * * coll.insert({_id: 'test1', val: 1}); * * @see Condition * @param {Object} query The query that will trigger the condition's then() * callback. * @returns {Condition} */ Collection.prototype.when = function (query) { var queryId = JSON.stringify(query); this._when = this._when || {}; this._when[queryId] = this._when[queryId] || new Condition(this, query); return this._when[queryId]; }; Db.prototype.collection = new Overload('Db.prototype.collection', { /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the * primary key field on the collection objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the * primary key field on the collection objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other * variants and handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or * regular expression to use to match collection names against. * @returns {Array} An array of objects containing details of each * collection the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Condition":9,"./Index2d":16,"./IndexBinaryTree":17,"./IndexHashMap":18,"./KeyValueStore":19,"./Metrics":20,"./Overload":33,"./Path":35,"./ReactorIO":39,"./Shared":41}],8:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Events'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {String=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Remove old data this._data.remove(chainPacket.data.oldData); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); delete this._listeners; if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; /** * Creates a new collectionGroup instance or returns an existing * instance if one already exists with the passed name. * @func collectionGroup * @memberOf Db * @param {String} name The name of the instance. * @returns {*} */ Db.prototype.collectionGroup = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof CollectionGroup) { return name; } if (this._collectionGroup && this._collectionGroup[name]) { return this._collectionGroup[name]; } this._collectionGroup[name] = new CollectionGroup(name).db(this); self.emit('create', self._collectionGroup[name], 'collectionGroup', name); return this._collectionGroup[name]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":7,"./Shared":41}],9:[function(_dereq_,module,exports){ "use strict"; /** * The condition class monitors a data source and updates it's internal * state depending on clauses that it has been given. When all clauses * are satisfied the then() callback is fired. If conditions were met * but data changed that made them un-met, the else() callback is fired. */ var Shared, Condition; Shared = _dereq_('./Shared'); /** * Create a constructor method that calls the instance's init method. * This allows the constructor to be overridden by other modules because * they can override the init method with their own. */ Condition = function () { this.init.apply(this, arguments); }; Condition.prototype.init = function (dataSource, clause) { this._dataSource = dataSource; this._query = [clause]; this._started = false; this._state = [false]; this._satisfied = false; // Set this to true by default for faster performance this.earlyExit(true); }; // Tell ForerunnerDB about our new module Shared.addModule('Condition', Condition); // Mixin some commonly used methods Shared.mixin(Condition.prototype, 'Mixin.Common'); Shared.mixin(Condition.prototype, 'Mixin.ChainReactor'); Shared.synthesize(Condition.prototype, 'then'); Shared.synthesize(Condition.prototype, 'else'); Shared.synthesize(Condition.prototype, 'earlyExit'); Shared.synthesize(Condition.prototype, 'debug'); /** * Adds a new clause to the condition. * @param {Object} clause The query clause to add to the condition. * @returns {Condition} */ Condition.prototype.and = function (clause) { this._query.push(clause); this._state.push(false); return this; }; /** * Starts the condition so that changes to data will call callback * methods according to clauses being met. * @param {*} initialState Initial state of condition. * @returns {Condition} */ Condition.prototype.start = function (initialState) { if (!this._started) { var self = this; if (arguments.length !== 0) { this._satisfied = initialState; } // Resolve the current state this._updateStates(); self._onChange = function () { self._updateStates(); }; // Create a chain reactor link to the data source so we start receiving CRUD ops from it this._dataSource.on('change', self._onChange); this._started = true; } return this; }; /** * Updates the internal status of all the clauses against the underlying * data source. * @private */ Condition.prototype._updateStates = function () { var satisfied = true, i; for (i = 0; i < this._query.length; i++) { this._state[i] = this._dataSource.count(this._query[i]) > 0; if (this._debug) { console.log(this.logIdentifier() + ' Evaluating', this._query[i], '=', this._query[i]); } if (!this._state[i]) { satisfied = false; // Early exit since we have found a state that is not true if (this._earlyExit) { break; } } } if (this._satisfied !== satisfied) { // Our state has changed, fire the relevant operation if (satisfied) { // Fire the "then" operation if (this._then) { this._then(); } } else { // Fire the "else" operation if (this._else) { this._else(); } } this._satisfied = satisfied; } }; /** * Stops the condition so that callbacks will no longer fire. * @returns {Condition} */ Condition.prototype.stop = function () { if (this._started) { this._dataSource.off('change', this._onChange); delete this._onChange; this._started = false; } return this; }; // Tell ForerunnerDB that our module has finished loading Shared.finishModule('Condition'); module.exports = Condition; },{"./Shared":41}],10:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (val) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":11,"./Metrics.js":20,"./Overload":33,"./Shared":41}],11:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Checksum, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Checksum = _dereq_('./Checksum.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.Checksum = Checksum; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Checksum.js":6,"./Collection.js":7,"./Metrics.js":20,"./Overload":33,"./Shared":41}],12:[function(_dereq_,module,exports){ "use strict"; // TODO: Remove the _update* methods because we are already mixing them // TODO: in now via Mixin.Updating and update autobind to extend the _update* // TODO: methods like we already do with collection var Shared, Collection, Db; Shared = _dereq_('./Shared'); /** * Creates a new Document instance. Documents allow you to create individual * objects that can have standard ForerunnerDB CRUD operations run against * them, as well as data-binding if the AutoBind module is included in your * project. * @name Document * @class Document * @constructor */ var FdbDocument = function () { this.init.apply(this, arguments); }; FdbDocument.prototype.init = function (name) { this._name = name; this._data = {}; }; Shared.addModule('Document', FdbDocument); Shared.mixin(FdbDocument.prototype, 'Mixin.Common'); Shared.mixin(FdbDocument.prototype, 'Mixin.Events'); Shared.mixin(FdbDocument.prototype, 'Mixin.ChainReactor'); Shared.mixin(FdbDocument.prototype, 'Mixin.Constants'); Shared.mixin(FdbDocument.prototype, 'Mixin.Triggers'); Shared.mixin(FdbDocument.prototype, 'Mixin.Matching'); Shared.mixin(FdbDocument.prototype, 'Mixin.Updating'); Shared.mixin(FdbDocument.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; /** * Gets / sets the current state. * @func state * @memberof Document * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'state'); /** * Gets / sets the db instance this class instance belongs to. * @func db * @memberof Document * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'db'); /** * Gets / sets the document name. * @func name * @memberof Document * @param {String=} val The name to assign * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'name'); /** * Sets the data for the document. * @func setData * @memberof Document * @param data * @param options * @returns {Document} */ FdbDocument.prototype.setData = function (data, options) { var i, $unset; if (data) { options = options || { $decouple: true }; if (options && options.$decouple === true) { data = this.decouple(data); } if (this._linked) { $unset = {}; // Remove keys that don't exist in the new data from the current object for (i in this._data) { if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) { // Check if existing data has key if (data[i] === undefined) { // Add property name to those to unset $unset[i] = 1; } } } data.$unset = $unset; // Now update the object with new data this.updateObject(this._data, data, {}); } else { // Straight data assignment this._data = data; } this.deferEmit('change', {type: 'setData', data: this.decouple(this._data)}); } return this; }; /** * Gets the document's data returned as a single object. * @func find * @memberof Document * @param {Object} query The query object - currently unused, just * provide a blank object e.g. {} * @param {Object=} options An options object. * @returns {Object} The document's data object. */ FdbDocument.prototype.find = function (query, options) { var result; if (options && options.$decouple === false) { result = this._data; } else { result = this.decouple(this._data); } return result; }; /** * Modifies the document. This will update the document with the data held in 'update'. * @func update * @memberof Document * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ FdbDocument.prototype.update = function (query, update, options) { var result = this.updateObject(this._data, update, query, options); if (result) { this.deferEmit('change', {type: 'update', data: this.decouple(this._data)}); } }; /** * Internal method for document updating. * @func updateObject * @memberof Document * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ FdbDocument.prototype.updateObject = Collection.prototype.updateObject; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @func _isPositionalKey * @memberof Document * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ FdbDocument.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Updates a property on an object depending on if the collection is * currently running data-binding or not. * @func _updateProperty * @memberof Document * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ FdbDocument.prototype._updateProperty = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, val); if (this.debug()) { console.log(this.logIdentifier() + ' Setting data-bound document property "' + prop + '"'); } } else { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"'); } } }; /** * Increments a value for a property on a document by the passed number. * @func _updateIncrement * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ FdbDocument.prototype._updateIncrement = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, doc[prop] + val); } else { doc[prop] += val; } }; /** * Changes the index of an item in the passed array. * @func _updateSpliceMove * @memberof Document * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ FdbDocument.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) { if (this._linked) { window.jQuery.observable(arr).move(indexFrom, indexTo); if (this.debug()) { console.log(this.logIdentifier() + ' Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } } else { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } } }; /** * Inserts an item into the passed array at the specified index. * @func _updateSplicePush * @memberof Document * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ FdbDocument.prototype._updateSplicePush = function (arr, index, doc) { if (arr.length > index) { if (this._linked) { window.jQuery.observable(arr).insert(index, doc); } else { arr.splice(index, 0, doc); } } else { if (this._linked) { window.jQuery.observable(arr).insert(doc); } else { arr.push(doc); } } }; /** * Inserts an item at the end of an array. * @func _updatePush * @memberof Document * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ FdbDocument.prototype._updatePush = function (arr, doc) { if (this._linked) { window.jQuery.observable(arr).insert(doc); } else { arr.push(doc); } }; /** * Removes an item from the passed array. * @func _updatePull * @memberof Document * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ FdbDocument.prototype._updatePull = function (arr, index) { if (this._linked) { window.jQuery.observable(arr).remove(index); } else { arr.splice(index, 1); } }; /** * Multiplies a value for a property on a document by the passed number. * @func _updateMultiply * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ FdbDocument.prototype._updateMultiply = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, doc[prop] * val); } else { doc[prop] *= val; } }; /** * Renames a property on a document to the passed property. * @func _updateRename * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ FdbDocument.prototype._updateRename = function (doc, prop, val) { var existingVal = doc[prop]; if (this._linked) { window.jQuery.observable(doc).setProperty(val, existingVal); window.jQuery.observable(doc).removeProperty(prop); } else { doc[val] = existingVal; delete doc[prop]; } }; /** * Deletes a property on a document. * @func _updateUnset * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ FdbDocument.prototype._updateUnset = function (doc, prop) { if (this._linked) { window.jQuery.observable(doc).removeProperty(prop); } else { delete doc[prop]; } }; /** * Drops the document. * @func drop * @memberof Document * @returns {boolean} True if successful, false if not. */ FdbDocument.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._db && this._name) { if (this._db && this._db._document && this._db._document[this._name]) { this._state = 'dropped'; delete this._db._document[this._name]; delete this._data; this.emit('drop', this); if (callback) { callback(false, true); } delete this._listeners; return true; } } } else { return true; } return false; }; /** * Creates a new document instance or returns an existing * instance if one already exists with the passed name. * @func document * @memberOf Db * @param {String} name The name of the instance. * @returns {*} */ Db.prototype.document = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof FdbDocument) { if (name.state() !== 'droppped') { return name; } else { name = name.name(); } } if (this._document && this._document[name]) { return this._document[name]; } this._document = this._document || {}; this._document[name] = new FdbDocument(name).db(this); self.emit('create', self._document[name], 'document', name); return this._document[name]; } else { // Return an object of document data return this._document; } }; /** * Returns an array of documents the DB currently has. * @func documents * @memberof Db * @returns {Array} An array of objects containing details of each document * the database is currently managing. */ Db.prototype.documents = function () { var arr = [], item, i; for (i in this._document) { if (this._document.hasOwnProperty(i)) { item = this._document[i]; arr.push({ name: i, linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Document'); module.exports = FdbDocument; },{"./Collection":7,"./Shared":41}],13:[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, PI180 = Math.PI / 180, PI180R = 180 / Math.PI, earthRadius = 6371; // mean radius of the earth 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 () {}; /** * Converts degrees to radians. * @param {Number} degrees * @return {Number} radians */ GeoHash.prototype.radians = function radians (degrees) { return degrees * PI180; }; /** * Converts radians to degrees. * @param {Number} radians * @return {Number} degrees */ GeoHash.prototype.degrees = function (radians) { return radians * PI180R; }; 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 a new lat/lng by travelling from the center point in the * bearing specified for the distance specified. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param {Number} distanceKm The distance to travel in kilometers. * @param {Number} bearing The bearing to travel in degrees (zero is * north). * @returns {{lat: Number, lng: Number}} */ GeoHash.prototype.calculateLatLngByDistanceBearing = function (centerPoint, distanceKm, bearing) { var curLon = centerPoint[1], curLat = centerPoint[0], destLat = Math.asin(Math.sin(this.radians(curLat)) * Math.cos(distanceKm / earthRadius) + Math.cos(this.radians(curLat)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(bearing))), tmpLon = this.radians(curLon) + Math.atan2(Math.sin(this.radians(bearing)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(curLat)), Math.cos(distanceKm / earthRadius) - Math.sin(this.radians(curLat)) * Math.sin(destLat)), destLon = (tmpLon + 3 * Math.PI) % (2 * Math.PI) - Math.PI; // normalise to -180..+180º return { lat: this.degrees(destLat), lng: this.degrees(destLon) }; }; /** * Calculates the extents of a bounding box around the center point which * encompasses the radius in kilometers passed. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param radiusKm Radius in kilometers. * @returns {{lat: Array, lng: Array}} */ GeoHash.prototype.calculateExtentByRadius = function (centerPoint, radiusKm) { var maxWest, maxEast, maxNorth, maxSouth, lat = [], lng = []; maxNorth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 0); maxEast = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 90); maxSouth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 180); maxWest = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 270); lat[0] = maxNorth.lat; lat[1] = maxSouth.lat; lng[0] = maxWest.lng; lng[1] = maxEast.lng; return { lat: lat, lng: lng }; }; /** * Calculates all the geohashes that make up the bounding box that surrounds * the circle created from the center point and radius passed. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param {Number} radiusKm The radius in kilometers to encompass. * @param {Number} precision The number of characters to limit the returned * geohash strings to. * @returns {Array} The array of geohashes that encompass the bounding box. */ GeoHash.prototype.calculateHashArrayByRadius = function (centerPoint, radiusKm, precision) { var extent = this.calculateExtentByRadius(centerPoint, radiusKm), northWest = [extent.lat[0], extent.lng[0]], northEast = [extent.lat[0], extent.lng[1]], southWest = [extent.lat[1], extent.lng[0]], northWestHash = this.encode(northWest[0], northWest[1], precision), northEastHash = this.encode(northEast[0], northEast[1], precision), southWestHash = this.encode(southWest[0], southWest[1], precision), hash, widthCount = 0, heightCount = 0, widthIndex, heightIndex, hashArray = []; hash = northWestHash; hashArray.push(hash); // Walk from north west to north east until we find the north east geohash while (hash !== northEastHash) { hash = this.calculateAdjacent(hash, 'right'); widthCount++; hashArray.push(hash); } hash = northWestHash; // Walk from north west to south west until we find the south west geohash while (hash !== southWestHash) { hash = this.calculateAdjacent(hash, 'bottom'); heightCount++; } // We now know the width and height in hash boxes of the area, fill in the // rest of the hashes into the hashArray array for (widthIndex = 0; widthIndex <= widthCount; widthIndex++) { hash = hashArray[widthIndex]; for (heightIndex = 0; heightIndex < heightCount; heightIndex++) { hash = this.calculateAdjacent(hash, 'bottom'); hashArray.push(hash); } } return hashArray; }; /** * 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 a longitude/latitude array. * The array contains three latitudes and three longitudes. The * first of each is the lower extent of the geohash bounding box, * the second is the upper extent and the third is the center * of the geohash bounding box. * @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 { lat: lat, lng: 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; }; if (typeof module !== 'undefined') { module.exports = GeoHash; } },{}],14:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, View, CollectionInit, DbInit, ReactorIO; //Shared = ForerunnerDB.shared; Shared = _dereq_('./Shared'); /** * Creates a new grid instance. * @name Grid * @class Grid * @param {String} selector jQuery selector. * @param {String} template The template selector. * @param {Object=} options The options object to apply to the grid. * @constructor */ var Grid = function (selector, template, options) { this.init.apply(this, arguments); }; Grid.prototype.init = function (selector, template, options) { var self = this; this._selector = selector; this._template = template; this._options = options || {}; this._debug = {}; this._id = this.objectId(); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; }; Shared.addModule('Grid', Grid); Shared.mixin(Grid.prototype, 'Mixin.Common'); Shared.mixin(Grid.prototype, 'Mixin.ChainReactor'); Shared.mixin(Grid.prototype, 'Mixin.Constants'); Shared.mixin(Grid.prototype, 'Mixin.Triggers'); Shared.mixin(Grid.prototype, 'Mixin.Events'); Shared.mixin(Grid.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); View = _dereq_('./View'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @func state * @memberof Grid * @param {String=} val The name of the state to set. * @returns {Grid} */ Shared.synthesize(Grid.prototype, 'state'); /** * Gets / sets the current name. * @func name * @memberof Grid * @param {String=} val The name to set. * @returns {Grid} */ Shared.synthesize(Grid.prototype, 'name'); /** * Executes an insert against the grid's underlying data-source. * @func insert * @memberof Grid */ Grid.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the grid's underlying data-source. * @func update * @memberof Grid */ Grid.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the grid's underlying data-source. * @func updateById * @memberof Grid */ Grid.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the grid's underlying data-source. * @func remove * @memberof Grid */ Grid.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Sets the collection from which the grid will assemble its data. * @func from * @memberof Grid * @param {Collection} collection The collection to use to assemble grid data. * @returns {Grid} */ Grid.prototype.from = function (collection) { //var self = this; if (collection !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); this._from._removeGrid(this); } if (typeof(collection) === 'string') { collection = this._db.collection(collection); } this._from = collection; this._from.on('drop', this._collectionDroppedWrap); this.refresh(); } return this; }; /** * Gets / sets the db instance this class instance belongs to. * @func db * @memberof Grid * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Grid.prototype, 'db', function (db) { if (db) { // Apply the same debug settings this.debug(db.debug()); } return this.$super.apply(this, arguments); }); Grid.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from grid delete this._from; } }; /** * Drops a grid and all it's stored data from the database. * @func drop * @memberof Grid * @returns {boolean} True on success, false on failure. */ Grid.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { // Remove data-binding this._from.unlink(this._selector, this.template()); // Kill listeners and references this._from.off('drop', this._collectionDroppedWrap); this._from._removeGrid(this); if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping grid ' + this._selector); } this._state = 'dropped'; if (this._db && this._selector) { delete this._db._grid[this._selector]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._selector; delete this._template; delete this._from; delete this._db; delete this._listeners; return true; } } else { return true; } return false; }; /** * Gets / sets the grid's HTML template to use when rendering. * @func template * @memberof Grid * @param {Selector} template The template's jQuery selector. * @returns {*} */ Grid.prototype.template = function (template) { if (template !== undefined) { this._template = template; return this; } return this._template; }; Grid.prototype._sortGridClick = function (e) { var elem = window.jQuery(e.currentTarget), sortColText = elem.attr('data-grid-sort') || '', sortColDir = parseInt((elem.attr('data-grid-dir') || "-1"), 10) === -1 ? 1 : -1, sortCols = sortColText.split(','), sortObj = {}, i; // Remove all grid sort tags from the grid window.jQuery(this._selector).find('[data-grid-dir]').removeAttr('data-grid-dir'); // Flip the sort direction elem.attr('data-grid-dir', sortColDir); for (i = 0; i < sortCols.length; i++) { sortObj[sortCols] = sortColDir; } Shared.mixin(sortObj, this._options.$orderBy); this._from.orderBy(sortObj); this.emit('sort', sortObj); }; /** * Refreshes the grid data such as ordering etc. * @func refresh * @memberof Grid */ Grid.prototype.refresh = function () { if (this._from) { if (this._from.link) { var self = this, elem = window.jQuery(this._selector), sortClickListener = function () { self._sortGridClick.apply(self, arguments); }; // Clear the container elem.html(''); if (self._from.orderBy) { // Remove listeners elem.off('click', '[data-grid-sort]', sortClickListener); } if (self._from.query) { // Remove listeners elem.off('click', '[data-grid-filter]', sortClickListener); } // Set wrap name if none is provided self._options.$wrap = self._options.$wrap || 'gridRow'; // Auto-bind the data to the grid template self._from.link(self._selector, self.template(), self._options); // Check if the data source (collection or view) has an // orderBy method (usually only views) and if so activate // the sorting system if (self._from.orderBy) { // Listen for sort requests elem.on('click', '[data-grid-sort]', sortClickListener); } if (self._from.query) { // Listen for filter requests var queryObj = {}; elem.find('[data-grid-filter]').each(function (index, filterElem) { filterElem = window.jQuery(filterElem); var filterField = filterElem.attr('data-grid-filter'), filterVarType = filterElem.attr('data-grid-vartype'), filterSort = {}, title = filterElem.html(), dropDownButton, dropDownMenu, template, onFilterSourceChange, filterQuery, filterView = self._db.view('tmpGridFilter_' + self._id + '_' + filterField); filterSort[filterField] = 1; filterQuery = { $distinct: filterSort }; filterView .query(filterQuery) .orderBy(filterSort) .from(self._from._from); onFilterSourceChange = function () { filterView.refresh(); }; // Listen for changes on the filter source and update // the filters if changes occur self._from._from.on('change', onFilterSourceChange); // This bit of commented code can filter other filter // views so that only items that match other filter // selections show in the other filters, but this can // be confusing to the user. The best possible way to // use this would be to "grey out" the selections that // cannot be used because they would return zero results // when used in conjuctions with other filter selections. /*self._from.on('change', function () { if (self._from && self._from instanceof View) { var query = self._from.query(); query.$distinct = filterSort; delete query[filterField]; filterView .query(query); console.log(self._from._from.find(query)); } });*/ // Listen for the grid being dropped and remove listener // for changes on filter source self.on('drop', function () { if (self._from && self._from._from) { self._from._from.off('change', onFilterSourceChange); } }); template = [ '<div class="dropdown" id="' + self._id + '_' + filterField + '">', '<button class="btn btn-default dropdown-toggle" type="button" id="' + self._id + '_' + filterField + '_dropdownButton" data-toggle="dropdown" aria-expanded="true">', title + ' <span class="caret"></span>', '</button>', '</div>' ]; dropDownButton = window.jQuery(template.join('')); dropDownMenu = window.jQuery('<ul class="dropdown-menu" role="menu" id="' + self._id + '_' + filterField + '_dropdownMenu"></ul>'); dropDownButton.append(dropDownMenu); filterElem.html(dropDownButton); // Data-link the underlying data to the grid filter drop-down filterView.link(dropDownMenu, { template: [ '<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">', '<input type="search" class="form-control gridFilterSearch" placeholder="Search...">', '<span class="input-group-btn">', '<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>', '</span>', '</li>', '<li role="presentation" class="divider"></li>', '<li role="presentation" data-val="$all">', '<a role="menuitem" tabindex="-1">', '<input type="checkbox" checked>&nbsp;All', '</a>', '</li>', '<li role="presentation" class="divider"></li>', '{^{for options}}', '<li role="presentation" data-link="data-val{:' + filterField + '}">', '<a role="menuitem" tabindex="-1">', '<input type="checkbox">&nbsp;{^{:' + filterField + '}}', '</a>', '</li>', '{{/for}}' ].join('') }, { $wrap: 'options' }); elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) { var elem = window.jQuery(this), query = filterView.query(), search = elem.val(); if (search) { query[filterField] = new RegExp(search, 'gi'); } else { delete query[filterField]; } filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) { // Clear search text box window.jQuery(this).parents('li').find('.gridFilterSearch').val(''); // Clear view query var query = filterView.query(); delete query[filterField]; filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) { e.stopPropagation(); var fieldValue, elem = $(this), checkbox = elem.find('input[type="checkbox"]'), checked, addMode = true, fieldInArr, liElem, i; // If the checkbox is not the one clicked on if (!window.jQuery(e.target).is('input')) { // Set checkbox to opposite of current value checkbox.prop('checked', !checkbox.prop('checked')); checked = checkbox.is(':checked'); } else { checkbox.prop('checked', checkbox.prop('checked')); checked = checkbox.is(':checked'); } liElem = window.jQuery(this); fieldValue = liElem.attr('data-val'); // Check if the selection is the "all" option if (fieldValue === '$all') { // Remove the field from the query delete queryObj[filterField]; // Clear all other checkboxes liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false); } else { // Clear the "all" checkbox liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false); // Check if the type needs casting switch (filterVarType) { case 'integer': fieldValue = parseInt(fieldValue, 10); break; case 'float': fieldValue = parseFloat(fieldValue); break; default: } // Check if the item exists already queryObj[filterField] = queryObj[filterField] || { $in: [] }; fieldInArr = queryObj[filterField].$in; for (i = 0; i < fieldInArr.length; i++) { if (fieldInArr[i] === fieldValue) { // Item already exists if (checked === false) { // Remove the item fieldInArr.splice(i, 1); } addMode = false; break; } } if (addMode && checked) { fieldInArr.push(fieldValue); } if (!fieldInArr.length) { // Remove the field from the query delete queryObj[filterField]; } } // Set the view query self._from.queryData(queryObj); if (self._from.pageFirst) { self._from.pageFirst(); } }); }); } self.emit('refresh'); } else { throw('Grid requires the AutoBind module in order to operate!'); } } return this; }; /** * Returns the number of documents currently in the grid. * @func count * @memberof Grid * @returns {Number} */ Grid.prototype.count = function () { return this._from.count(); }; /** * Creates a grid and assigns the collection as its data source. * @func grid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.grid = View.prototype.grid = function (selector, template, options) { if (this._db && this._db._grid ) { if (selector !== undefined) { if (template !== undefined) { if (!this._db._grid[selector]) { var grid = new Grid(selector, template, options) .db(this._db) .from(this); this._grid = this._grid || []; this._grid.push(grid); this._db._grid[selector] = grid; return grid; } else { throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector); } } return this._db._grid[selector]; } return this._db._grid; } }; /** * Removes a grid safely from the DOM. Must be called when grid is * no longer required / is being removed from DOM otherwise references * will stick around and cause memory leaks. * @func unGrid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) { var i, grid; if (this._db && this._db._grid ) { if (selector && template) { if (this._db._grid[selector]) { grid = this._db._grid[selector]; delete this._db._grid[selector]; return grid.drop(); } else { throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name); } } else { // No parameters passed, remove all grids from this module for (i in this._db._grid) { if (this._db._grid.hasOwnProperty(i)) { grid = this._db._grid[i]; delete this._db._grid[i]; grid.drop(); if (this.debug()) { console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"'); } } } this._db._grid = {}; } } }; /** * Adds a grid to the internal grid lookup. * @func _addGrid * @memberof Collection * @param {Grid} grid The grid to add. * @returns {Collection} * @private */ Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) { if (grid !== undefined) { this._grid = this._grid || []; this._grid.push(grid); } return this; }; /** * Removes a grid from the internal grid lookup. * @func _removeGrid * @memberof Collection * @param {Grid} grid The grid to remove. * @returns {Collection} * @private */ Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) { if (grid !== undefined && this._grid) { var index = this._grid.indexOf(grid); if (index > -1) { this._grid.splice(index, 1); } } return this; }; // Extend DB with grids init Db.prototype.init = function () { this._grid = {}; DbInit.apply(this, arguments); }; /** * Determine if a grid with the passed name already exists. * @func gridExists * @memberof Db * @param {String} selector The jQuery selector to bind the grid to. * @returns {boolean} */ Db.prototype.gridExists = function (selector) { return Boolean(this._grid[selector]); }; /** * Creates a grid based on the passed arguments. * @func grid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.grid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Removes a grid based on the passed arguments. * @func unGrid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.unGrid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Returns an array of grids the DB currently has. * @func grids * @memberof Db * @returns {Array} An array of objects containing details of each grid * the database is currently managing. */ Db.prototype.grids = function () { var arr = [], item, i; for (i in this._grid) { if (this._grid.hasOwnProperty(i)) { item = this._grid[i]; arr.push({ name: i, count: item.count(), linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Grid'); module.exports = Grid; },{"./Collection":7,"./CollectionGroup":8,"./ReactorIO":39,"./Shared":41,"./View":43}],15:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Collection, CollectionInit, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * The constructor. * * @constructor */ var Highchart = function (collection, options) { this.init.apply(this, arguments); }; Highchart.prototype.init = function (collection, options) { this._options = options; this._selector = window.jQuery(this._options.selector); if (!this._selector[0]) { throw(this.classIdentifier() + ' "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector); } this._listeners = {}; this._collection = collection; // Setup the chart this._options.series = []; // Disable attribution on highcharts options.chartOptions = options.chartOptions || {}; options.chartOptions.credits = false; // Set the data for the chart var data, seriesObj, chartData; switch (this._options.type) { case 'pie': // Create chart from data this._selector.highcharts(this._options.chartOptions); this._chart = this._selector.highcharts(); // Generate graph data from collection data data = this._collection.find(); seriesObj = { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)', style: { color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black' } } }; chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField); window.jQuery.extend(seriesObj, this._options.seriesOptions); window.jQuery.extend(seriesObj, { name: this._options.seriesName, data: chartData }); this._chart.addSeries(seriesObj, true, true); break; case 'line': case 'area': case 'column': case 'bar': // Generate graph data from collection data chartData = this.seriesDataFromCollectionData( this._options.seriesField, this._options.keyField, this._options.valField, this._options.orderBy, this._options ); this._options.chartOptions.xAxis = chartData.xAxis; this._options.chartOptions.series = chartData.series; this._selector.highcharts(this._options.chartOptions); this._chart = this._selector.highcharts(); break; default: throw(this.classIdentifier() + ' "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type); } // Hook the collection events to auto-update the chart this._hookEvents(); }; Shared.addModule('Highchart', Highchart); Collection = Shared.modules.Collection; CollectionInit = Collection.prototype.init; Shared.mixin(Highchart.prototype, 'Mixin.Common'); Shared.mixin(Highchart.prototype, 'Mixin.Events'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Highchart.prototype, 'state'); /** * Generate pie-chart series data from the given collection data array. * @param data * @param keyField * @param valField * @returns {Array} */ Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) { var graphData = [], i; for (i = 0; i < data.length; i++) { graphData.push([data[i][keyField], data[i][valField]]); } return graphData; }; /** * Generate line-chart series data from the given collection data array. * @param seriesField * @param keyField * @param valField * @param orderBy */ Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy, options) { var data = this._collection.distinct(seriesField), seriesData = [], xAxis = options && options.chartOptions && options.chartOptions.xAxis ? options.chartOptions.xAxis : { categories: [] }, seriesName, query, dataSearch, seriesValues, sData, i, k; // What we WANT to output: /*series: [{ name: 'Responses', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6] }]*/ // Loop keys for (i = 0; i < data.length; i++) { seriesName = data[i]; query = {}; query[seriesField] = seriesName; seriesValues = []; dataSearch = this._collection.find(query, { orderBy: orderBy }); // Loop the keySearch data and grab the value for each item for (k = 0; k < dataSearch.length; k++) { if (xAxis.categories) { xAxis.categories.push(dataSearch[k][keyField]); seriesValues.push(dataSearch[k][valField]); } else { seriesValues.push([dataSearch[k][keyField], dataSearch[k][valField]]); } } sData = { name: seriesName, data: seriesValues }; if (options.seriesOptions) { for (k in options.seriesOptions) { if (options.seriesOptions.hasOwnProperty(k)) { sData[k] = options.seriesOptions[k]; } } } seriesData.push(sData); } return { xAxis: xAxis, series: seriesData }; }; /** * Hook the events the chart needs to know about from the internal collection. * @private */ Highchart.prototype._hookEvents = function () { var self = this; self._collection.on('change', function () { self._changeListener.apply(self, arguments); }); // If the collection is dropped, clean up after ourselves self._collection.on('drop', function () { self.drop.apply(self); }); }; /** * Handles changes to the collection data that the chart is reading from and then * updates the data in the chart display. * @private */ Highchart.prototype._changeListener = function () { var self = this; // Update the series data on the chart if (typeof self._collection !== 'undefined' && self._chart) { var data = self._collection.find(), i; switch (self._options.type) { case 'pie': self._chart.series[0].setData( self.pieDataFromCollectionData( data, self._options.keyField, self._options.valField ), true, true ); break; case 'bar': case 'line': case 'area': case 'column': var seriesData = self.seriesDataFromCollectionData( self._options.seriesField, self._options.keyField, self._options.valField, self._options.orderBy, self._options ); if (seriesData.xAxis.categories) { self._chart.xAxis[0].setCategories( seriesData.xAxis.categories ); } for (i = 0; i < seriesData.series.length; i++) { if (self._chart.series[i]) { // Series exists, set it's data self._chart.series[i].setData( seriesData.series[i].data, true, true ); } else { // Series data does not yet exist, add a new series self._chart.addSeries( seriesData.series[i], true, true ); } } break; default: break; } } }; /** * Destroys the chart and all internal references. * @returns {Boolean} */ Highchart.prototype.drop = function (callback) { if (!this.isDropped()) { this._state = 'dropped'; if (this._chart) { this._chart.destroy(); } if (this._collection) { this._collection.off('change', this._changeListener); this._collection.off('drop', this.drop); if (this._collection._highcharts) { delete this._collection._highcharts[this._options.selector]; } } delete this._chart; delete this._options; delete this._collection; this.emit('drop', this); if (callback) { callback(false, true); } delete this._listeners; return true; } else { return true; } }; // Extend collection with highchart init Collection.prototype.init = function () { this._highcharts = {}; CollectionInit.apply(this, arguments); }; /** * Creates a pie chart from the collection. * @type {Overload} */ Collection.prototype.pieChart = new Overload({ /** * Chart via options object. * @func pieChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'pie'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'pie'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func pieChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {String} seriesName The name of the series to display on the chart. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) { options = options || {}; options.selector = selector; options.keyField = keyField; options.valField = valField; options.seriesName = seriesName; // Call the main chart method this.pieChart(options); } }); /** * Creates a line chart from the collection. * @type {Overload} */ Collection.prototype.lineChart = new Overload({ /** * Chart via selector. * @func lineChart * @memberof Highchart * @param {String} selector The chart selector. * @returns {*} */ 'string': function (selector) { return this._highcharts[selector]; }, /** * Chart via options object. * @func lineChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'line'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'line'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func lineChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.lineChart(options); } }); /** * Creates an area chart from the collection. * @type {Overload} */ Collection.prototype.areaChart = new Overload({ /** * Chart via options object. * @func areaChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'area'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'area'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func areaChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.areaChart(options); } }); /** * Creates a column chart from the collection. * @type {Overload} */ Collection.prototype.columnChart = new Overload({ /** * Chart via options object. * @func columnChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'column'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'column'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func columnChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.columnChart(options); } }); /** * Creates a bar chart from the collection. * @type {Overload} */ Collection.prototype.barChart = new Overload({ /** * Chart via options object. * @func barChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'bar'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'bar'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func barChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.barChart(options); } }); /** * Creates a stacked bar chart from the collection. * @type {Overload} */ Collection.prototype.stackedBarChart = new Overload({ /** * Chart via options object. * @func stackedBarChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'bar'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'bar'; options.plotOptions = options.plotOptions || {}; options.plotOptions.series = options.plotOptions.series || {}; options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func stackedBarChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.stackedBarChart(options); } }); /** * Removes a chart from the page by it's selector. * @memberof Collection * @param {String} selector The chart selector. */ Collection.prototype.dropChart = function (selector) { if (this._highcharts && this._highcharts[selector]) { this._highcharts[selector].drop(); } }; Shared.finishModule('Highchart'); module.exports = Highchart; },{"./Overload":33,"./Shared":41}],16:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; /** * Create the index. * @param {Object} keys The object with the keys that the user wishes the index * to operate on. * @param {Object} options Can be undefined, if passed is an object with arbitrary * options keys and values. * @param {Collection} collection The collection the index should be created for. */ Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; /** * Looks up records that match the passed query and options. * @param query The query to execute. * @param options A query options object. * @param {Operation=} op Optional operation instance that allows * us to provide operation diagnostics and analytics back to the * main calling instance as the process is running. * @returns {*} */ Index2d.prototype.lookup = function (query, options, op) { // 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, op)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options, op)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options, op) { var self = this, neighbours, visitedCount, visitedNodes, visitedData, 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 + 1; break; } } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i + 1; break; } } } if (precision === 0) { precision = 1; } // Calculate 9 box geohashes if (op) { op.time('index2d.calculateHashArea'); } neighbours = sharedGeoHashSolver.calculateHashArrayByRadius(query.$point, maxDistanceKm, precision); if (op) { op.time('index2d.calculateHashArea'); } if (op) { op.data('index2d.near.precision', precision); op.data('index2d.near.hashArea', neighbours); op.data('index2d.near.maxDistanceKm', maxDistanceKm); op.data('index2d.near.centerPointCoords', [query.$point[0], query.$point[1]]); } // Lookup all matching co-ordinates from the btree results = []; visitedCount = 0; visitedData = {}; visitedNodes = []; if (op) { op.time('index2d.near.getDocsInsideHashArea'); } for (i = 0; i < neighbours.length; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visitedData[neighbours[i]] = search; visitedCount += search._visitedCount; visitedNodes = visitedNodes.concat(search._visitedNodes); results = results.concat(search); } if (op) { op.time('index2d.near.getDocsInsideHashArea'); op.data('index2d.near.startsWith', visitedData); op.data('index2d.near.visitedTreeNodes', visitedNodes); } // Work with original data if (op) { op.time('index2d.near.lookupDocsById'); } results = this._collection._primaryIndex.lookup(results); if (op) { op.time('index2d.near.lookupDocsById'); } if (query.$distanceField) { // Decouple the results before we modify them results = this.decouple(results); } if (results.length) { distance = {}; if (op) { op.time('index2d.near.calculateDistanceFromCenter'); } // 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) { if (query.$distanceField) { // Options specify a field to add the distance data to // so add it now sharedPathSolver.set(results[i], query.$distanceField, query.$distanceUnits === 'km' ? distCache : Math.round(distCache * 0.621371)); } if (query.$geoHashField) { // Options specify a field to add the distance data to // so add it now sharedPathSolver.set(results[i], query.$geoHashField, sharedGeoHashSolver.encode(latLng[0], latLng[1], precision)); } // Add item as it is inside radius distance finalResults.push(results[i]); } } if (op) { op.time('index2d.near.calculateDistanceFromCenter'); } // Sort by distance from center if (op) { op.time('index2d.near.sortResultsByDistance'); } finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); if (op) { op.time('index2d.near.sortResultsByDistance'); } } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { console.log('geoWithin() is currently a prototype method with no actual implementation... it just returns a blank array.'); return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; Index2d.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; Index2d.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index['2d'] = Index2d; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":5,"./GeoHash":13,"./Path":35,"./Shared":41}],17:[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, op) { return this._btree.lookup(query, options, op); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.btree = IndexBinaryTree; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":5,"./Path":35,"./Shared":41}],18:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.hashed = IndexHashMap; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":35,"./Shared":41}],19:[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":41}],20:[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":32,"./Shared":41}],21:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],22:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * Creates a chain link between the current reactor node and the passed * reactor node. Chain packets that are send by this reactor node will * then be propagated to the passed node for subsequent packets. * @param {*} obj The chain reactor node to link to. */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, /** * Removes a chain link between the current reactor node and the passed * reactor node. Chain packets sent from this reactor node will no longer * be received by the passed node. * @param {*} obj The chain reactor node to unlink from. */ unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, /** * Determines if this chain reactor node has any listeners downstream. * @returns {Boolean} True if there are nodes downstream of this node. */ chainWillSend: function () { return Boolean(this._chain); }, /** * Sends a chain reactor packet downstream from this node to any of its * chained targets that were linked to this node via a call to chain(). * @param {String} type The type of chain reactor packet to send. This * can be any string but the receiving reactor nodes will not react to * it unless they recognise the string. Built-in strings include: "insert", * "update", "remove", "setData" and "debug". * @param {Object} data A data object that usually contains a key called * "dataSet" which is an array of items to work on, and can contain other * custom keys that help describe the operation. * @param {Object=} options An options object. Can also contain custom * key/value pairs that your custom chain reactor code can operate on. */ chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index, dataCopy = this.decouple(data, count); for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } if (arrItem.chainReceive) { arrItem.chainReceive(this, type, dataCopy[index], options); } } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, /** * Handles receiving a chain reactor message that was sent via the chainSend() * method. Creates the chain packet object and then allows it to be processed. * @param {Object} sender The node that is sending the packet. * @param {String} type The type of packet. * @param {Object} data The data related to the packet. * @param {Object=} options An options object. */ chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }, cancelPropagate = false; if (this.debug && this.debug()) { console.log(this.logIdentifier() + ' Received data from parent reactor node'); } // Check if we have a chain handler method if (this._chainHandler) { // Fire our internal handler cancelPropagate = this._chainHandler(chainPacket); } // Check if we were told to cancel further propagation if (!cancelPropagate) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],23:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Generates a JSON serialisation-compatible object instance. After the * instance has been passed through this method, it will be able to survive * a JSON.stringify() and JSON.parse() cycle and still end up as an * instance at the end. Further information about this process can be found * in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks * @param {*} val The object instance such as "new Date()" or "new RegExp()". */ make: function (val) { // This is a conversion request, hand over to serialiser return serialiser.convert(val); }, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined && data !== "") { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return JSON.parse(data, serialiser.reviver()); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { //return serialiser.stringify(data); return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Generates a unique hash for the passed object. * @param {Object} obj The object to generate a hash for. * @returns {String} */ hash: function (obj) { return JSON.stringify(obj); }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return 'ForerunnerDB ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; }, /** * Registers a timed callback that will overwrite itself if * the same id is used within the timeout period. Useful * for de-bouncing fast-calls. * @param {String} id An ID for the call (use the same one * to debounce the same calls). * @param {Function} callback The callback method to call on * timeout. * @param {Number} timeout The timeout in milliseconds before * the callback is called. */ debounce: function (id, callback, timeout) { var self = this, newData; self._debounce = self._debounce || {}; if (self._debounce[id]) { // Clear timeout for this item clearTimeout(self._debounce[id].timeout); } newData = { callback: callback, timeout: setTimeout(function () { // Delete existing reference delete self._debounce[id]; // Call the callback callback(); }, timeout) }; // Save current data self._debounce[id] = newData; } }; module.exports = Common; },{"./Overload":33,"./Serialiser":40}],24:[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; },{}],25:[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) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event); }); } else { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } } return this; }, 'string, function': function (event, listener) { var self = this, arr, index; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, listener); }); } else { 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) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, id, listener); }); } else { 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) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, id); }); } else { 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 || {}; this._emitting = true; // FIXME: TODO: Add a flag to show we are emitting and then // modify the "off" method to add items to a removal queue // if we are currently emitting, meaning that events that // cause an "off" call in their event method will not intefere // with the event queue until after the queue has completed 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)); } } } } } } } this._emitting = false; this._processRemovalQueue(); return this; }, /** * If events are cleared with the off() method while the event emitter is * actively processing any events then the off() calls get added to a * queue to be executed after the event emitter is finished. This stops * errors that might occur by potentially modifying the event queue while * the emitter is running through them. This method is called after the * event emitter is finished processing. * @private */ _processRemovalQueue: function () { var i; if (this._eventRemovalQueue && this._eventRemovalQueue.length) { // Execute each removal call for (i = 0; i < this._eventRemovalQueue.length; i++) { this._eventRemovalQueue[i](); } // Clear the removal queue this._eventRemovalQueue = []; } }, /** * 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":33}],26:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; if (sourceType === 'object' && source === null) { sourceType = 'null'; } if (testType === 'object' && test === null) { testType = 'null'; } options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number' || sourceType === 'null') && (testType === 'string' || testType === 'number' || testType === 'null')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number' || sourceType === 'null' || testType === 'null') { // Number or null comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; }, /** * * @param {Array | Object} docArr An array of objects to run the join * operation against or a single object. * @param {Array} joinClause The join clause object array (the array in * the $join key of a normal join options object). * @param {Object} joinSource An object containing join source reference * data or a blank object if you are doing a bespoke join operation. * @param {Object} options An options object or blank object if no options. * @returns {Array} * @private */ applyJoin: function (docArr, joinClause, joinSource, options) { var self = this, joinSourceIndex, joinSourceKey, joinMatch, joinSourceType, joinSourceIdentifier, resultKeyName, joinSourceInstance, resultIndex, joinSearchQuery, joinMulti, joinRequire, joinPrefix, joinMatchIndex, joinMatchData, joinSearchOptions, joinFindResults, joinFindResult, joinItem, resultRemove = [], l; if (!(docArr instanceof Array)) { // Turn the document into an array docArr = [docArr]; } for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) { for (joinSourceKey in joinClause[joinSourceIndex]) { if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) { // Get the match data for the join joinMatch = joinClause[joinSourceIndex][joinSourceKey]; // Check if the join is to a collection (default) or a specified source type // e.g 'view' or 'collection' joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; // Set the key to store the join result in to the collection name by default // can be overridden by the '$as' clause in the join object resultKeyName = joinSourceKey; // Get the join collection instance from the DB if (joinSource[joinSourceIdentifier]) { // We have a joinSource for this identifier already (given to us by // an index when we analysed the query earlier on) and we can use // that source instead. joinSourceInstance = joinSource[joinSourceIdentifier]; } else { // We do not already have a joinSource so grab the instance from the db if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') { joinSourceInstance = this._db[joinSourceType](joinSourceKey); } } // Loop our result data array for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultKeyName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultKeyName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = docArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultIndex); } } } } } return resultRemove; }, /** * Takes a query object with dynamic references and converts the references * into actual values from the references source. * @param {Object} query The query object with dynamic references. * @param {Object} item The document to apply the references to. * @returns {*} * @private */ resolveDynamicQuery: function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; // Check for early exit conditions if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3)); } else { pathResult = this.sharedPathSolver.value(item, query); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self.resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }, spliceArrayByIndexList: function (arr, list) { var i; for (i = list.length - 1; i >= 0; i--) { arr.splice(list[i], 1); } } }; module.exports = Matching; },{}],27:[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; },{}],28:[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; },{}],29:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * When called in a before phase the newDoc object can be directly altered * to modify the data in it before the operation is carried out. * @callback addTriggerCallback * @param {Object} operation The details about the operation. * @param {Object} oldDoc The document before the operation. * @param {Object} newDoc The document after the operation. */ /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Constants} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Constants} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {addTriggerCallback} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { self.triggerStack = {}; // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, /** * Tells the current instance to fire or ignore all triggers whether they * are enabled or not. * @param {Boolean} val Set to true to ignore triggers or false to not * ignore them. * @returns {*} */ ignoreTriggers: function (val) { if (val !== undefined) { this._ignoreTriggers = val; return this; } return this._ignoreTriggers; }, /** * Generates triggers that fire in the after phase for all CRUD ops * that automatically transform data back and forth and keep both * import and export collections in sync with each other. * @param {String} id The unique id for this link IO. * @param {Object} ioData The settings for the link IO. */ addLinkIO: function (id, ioData) { var self = this, matchAll, exportData, importData, exportTriggerMethod, importTriggerMethod, exportTo, importFrom, allTypes, i; // Store the linkIO self._linkIO = self._linkIO || {}; self._linkIO[id] = ioData; exportData = ioData['export']; importData = ioData['import']; if (exportData) { exportTo = self.db().collection(exportData.to); } if (importData) { importFrom = self.db().collection(importData.from); } allTypes = [ self.TYPE_INSERT, self.TYPE_UPDATE, self.TYPE_REMOVE ]; matchAll = function (data, callback) { // Match all callback(false, true); }; if (exportData) { // Check for export match method if (!exportData.match) { // No match method found, use the match all method exportData.match = matchAll; } // Check for export types if (!exportData.types) { exportData.types = allTypes; } exportTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data exportData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) exportData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert exportTo.upsert(data, callback); } else { // Do remove exportTo.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (importData) { // Check for import match method if (!importData.match) { // No match method found, use the match all method importData.match = matchAll; } // Check for import types if (!importData.types) { importData.types = allTypes; } importTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data importData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) importData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert self.upsert(data, callback); } else { // Do remove self.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.addTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.PHASE_AFTER, exportTriggerMethod); } } if (importData) { for (i = 0; i < importData.types.length; i++) { importFrom.addTrigger(id + 'import' + importData.types[i], importData.types[i], self.PHASE_AFTER, importTriggerMethod); } } }, /** * Removes a previously added link IO via it's ID. * @param {String} id The id of the link IO to remove. * @returns {boolean} True if successful, false if the link IO * was not found. */ removeLinkIO: function (id) { var self = this, linkIO = self._linkIO[id], exportData, importData, importFrom, i; if (linkIO) { exportData = linkIO['export']; importData = linkIO['import']; if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.removeTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.db.PHASE_AFTER); } } if (importData) { importFrom = self.db().collection(importData.from); for (i = 0; i < importData.types.length; i++) { importFrom.removeTrigger(id + 'import' + importData.types[i], importData.types[i], self.db.PHASE_AFTER); } } delete self._linkIO[id]; return true; } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (!this._ignoreTriggers && this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response, typeName, phaseName; if (!self._ignoreTriggers && self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (self.debug()) { switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } console.log('Triggers: Processing trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Check if the trigger is already in the stack, if it is, // don't fire it again (this is so we avoid infinite loops // where a trigger triggers another trigger which calls this // one and so on) if (self.triggerStack && self.triggerStack[type] && self.triggerStack[type][phase] && self.triggerStack[type][phase][triggerItem.id]) { // The trigger is already in the stack, do not fire the trigger again if (self.debug()) { console.log('Triggers: Will not run trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '" as it is already in the stack!'); } continue; } // Add the trigger to the stack so we don't go down an endless // trigger loop self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = true; // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Remove the trigger from the stack self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = false; // Check the response for a non-expected result (anything other than // [undefined, true or false] is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":33}],30:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],31:[function(_dereq_,module,exports){ "use strict"; // Tell JSHint about EventSource /*global EventSource */ // Import external names locally var Shared = _dereq_('./Shared'), Core, CoreInit, Collection, NodeApiClient, Overload; NodeApiClient = function () { this.init.apply(this, arguments); }; /** * The init method that can be overridden or extended. * @param {Core} core The ForerunnerDB core instance. */ NodeApiClient.prototype.init = function (core) { var self = this; self._core = core; self.rootPath('/fdb'); }; Shared.addModule('NodeApiClient', NodeApiClient); Shared.mixin(NodeApiClient.prototype, 'Mixin.Common'); Shared.mixin(NodeApiClient.prototype, 'Mixin.Events'); Shared.mixin(NodeApiClient.prototype, 'Mixin.ChainReactor'); Core = Shared.modules.Core; CoreInit = Core.prototype.init; Collection = Shared.modules.Collection; Overload = Shared.overload; Shared.synthesize(NodeApiClient.prototype, 'rootPath'); /** * Set the url of the server to use for API. * @name server * @param {String} host The server host name including protocol. E.g. * "https://0.0.0.0". * @param {String} port The server port number e.g. "8080". */ NodeApiClient.prototype.server = function (host, port) { if (host !== undefined) { if (host.substr(host.length - 1, 1) === '/') { // Strip trailing / host = host.substr(0, host.length - 1); } if (port !== undefined) { this._server = host + ":" + port; } else { this._server = host; } this._host = host; this._port = port; return this; } if (port !== undefined) { return { host: this._host, port: this._port, url: this._server }; } else { return this._server; } }; NodeApiClient.prototype.http = function (method, url, data, options, callback) { var self = this, finalUrl, sessionData, bodyData, xmlHttp = new XMLHttpRequest(); method = method.toUpperCase(); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState === 4) { if (xmlHttp.status === 200) { // Tell the callback about success if (xmlHttp.responseText) { callback(false, self.jParse(xmlHttp.responseText)); } else { callback(false, {}); } } else if (xmlHttp.status === 204) { callback(false, {}); } else { // Tell the callback about the error callback(xmlHttp.status, xmlHttp.responseText); // Emit the error code self.emit('httpError', xmlHttp.status, xmlHttp.responseText); } } }; switch (method) { case 'GET': case 'DELETE': case 'HEAD': // Check for global auth if (this._sessionData) { data = data !== undefined ? data : {}; // Add the session data to the key specified data[this._sessionData.key] = this._sessionData.obj; } finalUrl = url + (data !== undefined ? '?' + self.jStringify(data) : ''); bodyData = null; break; case 'POST': case 'PUT': case 'PATCH': // Check for global auth if (this._sessionData) { sessionData = {}; // Add the session data to the key specified sessionData[this._sessionData.key] = this._sessionData.obj; } finalUrl = url + (sessionData !== undefined ? '?' + self.jStringify(sessionData) : ''); bodyData = (data !== undefined ? self.jStringify(data) : null); break; default: return false; } xmlHttp.open(method, finalUrl, true); xmlHttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xmlHttp.send(bodyData); return this; }; // Define HTTP helper methods NodeApiClient.prototype.head = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('HEAD', this.server() + this._rootPath + path, data, options, callback); } }); NodeApiClient.prototype.get = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('GET', this.server() + this._rootPath + path, data, options, callback); } }); NodeApiClient.prototype.put = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('PUT', this.server() + this._rootPath + path, data, options, callback); } }); NodeApiClient.prototype.post = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('POST', this.server() + this._rootPath + path, data, options, callback); } }); NodeApiClient.prototype.patch = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('PATCH', this.server() + this._rootPath + path, data, options, callback); } }); NodeApiClient.prototype.postPatch = function (path, id, data, options, callback) { var self = this; // Determine if the item exists or not this.head(path + '/' + id, undefined, {}, function (err, headData) { if (err) { if (err === 404) { // Item does not exist, run post return self.http('POST', self.server() + self._rootPath + path, data, options, callback); } else { callback(err, data); } } else { // Item already exists, run patch return self.http('PATCH', self.server() + self._rootPath + path + '/' + id, data, options, callback); } }); }; NodeApiClient.prototype.delete = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('DELETE', this.server() + this._rootPath + path, data, options, callback); } }); /** * Gets/ sets a global object that will be sent up with client * requests to the API or REST server. * @param {String} key The key to send the session object up inside. * @param {*} obj The object / value to send up with all requests. If * a request has its own data to send up, this session data will be * mixed in to the request data under the specified key. */ NodeApiClient.prototype.session = function (key, obj) { if (key !== undefined && obj !== undefined) { this._sessionData = { key: key, obj: obj }; return this; } return this._sessionData; }; /** * Initiates a client connection to the API server. * @param collectionInstance * @param path * @param query * @param options * @param callback */ NodeApiClient.prototype.sync = function (collectionInstance, path, query, options, callback) { var self = this, source, finalPath, queryParams, queryString = '', connecting = true; if (this.debug()) { console.log(this.logIdentifier() + ' Connecting to API server ' + this.server() + this._rootPath + path); } finalPath = this.server() + this._rootPath + path + '/_sync'; // Check for global auth if (this._sessionData) { queryParams = queryParams || {}; if (this._sessionData.key) { // Add the session data to the key specified queryParams[this._sessionData.key] = this._sessionData.obj; } else { // Add the session data to the root query object Shared.mixin(queryParams, this._sessionData.obj); } } if (query) { queryParams = queryParams || {}; queryParams.$query = query; } if (options) { queryParams = queryParams || {}; if (options.$initialData === undefined) { options.$initialData = true; } queryParams.$options = options; } if (queryParams) { queryString = this.jStringify(queryParams); finalPath += '?' + queryString; } source = new EventSource(finalPath); collectionInstance.__apiConnection = source; source.addEventListener('open', function (e) { if (!options || (options && options.$initialData)) { // The connection is open, grab the initial data self.get(path, queryParams, function (err, data) { if (!err) { collectionInstance.upsert(data); } }); } }, false); source.addEventListener('error', function (e) { if (source.readyState === 2) { // The connection is dead, remove the connection collectionInstance.unSync(); } if (connecting) { connecting = false; callback(e); } }, false); source.addEventListener('insert', function(e) { var data = self.jParse(e.data); collectionInstance.insert(data.dataSet); }, false); source.addEventListener('update', function(e) { var data = self.jParse(e.data); collectionInstance.update(data.query, data.update); }, false); source.addEventListener('remove', function(e) { var data = self.jParse(e.data); collectionInstance.remove(data.query); }, false); if (callback) { source.addEventListener('connected', function (e) { if (connecting) { connecting = false; callback(false); } }, false); } }; Collection.prototype.sync = new Overload({ /** * Sync with this collection on the server-side. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'function': function (callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + this.name(), null, null, callback); }, /** * Sync with this collection on the server-side. * @param {String} collectionName The collection to sync from. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, function': function (collectionName, callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + collectionName, null, null, callback); }, /** * Sync with this collection on the server-side. * @param {Object} query A query object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'object, function': function (query, callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + this.name(), query, null, callback); }, /** * Sync with this collection on the server-side. * @param {String} objectType The type of object to sync to e.g. * "collection" or "view". * @param {String} objectName The name of the object to sync from. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, string, function': function (objectType, objectName, callback) { this.$main.call(this, '/' + this._db.name() + '/' + objectType + '/' + objectName, null, null, callback); }, /** * Sync with this collection on the server-side. * @param {String} collectionName The collection to sync from. * @param {Object} query A query object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, object, function': function (collectionName, query, callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + collectionName, query, null, callback); }, /** * Sync with this collection on the server-side. * @param {String} objectType The type of object to sync to e.g. * "collection" or "view". * @param {String} objectName The name of the object to sync from. * @param {Object} query A query object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, string, object, function': function (objectType, objectName, query, callback) { this.$main.call(this, '/' + this._db.name() + '/' + objectType + '/' + objectName, query, null, callback); }, /** * Sync with this collection on the server-side. * @param {Object} query A query object. * @param {Object} options An options object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'object, object, function': function (query, options, callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + this.name(), query, options, callback); }, /** * Sync with this collection on the server-side. * @param {String} collectionName The collection to sync from. * @param {Object} query A query object. * @param {Object} options An options object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, object, object, function': function (collectionName, query, options, callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + collectionName, query, options, callback); }, /** * Sync with this collection on the server-side. * @param {String} objectType The type of object to sync to e.g. * "collection" or "view". * @param {String} objectName The name of the object to sync from. * @param {Object} query A query object. * @param {Object} options An options object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, string, object, object, function': function (objectType, objectName, query, options, callback) { this.$main.call(this, '/' + this._db.name() + '/' + objectType + '/' + objectName, query, options, callback); }, '$main': function (path, query, options, callback) { var self = this; if (this._db && this._db._core) { // Kill any existing sync connection this.unSync(); // Create new sync connection this._db._core.api.sync(this, path, query, options, callback); // Hook on drop to call unsync this.on('drop', function () { self.unSync(); }); } else { throw(this.logIdentifier() + ' Cannot sync for an anonymous collection! (Collection must be attached to a database)'); } } }); /** * Disconnects an existing connection to a sync server. * @returns {boolean} True if a connection existed, false * if no connection existed. */ Collection.prototype.unSync = function () { if (this.__apiConnection) { if (this.__apiConnection.readyState !== 2) { this.__apiConnection.close(); } delete this.__apiConnection; return true; } return false; }; Collection.prototype.http = new Overload({ 'string, function': function (method, callback) { this.$main.call(this, method, '/' + this._db.name() + '/collection/' + this.name(), undefined, undefined, {}, callback); }, '$main': function (method, path, queryObj, queryOptions, options, callback) { if (this._db && this._db._core) { return this._db._core.api.http('GET', this._db._core.api.server() + this._rootPath + path, {"$query": queryObj, "$options": queryOptions}, options, callback); } else { throw(this.logIdentifier() + ' Cannot do HTTP for an anonymous collection! (Collection must be attached to a database)'); } } }); Collection.prototype.autoHttp = new Overload({ 'string, function': function (method, callback) { this.$main.call(this, method, '/' + this._db.name() + '/collection/' + this.name(), undefined, undefined, {}, callback); }, 'string, string, function': function (method, collectionName, callback) { this.$main.call(this, method, '/' + this._db.name() + '/collection/' + collectionName, undefined, undefined, {}, callback); }, 'string, string, string, function': function (method, objType, objName, callback) { this.$main.call(this, method, '/' + this._db.name() + '/' + objType + '/' + objName, undefined, undefined, {}, callback); }, 'string, string, string, object, function': function (method, objType, objName, queryObj, callback) { this.$main.call(this, method, '/' + this._db.name() + '/' + objType + '/' + objName, queryObj, undefined, {}, callback); }, 'string, string, string, object, object, function': function (method, objType, objName, queryObj, queryOptions, callback) { this.$main.call(this, method, '/' + this._db.name() + '/' + objType + '/' + objName, queryObj, queryOptions, {}, callback); }, '$main': function (method, path, queryObj, queryOptions, options, callback) { var self = this; if (this._db && this._db._core) { return this._db._core.api.http('GET', this._db._core.api.server() + this._db._core.api._rootPath + path, {"$query": queryObj, "$options": queryOptions}, options, function (err, data) { var i; if (!err && data) { // Check the type of method we used and operate on the collection accordingly switch (method) { // Find insert case 'GET': self.insert(data); break; // Insert case 'POST': if (data.inserted && data.inserted.length) { self.insert(data.inserted); } break; // Update overwrite case 'PUT': case 'PATCH': if (data instanceof Array) { // Update each document for (i = 0; i < data.length; i++) { self.updateById(data[i]._id, {$overwrite: data[i]}); } } else { // Update single document self.updateById(data._id, {$overwrite: data}); } break; // Remove case 'DELETE': self.remove(data); break; default: // Nothing to do with this method break; } } // Send the data back to the callback callback(err, data); }); } else { throw(this.logIdentifier() + ' Cannot do HTTP for an anonymous collection! (Collection must be attached to a database)'); } } }); // Override the Core init to instantiate the plugin Core.prototype.init = function () { CoreInit.apply(this, arguments); this.api = new NodeApiClient(this); }; Shared.finishModule('NodeApiClient'); module.exports = NodeApiClient; },{"./Shared":41}],32:[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":35,"./Shared":41}],33:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {String=} name A name to provide this overload to help identify * it if any errors occur during the resolving phase of the overload. This * is purely for debug purposes and serves no functional purpose. * @param {Object} def The overload definition. * @returns {Function} * @constructor */ var Overload = function (name, def) { if (!def) { def = name; name = undefined; } if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, overloadName; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload Definition:', def); throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['array', 'string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],34:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, DbDocument; Shared = _dereq_('./Shared'); var Overview = function () { this.init.apply(this, arguments); }; Overview.prototype.init = function (name) { var self = this; this._name = name; this._data = new DbDocument('__FDB__dc_data_' + this._name); this._collData = new Collection(); this._sources = []; this._sourceDroppedWrap = function () { self._sourceDropped.apply(self, arguments); }; }; Shared.addModule('Overview', Overview); Shared.mixin(Overview.prototype, 'Mixin.Common'); Shared.mixin(Overview.prototype, 'Mixin.ChainReactor'); Shared.mixin(Overview.prototype, 'Mixin.Constants'); Shared.mixin(Overview.prototype, 'Mixin.Triggers'); Shared.mixin(Overview.prototype, 'Mixin.Events'); Shared.mixin(Overview.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); DbDocument = _dereq_('./Document'); Db = Shared.modules.Db; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Overview.prototype, 'state'); Shared.synthesize(Overview.prototype, 'db'); Shared.synthesize(Overview.prototype, 'name'); Shared.synthesize(Overview.prototype, 'query', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Shared.synthesize(Overview.prototype, 'queryOptions', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Shared.synthesize(Overview.prototype, 'reduce', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Overview.prototype.from = function (source) { if (source !== undefined) { if (typeof(source) === 'string') { source = this._db.collection(source); } this._setFrom(source); return this; } return this._sources; }; Overview.prototype.find = function () { return this._collData.find.apply(this._collData, arguments); }; /** * Executes and returns the response from the current reduce method * assigned to the overview. * @returns {*} */ Overview.prototype.exec = function () { var reduceFunc = this.reduce(); return reduceFunc ? reduceFunc.apply(this) : undefined; }; Overview.prototype.count = function () { return this._collData.count.apply(this._collData, arguments); }; Overview.prototype._setFrom = function (source) { // Remove all source references while (this._sources.length) { this._removeSource(this._sources[0]); } this._addSource(source); return this; }; Overview.prototype._addSource = function (source) { if (source && source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.data(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } if (this._sources.indexOf(source) === -1) { this._sources.push(source); source.chain(this); source.on('drop', this._sourceDroppedWrap); this._refresh(); } return this; }; Overview.prototype._removeSource = function (source) { if (source && source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.data(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } var sourceIndex = this._sources.indexOf(source); if (sourceIndex > -1) { this._sources.splice(source, 1); source.unChain(this); source.off('drop', this._sourceDroppedWrap); this._refresh(); } return this; }; Overview.prototype._sourceDropped = function (source) { if (source) { // Source was dropped, remove from overview this._removeSource(source); } }; Overview.prototype._refresh = function () { if (!this.isDropped()) { if (this._sources && this._sources[0]) { this._collData.primaryKey(this._sources[0].primaryKey()); var tempArr = [], i; for (i = 0; i < this._sources.length; i++) { tempArr = tempArr.concat(this._sources[i].find(this._query, this._queryOptions)); } this._collData.setData(tempArr); } // Now execute the reduce method if (this._reduce) { var reducedData = this._reduce.apply(this); // Update the document with the newly returned data this._data.setData(reducedData); } } }; Overview.prototype._chainHandler = function (chainPacket) { switch (chainPacket.type) { case 'setData': case 'insert': case 'update': case 'remove': this._refresh(); break; default: break; } }; /** * Gets the module's internal data collection. * @returns {Collection} */ Overview.prototype.data = function () { return this._data; }; Overview.prototype.drop = function (callback) { if (!this.isDropped()) { this._state = 'dropped'; delete this._data; delete this._collData; // Remove all source references while (this._sources.length) { this._removeSource(this._sources[0]); } delete this._sources; if (this._db && this._name) { delete this._db._overview[this._name]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._listeners; } return true; }; Db.prototype.overview = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof Overview) { return name; } if (this._overview && this._overview[name]) { return this._overview[name]; } this._overview = this._overview || {}; this._overview[name] = new Overview(name).db(this); self.emit('create', self._overview[name], 'overview', name); return this._overview[name]; } else { // Return an object of collection data return this._overview || {}; } }; /** * Returns an array of overviews the DB currently has. * @returns {Array} An array of objects containing details of each overview * the database is currently managing. */ Db.prototype.overviews = function () { var arr = [], item, i; for (i in this._overview) { if (this._overview.hasOwnProperty(i)) { item = this._overview[i]; arr.push({ name: i, count: item.count(), linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Overview'); module.exports = Overview; },{"./Collection":7,"./Document":12,"./Shared":41}],35:[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":41}],36:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared = _dereq_('./Shared'), async = _dereq_('async'), localforage = _dereq_('localforage'), FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line Db, Collection, CollectionDrop, CollectionGroup, CollectionInit, DbInit, DbDrop, Persist, Overload;//, //DataVersion = '2.0'; /** * The persistent storage class handles loading and saving data to browser * storage. * @constructor */ Persist = function () { this.init.apply(this, arguments); }; /** * The local forage library. */ Persist.prototype.localforage = localforage; /** * The init method that can be overridden or extended. * @param {Db} db The ForerunnerDB database instance. */ Persist.prototype.init = function (db) { var self = this; this._encodeSteps = [ function () { return self._encode.apply(self, arguments); } ]; this._decodeSteps = [ function () { return self._decode.apply(self, arguments); } ]; // Check environment if (db.isClient()) { if (window.Storage !== undefined) { this.mode('localforage'); localforage.config({ driver: [ localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE ], name: String(db.core().name()), storeName: 'FDB' }); } } }; Shared.addModule('Persist', Persist); Shared.mixin(Persist.prototype, 'Mixin.ChainReactor'); Shared.mixin(Persist.prototype, 'Mixin.Common'); Db = Shared.modules.Db; Collection = _dereq_('./Collection'); CollectionDrop = Collection.prototype.drop; CollectionGroup = _dereq_('./CollectionGroup'); CollectionInit = Collection.prototype.init; DbInit = Db.prototype.init; DbDrop = Db.prototype.drop; Overload = Shared.overload; /** * Gets / sets the auto flag which determines if the persistence module * will automatically load data for collections the first time they are * accessed and save data whenever it changes. This is disabled by * default. * @param {Boolean} val Set to true to enable, false to disable * @returns {*} */ Shared.synthesize(Persist.prototype, 'auto', function (val) { var self = this; if (val !== undefined) { if (val) { // Hook db events this._db.on('create', function () { self._autoLoad.apply(self, arguments); }); this._db.on('change', function () { self._autoSave.apply(self, arguments); }); if (this._db.debug()) { console.log(this._db.logIdentifier() + ' Automatic load/save enabled'); } } else { // Un-hook db events this._db.off('create', this._autoLoad); this._db.off('change', this._autoSave); if (this._db.debug()) { console.log(this._db.logIdentifier() + ' Automatic load/save disbled'); } } } return this.$super.call(this, val); }); Persist.prototype._autoLoad = function (obj, objType, name) { var self = this; if (typeof obj.load === 'function') { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-loading data for ' + objType + ':', name); } obj.load(function (err, data) { if (err && self._db.debug()) { console.log(self._db.logIdentifier() + ' Automatic load failed:', err); } self.emit('load', err, data); }); } else { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-load for ' + objType + ':', name, 'no load method, skipping'); } } }; Persist.prototype._autoSave = function (obj, objType, name) { var self = this; if (typeof obj.save === 'function') { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-saving data for ' + objType + ':', name); } obj.save(function (err, data) { if (err && self._db.debug()) { console.log(self._db.logIdentifier() + ' Automatic save failed:', err); } self.emit('save', err, data); }); } }; /** * Gets / sets the persistent storage mode (the library used * to persist data to the browser - defaults to localForage). * @param {String} type The library to use for storage. Defaults * to localForage. * @returns {*} */ Persist.prototype.mode = function (type) { if (type !== undefined) { this._mode = type; return this; } return this._mode; }; /** * Gets / sets the driver used when persisting data. * @param {String} val Specify the driver type (LOCALSTORAGE, * WEBSQL or INDEXEDDB) * @returns {*} */ Persist.prototype.driver = function (val) { if (val !== undefined) { switch (val.toUpperCase()) { case 'LOCALSTORAGE': localforage.setDriver(localforage.LOCALSTORAGE); break; case 'WEBSQL': localforage.setDriver(localforage.WEBSQL); break; case 'INDEXEDDB': localforage.setDriver(localforage.INDEXEDDB); break; default: throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!'); } return this; } return localforage.driver(); }; /** * Starts a decode waterfall process. * @param {*} val The data to be decoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.decode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._decodeSteps), finished); }; /** * Starts an encode waterfall process. * @param {*} val The data to be encoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.encode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._encodeSteps), finished); }; Shared.synthesize(Persist.prototype, 'encodeSteps'); Shared.synthesize(Persist.prototype, 'decodeSteps'); /** * Adds an encode/decode step to the persistent storage system so * that you can add custom functionality. * @param {Function} encode The encode method called with the data from the * previous encode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the encoder will fail and throw an error. * @param {Function} decode The decode method called with the data from the * previous decode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the decoder will fail and throw an error. * @param {Number=} index Optional index to add the encoder step to. This * allows you to place a step before or after other existing steps. If not * provided your step is placed last in the list of steps. For instance if * you are providing an encryption step it makes sense to place this last * since all previous steps will then have their data encrypted by your * final step. */ Persist.prototype.addStep = new Overload({ 'object': function (obj) { this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0); }, 'function, function': function (encode, decode) { this.$main.call(this, encode, decode, 0); }, 'function, function, number': function (encode, decode, index) { this.$main.call(this, encode, decode, index); }, $main: function (encode, decode, index) { if (index === 0 || index === undefined) { this._encodeSteps.push(encode); this._decodeSteps.unshift(decode); } else { // Place encoder step at index then work out correct // index to place decoder step this._encodeSteps.splice(index, 0, encode); this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode); } } }); Persist.prototype.unwrap = function (dataStr) { var parts = dataStr.split('::fdb::'), data; switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } }; /** * Takes encoded data and decodes it for use as JS native objects and arrays. * @param {String} val The currently encoded string data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when decoding is * completed. * @private */ Persist.prototype._decode = function (val, meta, finished) { var parts, data; if (val) { parts = val.split('::fdb::'); switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } if (data) { meta.foundData = true; meta.rowCount = data.length || 0; } else { meta.foundData = false; meta.rowCount = 0; } if (finished) { finished(false, data, meta); } } else { meta.foundData = false; meta.rowCount = 0; if (finished) { finished(false, val, meta); } } }; /** * Takes native JS data and encodes it for for storage as a string. * @param {Object} val The current un-encoded data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when encoding is * completed. * @private */ Persist.prototype._encode = function (val, meta, finished) { var data = val; if (typeof val === 'object') { val = 'json::fdb::' + this.jStringify(val); } else { val = 'raw::fdb::' + val; } if (data) { meta.foundData = true; meta.rowCount = data.length || 0; } else { meta.foundData = false; meta.rowCount = 0; } if (finished) { finished(false, val, meta); } }; /** * Encodes passed data and then stores it in the browser's persistent * storage layer. * @param {String} key The key to store the data under in the persistent * storage. * @param {Object} data The data to store under the key. * @param {Function=} callback The method to call when the save process * has completed. */ Persist.prototype.save = function (key, data, callback) { switch (this.mode()) { case 'localforage': this.encode(data, function (err, data, tableStats) { if (!err) { localforage.setItem(key, data).then(function (data) { if (callback) { callback(false, data, tableStats); } }, function (err) { if (callback) { callback(err); } }); } else { callback(err); } }); break; default: if (callback) { callback('No data handler.'); } break; } }; /** * Loads and decodes data from the passed key. * @param {String} key The key to retrieve data from in the persistent * storage. * @param {Function=} callback The method to call when the load process * has completed. */ Persist.prototype.load = function (key, callback) { var self = this; switch (this.mode()) { case 'localforage': localforage.getItem(key).then(function (val) { self.decode(val, callback); }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; /** * Deletes data in persistent storage stored under the passed key. * @param {String} key The key to drop data for in the storage. * @param {Function=} callback The method to call when the data is dropped. */ Persist.prototype.drop = function (key, callback) { switch (this.mode()) { case 'localforage': localforage.removeItem(key).then(function () { if (callback) { callback(false); } }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; // Extend the Collection prototype with persist methods Collection.prototype.drop = new Overload({ /** * Drop collection and persistent storage. */ '': function () { if (!this.isDropped()) { this.drop(true); } }, /** * Drop collection and persistent storage with callback. * @param {Function} callback Callback method. */ 'function': function (callback) { if (!this.isDropped()) { this.drop(true, callback); } }, /** * Drop collection and optionally drop persistent storage. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. */ 'boolean': function (removePersistent) { if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name); this._db.persist.drop(this._db._name + '-' + this._name + '-metaData'); } } else { throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } // Call the original method CollectionDrop.call(this); } }, /** * Drop collections and optionally drop persistent storage with callback. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. * @param {Function} callback Callback method. */ 'boolean, function': function (removePersistent, callback) { var self = this; if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name, function () { self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback); }); return CollectionDrop.call(this); } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); } } } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } } else { // Call the original method return CollectionDrop.call(this, callback); } } } }); /** * Saves an entire collection's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ Collection.prototype.save = function (callback) { var self = this, processSave; if (self._name) { if (self._db) { processSave = function () { // Save the collection data self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, tableData, tableStats) { if (!err) { self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, metaData, metaStats) { if (callback) { callback(err, tableStats, metaStats, { tableData: tableData, metaData: metaData, tableDataName: self._db._name + '-' + self._name, metaDataName: self._db._name + '-' + self._name + '-metaData' }); } }); } else { if (callback) { callback(err); } } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads an entire collection's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ Collection.prototype.load = function (callback) { var self = this; if (self._name) { if (self._db) { // Load the collection data self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) { if (!err) { // Remove all previous data self.remove({}, function () { // Now insert the new data data = data || []; self.insert(data, function () { // Now load the collection's metadata self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); } } if (callback) { callback(err, tableStats, metaStats); } }); }); //self.setData(data); }); } else { if (callback) { callback(err); } } }); } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; /** * Gets the data that represents this collection for easy storage using * a third-party method / plugin instead of using the standard persistent * storage system. * @param {Function} callback The method to call with the data response. */ Collection.prototype.saveCustom = function (callback) { var self = this, myData = {}, processSave; if (self._name) { if (self._db) { processSave = function () { self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.data = { name: self._db._name + '-' + self._name, store: data, tableStats: tableStats }; self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.metaData = { name: self._db._name + '-' + self._name + '-metaData', store: data, tableStats: tableStats }; callback(false, myData); } else { callback(err); } }); } else { callback(err); } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads custom data loaded by a third-party plugin into the collection. * @param {Object} myData Data object previously saved by using saveCustom() * @param {Function} callback A callback method to receive notification when * data has loaded. */ Collection.prototype.loadCustom = function (myData, callback) { var self = this; if (self._name) { if (self._db) { if (myData.data && myData.data.store) { if (myData.metaData && myData.metaData.store) { self.decode(myData.data.store, function (err, data, tableStats) { if (!err) { if (data) { // Remove all previous data self.remove({}); self.insert(data); self.decode(myData.metaData.store, function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); if (callback) { callback(err, tableStats, metaStats); } } } else { callback(err); } }); } } else { callback(err); } }); } else { callback('No "metaData" key found in passed object!'); } } else { callback('No "data" key found in passed object!'); } } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; // Override the DB init to instantiate the plugin Db.prototype.init = function () { DbInit.apply(this, arguments); this.persist = new Persist(this); }; Db.prototype.load = new Overload({ /** * Loads an entire database's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (myData, callback) { this.$main.call(this, myData, callback); }, '$main': function (myData, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, loadCallback, index; loadCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection load method if (!myData) { obj[index].load(loadCallback); } else { obj[index].loadCustom(myData, loadCallback); } } } } }); Db.prototype.save = new Overload({ /** * Saves an entire database's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (options, callback) { this.$main.call(this, options, callback); }, '$main': function (options, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, saveCallback, index; saveCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection save method if (!options.custom) { obj[index].save(saveCallback); } else { obj[index].saveCustom(saveCallback); } } } } }); Shared.finishModule('Persist'); module.exports = Persist; },{"./Collection":7,"./CollectionGroup":8,"./PersistCompress":37,"./PersistCrypto":38,"./Shared":41,"async":45,"localforage":83}],37:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), pako = _dereq_('pako'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); Plugin.prototype.encode = function (val, meta, finished) { var wrapper = { data: val, type: 'fdbCompress', enabled: false }, before, after, compressedVal; // Compress the data before = val.length; compressedVal = pako.deflate(val, {to: 'string'}); after = compressedVal.length; // If the compressed version is smaller than the original, use it! if (after < before) { wrapper.data = compressedVal; wrapper.enabled = true; } meta.compression = { enabled: wrapper.enabled, compressedBytes: after, uncompressedBytes: before, effect: Math.round((100 / before) * after) + '%' }; finished(false, this.jStringify(wrapper), meta); }; Plugin.prototype.decode = function (wrapper, meta, finished) { var compressionEnabled = false, data; if (wrapper) { wrapper = this.jParse(wrapper); // Check if we need to decompress the string if (wrapper.enabled) { data = pako.inflate(wrapper.data, {to: 'string'}); compressionEnabled = true; } else { data = wrapper.data; compressionEnabled = false; } meta.compression = { enabled: compressionEnabled }; if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, data, meta); } } }; // Register this plugin with ForerunnerDB Shared.plugins.FdbCompress = Plugin; module.exports = Plugin; },{"./Shared":41,"pako":85}],38:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), CryptoJS = _dereq_('crypto-js'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { // Ensure at least a password is passed in options if (!options || !options.pass) { throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.'); } this._algo = options.algo || 'AES'; this._pass = options.pass; }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); /** * Gets / sets the current pass-phrase being used to encrypt / decrypt * data with the plugin. */ Shared.synthesize(Plugin.prototype, 'pass'); Plugin.prototype.stringify = function (cipherParams) { // create json object with ciphertext var jsonObj = { ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64) }; // optionally add iv and salt if (cipherParams.iv) { jsonObj.iv = cipherParams.iv.toString(); } if (cipherParams.salt) { jsonObj.s = cipherParams.salt.toString(); } // stringify json object return this.jStringify(jsonObj); }; Plugin.prototype.parse = function (jsonStr) { // parse json string var jsonObj = this.jParse(jsonStr); // extract ciphertext from json object, and create cipher params object var cipherParams = CryptoJS.lib.CipherParams.create({ ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct) }); // optionally extract iv and salt if (jsonObj.iv) { cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv); } if (jsonObj.s) { cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s); } return cipherParams; }; Plugin.prototype.encode = function (val, meta, finished) { var self = this, wrapper = { type: 'fdbCrypto' }, encryptedVal; // Encrypt the data encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }); wrapper.data = encryptedVal.toString(); wrapper.enabled = true; meta.encryption = { enabled: wrapper.enabled }; if (finished) { finished(false, this.jStringify(wrapper), meta); } }; Plugin.prototype.decode = function (wrapper, meta, finished) { var self = this, data; if (wrapper) { wrapper = this.jParse(wrapper); data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }).toString(CryptoJS.enc.Utf8); if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, wrapper, meta); } } }; // Register this plugin with ForerunnerDB Shared.plugins.FdbCrypto = Plugin; module.exports = Plugin; },{"./Shared":41,"crypto-js":54}],39:[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":41}],40:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { var self = this; this._encoder = []; this._decoder = []; // Handler for Date() objects this.registerHandler('$date', function (objInstance) { if (objInstance instanceof Date) { // Augment this date object with a new toJSON method objInstance.toJSON = function () { return "$date:" + this.toISOString(); }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$date:') === 0) { return self.convert(new Date(data.substr(6))); } return undefined; }); // Handler for RegExp() objects this.registerHandler('$regexp', function (objInstance) { if (objInstance instanceof RegExp) { objInstance.toJSON = function () { return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : ''); /*return { source: this.source, params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '') };*/ }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$regexp:') === 0) { var dataStr = data.substr(8),//± lengthEnd = dataStr.indexOf(':'), sourceLength = Number(dataStr.substr(0, lengthEnd)), source = dataStr.substr(lengthEnd + 1, sourceLength), params = dataStr.substr(lengthEnd + sourceLength + 2); return self.convert(new RegExp(source, params)); } return undefined; }); }; Serialiser.prototype.registerHandler = function (handles, encoder, decoder) { if (handles !== undefined) { // Register encoder this._encoder.push(encoder); // Register decoder this._decoder.push(decoder); } }; Serialiser.prototype.convert = function (data) { // Run through converters and check for match var arr = this._encoder, i; for (i = 0; i < arr.length; i++) { if (arr[i](data)) { // The converter we called matched the object and converted it // so let's return it now. return data; } } // No converter matched the object, return the unaltered one return data; }; Serialiser.prototype.reviver = function () { var arr = this._decoder; return function (key, value) { // Check if we have a decoder method for this key var decodedData, i; for (i = 0; i < arr.length; i++) { decodedData = arr[i](value); if (decodedData !== undefined) { // The decoder we called matched the object and decoded it // so let's return it now. return decodedData; } } // No decoder, return basic value return value; }; }; module.exports = Serialiser; },{}],41:[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.794', modules: {}, plugins: {}, index: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":21,"./Mixin.ChainReactor":22,"./Mixin.Common":23,"./Mixin.Constants":24,"./Mixin.Events":25,"./Mixin.Matching":26,"./Mixin.Sorting":27,"./Mixin.Tags":28,"./Mixin.Triggers":29,"./Mixin.Updating":30,"./Overload":33}],42:[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 = {}; },{}],43:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket, Overload = _dereq_('./Overload'), Path, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new view instance. * @param {String} name The name of the view. * @param {Object=} query The view's query. * @param {Object=} options An options object. * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.Matching'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); //Shared.mixin(View.prototype, 'Mixin.Triggers'); Shared.mixin(View.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; Path = Shared.modules.Path; sharedPathSolver = new Path(); View.prototype.init = function (name, query, options) { var self = this; this.sharedPathSolver = sharedPathSolver; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._data = new Collection(this.name() + '_internal'); }; /** * This reactor IO node is given data changes from source data and * then acts as a firewall process between the source and view data. * Data needs to meet the requirements this IO node imposes before * the data is passed down the reactor chain (to the view). This * allows us to intercept data changes from the data source and act * on them such as applying transforms, checking the data matches * the view's query, applying joins to the data etc before sending it * down the reactor chain via the this.chainSend() calls. * * Update packets are especially complex to handle because an update * on the underlying source data could translate into an insert, * update or remove call on the view. Take a scenario where the view's * query limits the data see from the source. If the source data is * updated and the data now falls inside the view's query limitations * the data is technically now an insert on the view, not an update. * The same is true in reverse where the update becomes a remove. If * the updated data already exists in the view and will still exist * after the update operation then the update can remain an update. * @param {Object} chainPacket The chain reactor packet representing the * data operation that has just been processed on the source data. * @param {View} self The reference to the view we are operating for. * @private */ View.prototype._handleChainIO = function (chainPacket, self) { var type = chainPacket.type, hasActiveJoin, hasActiveQuery, hasTransformIn, sharedData; // NOTE: "self" in this context is the view instance. // NOTE: "this" in this context is the ReactorIO node sitting in // between the source (sender) and the destination (listener) and // in this case the source is the view's "from" data source and the // destination is the view's _data collection. This means // that "this.chainSend()" is asking the ReactorIO node to send the // packet on to the destination listener. // EARLY EXIT: Check that the packet is not a CRUD operation if (type !== 'setData' && type !== 'insert' && type !== 'update' && type !== 'remove') { // This packet is NOT a CRUD operation packet so exit early! // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } // We only need to check packets under three conditions // 1) We have a limiting query on the view "active query", // 2) We have a query options with a $join clause on the view "active join" // 3) We have a transformIn operation registered on the view. // If none of these conditions exist we can just allow the chain // packet to proceed as normal hasActiveJoin = Boolean(self._querySettings.options && self._querySettings.options.$join); hasActiveQuery = Boolean(self._querySettings.query); hasTransformIn = self._data._transformIn !== undefined; // EARLY EXIT: Check for any complex operation flags and if none // exist, send the packet on and exit early if (!hasActiveJoin && !hasActiveQuery && !hasTransformIn) { // We don't have any complex operation flags so exit early! // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } // We have either an active query, active join or a transformIn // function registered on the view // We create a shared data object here so that the disparate method // calls can share data with each other via this object whilst // still remaining separate methods to keep code relatively clean. sharedData = { dataArr: [], removeArr: [] }; // Check the packet type to get the data arrays to work on if (chainPacket.type === 'insert') { // Check if the insert data is an array if (chainPacket.data.dataSet instanceof Array) { // Use the insert data array sharedData.dataArr = chainPacket.data.dataSet; } else { // Generate an array from the single insert object sharedData.dataArr = [chainPacket.data.dataSet]; } } else if (chainPacket.type === 'update') { // Use the dataSet array sharedData.dataArr = chainPacket.data.dataSet; } else if (chainPacket.type === 'remove') { if (chainPacket.data.dataSet instanceof Array) { // Use the remove data array sharedData.removeArr = chainPacket.data.dataSet; } else { // Generate an array from the single remove object sharedData.removeArr = [chainPacket.data.dataSet]; } } // Safety check if (!(sharedData.dataArr instanceof Array)) { // This shouldn't happen, let's log it console.warn('WARNING: dataArr being processed by chain reactor in View class is inconsistent!'); sharedData.dataArr = []; } if (!(sharedData.removeArr instanceof Array)) { // This shouldn't happen, let's log it console.warn('WARNING: removeArr being processed by chain reactor in View class is inconsistent!'); sharedData.removeArr = []; } // We need to operate in this order: // 1) Check if there is an active join - active joins are operated // against the SOURCE data. The joined data can potentially be // utilised by any active query or transformIn so we do this step first. // 2) Check if there is an active query - this is a query that is run // against the SOURCE data after any active joins have been resolved // on the source data. This allows an active query to operate on data // that would only exist after an active join has been executed. // If the source data does not fall inside the limiting factors of the // active query then we add it to a removal array. If it does fall // inside the limiting factors when we add it to an upsert array. This // is because data that falls inside the query could end up being // either new data or updated data after a transformIn operation. // 3) Check if there is a transformIn function. If a transformIn function // exist we run it against the data after doing any active join and // active query. if (hasActiveJoin) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin'); } self._handleChainIO_ActiveJoin(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin'); } } if (hasActiveQuery) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery'); } self._handleChainIO_ActiveQuery(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery'); } } if (hasTransformIn) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_TransformIn'); } self._handleChainIO_TransformIn(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_TransformIn'); } } // Check if we still have data to operate on and exit // if there is none left if (!sharedData.dataArr.length && !sharedData.removeArr.length) { // There is no more data to operate on, exit without // sending any data down the chain reactor (return true // will tell reactor to exit without continuing)! return true; } // Grab the public data collection's primary key sharedData.pk = self._data.primaryKey(); // We still have data left, let's work out how to handle it // first let's loop through the removals as these are easy if (sharedData.removeArr.length) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_RemovePackets'); } self._handleChainIO_RemovePackets(this, chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_RemovePackets'); } } if (sharedData.dataArr.length) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets'); } self._handleChainIO_UpsertPackets(this, chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets'); } } // Now return true to tell the chain reactor not to propagate // the data itself as we have done all that work here return true; }; View.prototype._handleChainIO_ActiveJoin = function (chainPacket, sharedData) { var dataArr = sharedData.dataArr, removeArr; // Since we have an active join, all we need to do is operate // the join clause on each item in the packet's data array. removeArr = this.applyJoin(dataArr, this._querySettings.options.$join, {}, {}); // Now that we've run our join keep in mind that joins can exclude data // if there is no matching joined data and the require: true clause in // the join options is enabled. This means we have to store a removal // array that tells us which items from the original data we sent to // join did not match the join data and were set with a require flag. // Now that we have our array of items to remove, let's run through the // original data and remove them from there. this.spliceArrayByIndexList(dataArr, removeArr); // Make sure we add any items we removed to the shared removeArr sharedData.removeArr = sharedData.removeArr.concat(removeArr); }; View.prototype._handleChainIO_ActiveQuery = function (chainPacket, sharedData) { var self = this, dataArr = sharedData.dataArr, i; // Now we need to run the data against the active query to // see if the data should be in the final data list or not, // so we use the _match method. // Loop backwards so we can safely splice from the array // while we are looping for (i = dataArr.length - 1; i >= 0; i--) { if (!self._match(dataArr[i], self._querySettings.query, self._querySettings.options, 'and', {})) { // The data didn't match the active query, add it // to the shared removeArr sharedData.removeArr.push(dataArr[i]); // Now remove it from the shared dataArr dataArr.splice(i, 1); } } }; View.prototype._handleChainIO_TransformIn = function (chainPacket, sharedData) { var self = this, dataArr = sharedData.dataArr, removeArr = sharedData.removeArr, dataIn = self._data._transformIn, i; // At this stage we take the remaining items still left in the data // array and run our transformIn method on each one, modifying it // from what it was to what it should be on the view. We also have // to run this on items we want to remove too because transforms can // affect primary keys and therefore stop us from identifying the // correct items to run removal operations on. // It is important that these are transformed BEFORE they are passed // to the CRUD methods because we use the CU data to check the position // of the item in the array and that can only happen if it is already // pre-transformed. The removal stuff also needs pre-transformed // because ids can be modified by a transform. for (i = 0; i < dataArr.length; i++) { // Assign the new value dataArr[i] = dataIn(dataArr[i]); } for (i = 0; i < removeArr.length; i++) { // Assign the new value removeArr[i] = dataIn(removeArr[i]); } }; View.prototype._handleChainIO_RemovePackets = function (ioObj, chainPacket, sharedData) { var $or = [], pk = sharedData.pk, removeArr = sharedData.removeArr, packet = { dataSet: removeArr, query: { $or: $or } }, orObj, i; for (i = 0; i < removeArr.length; i++) { orObj = {}; orObj[pk] = removeArr[i][pk]; $or.push(orObj); } ioObj.chainSend('remove', packet); }; View.prototype._handleChainIO_UpsertPackets = function (ioObj, chainPacket, sharedData) { var data = this._data, primaryIndex = data._primaryIndex, primaryCrc = data._primaryCrc, pk = sharedData.pk, dataArr = sharedData.dataArr, arrItem, insertArr = [], updateArr = [], query, i; // Let's work out what type of operation this data should // generate between an insert or an update. for (i = 0; i < dataArr.length; i++) { arrItem = dataArr[i]; // Check if the data already exists in the data if (primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (primaryCrc.get(arrItem[pk]) !== this.hash(arrItem[pk])) { // The document exists in the data collection but data differs, update required updateArr.push(arrItem); } } else { // The document is missing from this collection, insert required insertArr.push(arrItem); } } if (insertArr.length) { ioObj.chainSend('insert', { dataSet: insertArr }); } if (updateArr.length) { for (i = 0; i < updateArr.length; i++) { arrItem = updateArr[i]; query = {}; query[pk] = arrItem[pk]; ioObj.chainSend('update', { query: query, update: arrItem, dataSet: [arrItem] }); } } }; /** * Executes an insert against the view's underlying data-source. * @see Collection::insert() */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. * @see Collection::update() */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. * @see Collection::updateById() */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. * @see Collection::remove() */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. * @see Collection::find() * @returns {Array} The result of the find query. */ View.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Queries the view data for a single document. * @see Collection::findOne() * @returns {Object} The result of the find query. */ View.prototype.findOne = function (query, options) { return this._data.findOne(query, options); }; /** * Queries the view data by specific id. * @see Collection::findById() * @returns {Array} The result of the find query. */ View.prototype.findById = function (id, options) { return this._data.findById(id, options); }; /** * Queries the view data in a sub-array. * @see Collection::findSub() * @returns {Array} The result of the find query. */ View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._data.findSub(match, path, subDocQuery, subDocOptions); }; /** * Queries the view data in a sub-array and returns first match. * @see Collection::findSubOne() * @returns {Object} The result of the find query. */ View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this._data.findSubOne(match, path, subDocQuery, subDocOptions); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._data; }; /** * Sets the source from which the view will assemble its data. * @param {Collection|View} source The source to use to assemble view data. * @param {Function=} callback A callback method. * @returns {*} If no argument is passed, returns the current value of from, * otherwise returns itself for chaining. */ View.prototype.from = function (source, callback) { var self = this; if (source !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); // Remove the current reference to the _from since we // are about to replace it with a new one delete this._from; } // Check if we have an existing reactor io that links the // previous _from source to the view's internal data if (this._io) { // Drop the io and remove it this._io.drop(); delete this._io; } // Check if we were passed a source name rather than a // reference to a source object if (typeof(source) === 'string') { // We were passed a name, assume it is a collection and // get the reference to the collection of that name source = this._db.collection(source); } // Check if we were passed a reference to a view rather than // a collection. Views need to be handled slightly differently // since their data is stored in an internal data collection // rather than actually being a direct data source themselves. if (source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source._data; if (this.debug()) { console.log(this.logIdentifier() + ' Using internal data "' + source.instanceIdentifier() + '" for IO graph linking'); } } // Assign the new data source as the view's _from this._from = source; // Hook the new data source's drop event so we can unhook // it as a data source if it gets dropped. This is important // so that we don't run into problems using a dropped source // for active data. this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's _from source and determines how they should be interpreted by // this view. See the _handleChainIO() method which does all the chain packet // processing for the view. this._io = new ReactorIO(this._from, this, function (chainPacket) { return self._handleChainIO.call(this, chainPacket, self); }); // Set the view's internal data primary key to the same as the // current active _from data source this._data.primaryKey(source.primaryKey()); // Do the initial data lookup and populate the view's internal data // since at this point we don't actually have any data in the view // yet. var collData = source.find(this._querySettings.query, this._querySettings.options); this._data.setData(collData, {}, callback); // If we have an active query and that query has an $orderBy clause, // update our active bucket which allows us to keep track of where // data should be placed in our internal data array. This is about // ordering of data and making sure that we maintain an ordered array // so that if we have data-binding we can place an item in the data- // bound view at the correct location. Active buckets use quick-sort // algorithms to quickly determine the position of an item inside an // existing array based on a sort protocol. if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; } return this._from; }; /** * The chain reaction handler method for the view. * @param {Object} chainPacket The chain reaction packet to handle. * @private */ View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, updates, primaryKey, item, currentIndex; if (this.debug()) { console.log(this.logIdentifier() + ' Received chain reactor data: ' + chainPacket.type); } switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._data.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); this._data.setData(collData); // Rebuild active bucket as well this.rebuildActiveBucket(this._querySettings.options); break; case 'insert': if (this.debug()) { console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._data.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Make sure we are working with an array if (!(chainPacket.data.dataSet instanceof Array)) { chainPacket.data.dataSet = [chainPacket.data.dataSet]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data.dataSet; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); this._data._insertHandle(arr[index], insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._data._data.length; this._data._insertHandle(chainPacket.data.dataSet, insertIndex); } break; case 'update': if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._data.name() + '"'); } primaryKey = this._data.primaryKey(); // Do the update updates = this._data._handleUpdate( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._data._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._data._updateSpliceMove(this._data._data, currentIndex, insertIndex); } } } break; case 'remove': if (this.debug()) { console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._data.name() + '"'); } this._data.remove(chainPacket.data.query, chainPacket.options); if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the dataSet and remove the objects from the ActiveBucket arr = chainPacket.data.dataSet; count = arr.length; for (index = 0; index < count; index++) { this._activeBucket.remove(arr[index]); } } break; default: break; } }; /** * Handles when an underlying collection the view is using as a data * source is dropped. * @param {Collection} collection The collection that has been dropped. * @private */ View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; /** * Creates an index on the view. * @see Collection::ensureIndex() * @returns {*} */ View.prototype.ensureIndex = function () { return this._data.ensureIndex.apply(this._data, arguments); }; /** /** * Listens for an event. * @see Mixin.Events::on() */ View.prototype.on = function () { return this._data.on.apply(this._data, arguments); }; /** * Cancels an event listener. * @see Mixin.Events::off() */ View.prototype.off = function () { return this._data.off.apply(this._data, arguments); }; /** * Emits an event. * @see Mixin.Events::emit() */ View.prototype.emit = function () { return this._data.emit.apply(this._data, arguments); }; /** * Emits an event. * @see Mixin.Events::deferEmit() */ View.prototype.deferEmit = function () { return this._data.deferEmit.apply(this._data, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { return this._data.distinct(key, query, options); }; /** * Gets the primary key for this view from the assigned collection. * @see Collection::primaryKey() * @returns {String} */ View.prototype.primaryKey = function () { return this._data.primaryKey(); }; /** * @see Mixin.Triggers::addTrigger() */ View.prototype.addTrigger = function () { return this._data.addTrigger.apply(this._data, arguments); }; /** * @see Mixin.Triggers::removeTrigger() */ View.prototype.removeTrigger = function () { return this._data.removeTrigger.apply(this._data, arguments); }; /** * @see Mixin.Triggers::ignoreTriggers() */ View.prototype.ignoreTriggers = function () { return this._data.ignoreTriggers.apply(this._data, arguments); }; /** * @see Mixin.Triggers::addLinkIO() */ View.prototype.addLinkIO = function () { return this._data.addLinkIO.apply(this._data, arguments); }; /** * @see Mixin.Triggers::removeLinkIO() */ View.prototype.removeLinkIO = function () { return this._data.removeLinkIO.apply(this._data, arguments); }; /** * @see Mixin.Triggers::willTrigger() */ View.prototype.willTrigger = function () { return this._data.willTrigger.apply(this._data, arguments); }; /** * @see Mixin.Triggers::processTrigger() */ View.prototype.processTrigger = function () { return this._data.processTrigger.apply(this._data, arguments); }; /** * @see Mixin.Triggers::_triggerIndexOf() */ View.prototype._triggerIndexOf = function () { return this._data._triggerIndexOf.apply(this._data, arguments); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._data) { this._data.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._chain; delete this._from; delete this._data; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } return false; }; /** * Gets / sets the query object and query options that the view uses * to build it's data set. This call modifies both the query and * query options at the same time. * @param {Object=} query The query to set. * @param {Boolean=} options The query options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} * @deprecated Use query(<query>, <options>, <refresh>) instead. Query * now supports being presented with multiple different variations of * arguments. */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._data.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._data.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } } if (query !== undefined) { this.emit('queryChange', query); } if (options !== undefined) { this.emit('queryOptionsChange', options); } if (query !== undefined || options !== undefined) { return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } if (query !== undefined) { this.emit('queryChange', query); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (query) { if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } if (query !== undefined) { this.emit('queryChange', query); } } }; /** * Gets / sets the query being used to generate the view data. It * does not change or modify the view's query options. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = new Overload({ '': function () { return this.decouple(this._querySettings.query); }, 'object': function (query) { return this.$main.call(this, query, undefined, true); }, '*, boolean': function (query, refresh) { return this.$main.call(this, query, undefined, refresh); }, 'object, object': function (query, options) { return this.$main.call(this, query, options, true); }, '*, *, boolean': function (query, options, refresh) { return this.$main.call(this, query, options, refresh); }, '$main': function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._data.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._data.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } } if (query !== undefined) { this.emit('queryChange', query); } if (options !== undefined) { this.emit('queryOptionsChange', options); } if (query !== undefined || options !== undefined) { return this; } return this.decouple(this._querySettings); } }); /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { // TODO: This could be wasteful if the previous options $orderBy was identical, do a hash and check first! this.rebuildActiveBucket(options.$orderBy); } if (options !== undefined) { this.emit('queryOptionsChange', options); } return this; } return this._querySettings.options; }; /** * Clears the existing active bucket and builds a new one based * on the passed orderBy object (if one is passed). * @param {Object=} orderBy The orderBy object describing how to * order any data. */ View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._data._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._data.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { var self = this, refreshResults, joinArr, i, k; if (this._from) { // Clear the private data collection which will propagate to the public data // collection automatically via the chain reactor node between them this._data.remove(); // Grab all the data from the underlying data source refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); // Insert the underlying data into the private data collection this._data.insert(refreshResults); // Store the current cursor data this._data._data.$cursor = refreshResults.$cursor; } if (this._querySettings && this._querySettings.options && this._querySettings.options.$join && this._querySettings.options.$join.length) { // Define the change handler method self.__joinChange = self.__joinChange || function () { self._joinChange(); }; // Check for existing join collections if (this._joinCollections && this._joinCollections.length) { // Loop the join collections and remove change listeners // Loop the collections and hook change events for (i = 0; i < this._joinCollections.length; i++) { this._db.collection(this._joinCollections[i]).off('immediateChange', self.__joinChange); } } // Now start hooking any new / existing joins joinArr = this._querySettings.options.$join; this._joinCollections = []; // Loop the joined collections and hook change events for (i = 0; i < joinArr.length; i++) { for (k in joinArr[i]) { if (joinArr[i].hasOwnProperty(k)) { this._joinCollections.push(k); } } } if (this._joinCollections.length) { // Loop the collections and hook change events for (i = 0; i < this._joinCollections.length; i++) { this._db.collection(this._joinCollections[i]).on('immediateChange', self.__joinChange); } } } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Handles when a change has occurred on a collection that is joined * by query to this view. * @param objName * @param objType * @private */ View.prototype._joinChange = function (objName, objType) { this.emit('joinChange'); // TODO: This is a really dirty solution because it will require a complete // TODO: rebuild of the view data. We need to implement an IO handler to // TODO: selectively update the data of the view based on the joined // TODO: collection data operation. // FIXME: This isnt working, major performance killer, invest in some IO from chain reactor to make this a targeted call this.refresh(); }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { return this._data.count.apply(this._data, arguments); }; // Call underlying View.prototype.subset = function () { return this._data.subset.apply(this._data, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" * and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { var currentSettings, newSettings; currentSettings = this._data.transform(); this._data.transform(obj); newSettings = this._data.transform(); // Check if transforms are enabled, a dataIn method is set and these // settings did not match the previous transform settings if (newSettings.enabled && newSettings.dataIn && (currentSettings.enabled !== newSettings.enabled || currentSettings.dataIn !== newSettings.dataIn)) { // The data in the view is now stale, refresh it this.refresh(); } return newSettings; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return this._data.filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.data = function () { return this._data; }; /** * @see Collection.indexOf * @returns {*} */ View.prototype.indexOf = function () { return this._data.indexOf.apply(this._data, arguments); }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @memberof View * @returns {*} */ Shared.synthesize(View.prototype, 'db', function (db) { if (db) { this._data.db(db); // Apply the same debug settings this.debug(db.debug()); this._data.debug(db.debug()); } return this.$super.apply(this, arguments); }); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); /** * Gets / sets the current name. * @param {String=} val The new name to set. * @returns {*} */ Shared.synthesize(View.prototype, 'name'); /** * Gets / sets the current cursor. * @param {String=} val The new cursor to set. * @returns {*} */ Shared.synthesize(View.prototype, 'cursor', function (val) { if (val === undefined) { return this._cursor || {}; } this.$super.apply(this, arguments); }); // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} name The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (name) { var self = this; // Handle being passed an instance if (name instanceof View) { return name; } if (this._view[name]) { return this._view[name]; } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating view ' + name); } this._view[name] = new View(name).db(this); self.emit('create', self._view[name], 'view', name); return this._view[name]; }; /** * Determine if a view with the passed name already exists. * @param {String} name The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (name) { return Boolean(this._view[name]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], view, i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { view = this._view[i]; arr.push({ name: i, count: view.count(), linked: view.isLinked !== undefined ? view.isLinked() : false }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":3,"./Collection":7,"./CollectionGroup":8,"./Overload":33,"./ReactorIO":39,"./Shared":41}],44:[function(_dereq_,module,exports){ (function (process){ // Use the fastest possible means to execute a task in a future turn // of the event loop. // linked list of tasks (single, with head node) var head = {task: void 0, next: null}; var tail = head; var flushing = false; var requestFlush = void 0; var isNodeJS = false; function flush() { /* jshint loopfunc: true */ while (head.next) { head = head.next; var task = head.task; head.task = void 0; var domain = head.domain; if (domain) { head.domain = void 0; domain.enter(); } try { task(); } catch (e) { if (isNodeJS) { // In node, uncaught exceptions are considered fatal errors. // Re-throw them synchronously to interrupt flushing! // Ensure continuation if the uncaught exception is suppressed // listening "uncaughtException" events (as domains does). // Continue in next event to avoid tick recursion. if (domain) { domain.exit(); } setTimeout(flush, 0); if (domain) { domain.enter(); } throw e; } else { // In browsers, uncaught exceptions are not fatal. // Re-throw them asynchronously to avoid slow-downs. setTimeout(function() { throw e; }, 0); } } if (domain) { domain.exit(); } } flushing = false; } if (typeof process !== "undefined" && process.nextTick) { // Node.js before 0.9. Note that some fake-Node environments, like the // Mocha test runner, introduce a `process` global without a `nextTick`. isNodeJS = true; requestFlush = function () { process.nextTick(flush); }; } else if (typeof setImmediate === "function") { // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate if (typeof window !== "undefined") { requestFlush = setImmediate.bind(window, flush); } else { requestFlush = function () { setImmediate(flush); }; } } else if (typeof MessageChannel !== "undefined") { // modern browsers // http://www.nonblocking.io/2011/06/windownexttick.html var channel = new MessageChannel(); channel.port1.onmessage = flush; requestFlush = function () { channel.port2.postMessage(0); }; } else { // old browsers requestFlush = function () { setTimeout(flush, 0); }; } function asap(task) { tail = tail.next = { task: task, domain: isNodeJS && process.domain, next: null }; if (!flushing) { flushing = true; requestFlush(); } }; module.exports = asap; }).call(this,_dereq_('_process')) },{"_process":101}],45:[function(_dereq_,module,exports){ (function (process,global){ /*! * async * https://github.com/caolan/async * * Copyright 2010-2014 Caolan McMahon * Released under the MIT license */ (function () { var async = {}; function noop() {} function identity(v) { return v; } function toBool(v) { return !!v; } function notId(v) { return !v; } // global on the server, window in the browser var previous_async; // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. var root = typeof self === 'object' && self.self === self && self || typeof global === 'object' && global.global === global && global || this; if (root != null) { previous_async = root.async; } async.noConflict = function () { root.async = previous_async; return async; }; function only_once(fn) { return function() { if (fn === null) throw new Error("Callback was already called."); fn.apply(this, arguments); fn = null; }; } function _once(fn) { return function() { if (fn === null) return; fn.apply(this, arguments); fn = null; }; } //// cross-browser compatiblity functions //// var _toString = Object.prototype.toString; var _isArray = Array.isArray || function (obj) { return _toString.call(obj) === '[object Array]'; }; // Ported from underscore.js isObject var _isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; function _isArrayLike(arr) { return _isArray(arr) || ( // has a positive integer length property typeof arr.length === "number" && arr.length >= 0 && arr.length % 1 === 0 ); } function _arrayEach(arr, iterator) { var index = -1, length = arr.length; while (++index < length) { iterator(arr[index], index, arr); } } function _map(arr, iterator) { var index = -1, length = arr.length, result = Array(length); while (++index < length) { result[index] = iterator(arr[index], index, arr); } return result; } function _range(count) { return _map(Array(count), function (v, i) { return i; }); } function _reduce(arr, iterator, memo) { _arrayEach(arr, function (x, i, a) { memo = iterator(memo, x, i, a); }); return memo; } function _forEachOf(object, iterator) { _arrayEach(_keys(object), function (key) { iterator(object[key], key); }); } function _indexOf(arr, item) { for (var i = 0; i < arr.length; i++) { if (arr[i] === item) return i; } return -1; } var _keys = Object.keys || function (obj) { var keys = []; for (var k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys; }; function _keyIterator(coll) { var i = -1; var len; var keys; if (_isArrayLike(coll)) { len = coll.length; return function next() { i++; return i < len ? i : null; }; } else { keys = _keys(coll); len = keys.length; return function next() { i++; return i < len ? keys[i] : null; }; } } // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) // This accumulates the arguments passed into an array, after a given index. // From underscore.js (https://github.com/jashkenas/underscore/pull/2140). function _restParam(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { var length = Math.max(arguments.length - startIndex, 0); var rest = Array(length); for (var index = 0; index < length; index++) { rest[index] = arguments[index + startIndex]; } switch (startIndex) { case 0: return func.call(this, rest); case 1: return func.call(this, arguments[0], rest); } // Currently unused but handle cases outside of the switch statement: // var args = Array(startIndex + 1); // for (index = 0; index < startIndex; index++) { // args[index] = arguments[index]; // } // args[startIndex] = rest; // return func.apply(this, args); }; } function _withoutIndex(iterator) { return function (value, index, callback) { return iterator(value, callback); }; } //// exported async module functions //// //// nextTick implementation with browser-compatible fallback //// // capture the global reference to guard against fakeTimer mocks var _setImmediate = typeof setImmediate === 'function' && setImmediate; var _delay = _setImmediate ? function(fn) { // not a direct alias for IE10 compatibility _setImmediate(fn); } : function(fn) { setTimeout(fn, 0); }; if (typeof process === 'object' && typeof process.nextTick === 'function') { async.nextTick = process.nextTick; } else { async.nextTick = _delay; } async.setImmediate = _setImmediate ? _delay : async.nextTick; async.forEach = async.each = function (arr, iterator, callback) { return async.eachOf(arr, _withoutIndex(iterator), callback); }; async.forEachSeries = async.eachSeries = function (arr, iterator, callback) { return async.eachOfSeries(arr, _withoutIndex(iterator), callback); }; async.forEachLimit = async.eachLimit = function (arr, limit, iterator, callback) { return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback); }; async.forEachOf = async.eachOf = function (object, iterator, callback) { callback = _once(callback || noop); object = object || []; var iter = _keyIterator(object); var key, completed = 0; while ((key = iter()) != null) { completed += 1; iterator(object[key], key, only_once(done)); } if (completed === 0) callback(null); function done(err) { completed--; if (err) { callback(err); } // Check key is null in case iterator isn't exhausted // and done resolved synchronously. else if (key === null && completed <= 0) { callback(null); } } }; async.forEachOfSeries = async.eachOfSeries = function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); var key = nextKey(); function iterate() { var sync = true; if (key === null) { return callback(null); } iterator(obj[key], key, only_once(function (err) { if (err) { callback(err); } else { key = nextKey(); if (key === null) { return callback(null); } else { if (sync) { async.setImmediate(iterate); } else { iterate(); } } } })); sync = false; } iterate(); }; async.forEachOfLimit = async.eachOfLimit = function (obj, limit, iterator, callback) { _eachOfLimit(limit)(obj, iterator, callback); }; function _eachOfLimit(limit) { return function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); if (limit <= 0) { return callback(null); } var done = false; var running = 0; var errored = false; (function replenish () { if (done && running <= 0) { return callback(null); } while (running < limit && !errored) { var key = nextKey(); if (key === null) { done = true; if (running <= 0) { callback(null); } return; } running += 1; iterator(obj[key], key, only_once(function (err) { running -= 1; if (err) { callback(err); errored = true; } else { replenish(); } })); } })(); }; } function doParallel(fn) { return function (obj, iterator, callback) { return fn(async.eachOf, obj, iterator, callback); }; } function doParallelLimit(fn) { return function (obj, limit, iterator, callback) { return fn(_eachOfLimit(limit), obj, iterator, callback); }; } function doSeries(fn) { return function (obj, iterator, callback) { return fn(async.eachOfSeries, obj, iterator, callback); }; } function _asyncMap(eachfn, arr, iterator, callback) { callback = _once(callback || noop); arr = arr || []; var results = _isArrayLike(arr) ? [] : {}; eachfn(arr, function (value, index, callback) { iterator(value, function (err, v) { results[index] = v; callback(err); }); }, function (err) { callback(err, results); }); } async.map = doParallel(_asyncMap); async.mapSeries = doSeries(_asyncMap); async.mapLimit = doParallelLimit(_asyncMap); // reduce only has a series version, as doing reduce in parallel won't // work in many situations. async.inject = async.foldl = async.reduce = function (arr, memo, iterator, callback) { async.eachOfSeries(arr, function (x, i, callback) { iterator(memo, x, function (err, v) { memo = v; callback(err); }); }, function (err) { callback(err, memo); }); }; async.foldr = async.reduceRight = function (arr, memo, iterator, callback) { var reversed = _map(arr, identity).reverse(); async.reduce(reversed, memo, iterator, callback); }; async.transform = function (arr, memo, iterator, callback) { if (arguments.length === 3) { callback = iterator; iterator = memo; memo = _isArray(arr) ? [] : {}; } async.eachOf(arr, function(v, k, cb) { iterator(memo, v, k, cb); }, function(err) { callback(err, memo); }); }; function _filter(eachfn, arr, iterator, callback) { var results = []; eachfn(arr, function (x, index, callback) { iterator(x, function (v) { if (v) { results.push({index: index, value: x}); } callback(); }); }, function () { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); } async.select = async.filter = doParallel(_filter); async.selectLimit = async.filterLimit = doParallelLimit(_filter); async.selectSeries = async.filterSeries = doSeries(_filter); function _reject(eachfn, arr, iterator, callback) { _filter(eachfn, arr, function(value, cb) { iterator(value, function(v) { cb(!v); }); }, callback); } async.reject = doParallel(_reject); async.rejectLimit = doParallelLimit(_reject); async.rejectSeries = doSeries(_reject); function _createTester(eachfn, check, getResult) { return function(arr, limit, iterator, cb) { function done() { if (cb) cb(getResult(false, void 0)); } function iteratee(x, _, callback) { if (!cb) return callback(); iterator(x, function (v) { if (cb && check(v)) { cb(getResult(true, x)); cb = iterator = false; } callback(); }); } if (arguments.length > 3) { eachfn(arr, limit, iteratee, done); } else { cb = iterator; iterator = limit; eachfn(arr, iteratee, done); } }; } async.any = async.some = _createTester(async.eachOf, toBool, identity); async.someLimit = _createTester(async.eachOfLimit, toBool, identity); async.all = async.every = _createTester(async.eachOf, notId, notId); async.everyLimit = _createTester(async.eachOfLimit, notId, notId); function _findGetResult(v, x) { return x; } async.detect = _createTester(async.eachOf, identity, _findGetResult); async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult); async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult); async.sortBy = function (arr, iterator, callback) { async.map(arr, function (x, callback) { iterator(x, function (err, criteria) { if (err) { callback(err); } else { callback(null, {value: x, criteria: criteria}); } }); }, function (err, results) { if (err) { return callback(err); } else { callback(null, _map(results.sort(comparator), function (x) { return x.value; })); } }); function comparator(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } }; async.auto = function (tasks, concurrency, callback) { if (typeof arguments[1] === 'function') { // concurrency is optional, shift the args. callback = concurrency; concurrency = null; } callback = _once(callback || noop); var keys = _keys(tasks); var remainingTasks = keys.length; if (!remainingTasks) { return callback(null); } if (!concurrency) { concurrency = remainingTasks; } var results = {}; var runningTasks = 0; var hasError = false; var listeners = []; function addListener(fn) { listeners.unshift(fn); } function removeListener(fn) { var idx = _indexOf(listeners, fn); if (idx >= 0) listeners.splice(idx, 1); } function taskComplete() { remainingTasks--; _arrayEach(listeners.slice(0), function (fn) { fn(); }); } addListener(function () { if (!remainingTasks) { callback(null, results); } }); _arrayEach(keys, function (k) { if (hasError) return; var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; var taskCallback = _restParam(function(err, args) { runningTasks--; if (args.length <= 1) { args = args[0]; } if (err) { var safeResults = {}; _forEachOf(results, function(val, rkey) { safeResults[rkey] = val; }); safeResults[k] = args; hasError = true; callback(err, safeResults); } else { results[k] = args; async.setImmediate(taskComplete); } }); var requires = task.slice(0, task.length - 1); // prevent dead-locks var len = requires.length; var dep; while (len--) { if (!(dep = tasks[requires[len]])) { throw new Error('Has nonexistent dependency in ' + requires.join(', ')); } if (_isArray(dep) && _indexOf(dep, k) >= 0) { throw new Error('Has cyclic dependencies'); } } function ready() { return runningTasks < concurrency && _reduce(requires, function (a, x) { return (a && results.hasOwnProperty(x)); }, true) && !results.hasOwnProperty(k); } if (ready()) { runningTasks++; task[task.length - 1](taskCallback, results); } else { addListener(listener); } function listener() { if (ready()) { runningTasks++; removeListener(listener); task[task.length - 1](taskCallback, results); } } }); }; async.retry = function(times, task, callback) { var DEFAULT_TIMES = 5; var DEFAULT_INTERVAL = 0; var attempts = []; var opts = { times: DEFAULT_TIMES, interval: DEFAULT_INTERVAL }; function parseTimes(acc, t){ if(typeof t === 'number'){ acc.times = parseInt(t, 10) || DEFAULT_TIMES; } else if(typeof t === 'object'){ acc.times = parseInt(t.times, 10) || DEFAULT_TIMES; acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL; } else { throw new Error('Unsupported argument type for \'times\': ' + typeof t); } } var length = arguments.length; if (length < 1 || length > 3) { throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)'); } else if (length <= 2 && typeof times === 'function') { callback = task; task = times; } if (typeof times !== 'function') { parseTimes(opts, times); } opts.callback = callback; opts.task = task; function wrappedTask(wrappedCallback, wrappedResults) { function retryAttempt(task, finalAttempt) { return function(seriesCallback) { task(function(err, result){ seriesCallback(!err || finalAttempt, {err: err, result: result}); }, wrappedResults); }; } function retryInterval(interval){ return function(seriesCallback){ setTimeout(function(){ seriesCallback(null); }, interval); }; } while (opts.times) { var finalAttempt = !(opts.times-=1); attempts.push(retryAttempt(opts.task, finalAttempt)); if(!finalAttempt && opts.interval > 0){ attempts.push(retryInterval(opts.interval)); } } async.series(attempts, function(done, data){ data = data[data.length - 1]; (wrappedCallback || opts.callback)(data.err, data.result); }); } // If a callback is passed, run this as a controll flow return opts.callback ? wrappedTask() : wrappedTask; }; async.waterfall = function (tasks, callback) { callback = _once(callback || noop); if (!_isArray(tasks)) { var err = new Error('First argument to waterfall must be an array of functions'); return callback(err); } if (!tasks.length) { return callback(); } function wrapIterator(iterator) { return _restParam(function (err, args) { if (err) { callback.apply(null, [err].concat(args)); } else { var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } ensureAsync(iterator).apply(null, args); } }); } wrapIterator(async.iterator(tasks))(); }; function _parallel(eachfn, tasks, callback) { callback = callback || noop; var results = _isArrayLike(tasks) ? [] : {}; eachfn(tasks, function (task, key, callback) { task(_restParam(function (err, args) { if (args.length <= 1) { args = args[0]; } results[key] = args; callback(err); })); }, function (err) { callback(err, results); }); } async.parallel = function (tasks, callback) { _parallel(async.eachOf, tasks, callback); }; async.parallelLimit = function(tasks, limit, callback) { _parallel(_eachOfLimit(limit), tasks, callback); }; async.series = function(tasks, callback) { _parallel(async.eachOfSeries, tasks, callback); }; async.iterator = function (tasks) { function makeCallback(index) { function fn() { if (tasks.length) { tasks[index].apply(null, arguments); } return fn.next(); } fn.next = function () { return (index < tasks.length - 1) ? makeCallback(index + 1): null; }; return fn; } return makeCallback(0); }; async.apply = _restParam(function (fn, args) { return _restParam(function (callArgs) { return fn.apply( null, args.concat(callArgs) ); }); }); function _concat(eachfn, arr, fn, callback) { var result = []; eachfn(arr, function (x, index, cb) { fn(x, function (err, y) { result = result.concat(y || []); cb(err); }); }, function (err) { callback(err, result); }); } async.concat = doParallel(_concat); async.concatSeries = doSeries(_concat); async.whilst = function (test, iterator, callback) { callback = callback || noop; if (test()) { var next = _restParam(function(err, args) { if (err) { callback(err); } else if (test.apply(this, args)) { iterator(next); } else { callback.apply(null, [null].concat(args)); } }); iterator(next); } else { callback(null); } }; async.doWhilst = function (iterator, test, callback) { var calls = 0; return async.whilst(function() { return ++calls <= 1 || test.apply(this, arguments); }, iterator, callback); }; async.until = function (test, iterator, callback) { return async.whilst(function() { return !test.apply(this, arguments); }, iterator, callback); }; async.doUntil = function (iterator, test, callback) { return async.doWhilst(iterator, function() { return !test.apply(this, arguments); }, callback); }; async.during = function (test, iterator, callback) { callback = callback || noop; var next = _restParam(function(err, args) { if (err) { callback(err); } else { args.push(check); test.apply(this, args); } }); var check = function(err, truth) { if (err) { callback(err); } else if (truth) { iterator(next); } else { callback(null); } }; test(check); }; async.doDuring = function (iterator, test, callback) { var calls = 0; async.during(function(next) { if (calls++ < 1) { next(null, true); } else { test.apply(this, arguments); } }, iterator, callback); }; function _queue(worker, concurrency, payload) { if (concurrency == null) { concurrency = 1; } else if(concurrency === 0) { throw new Error('Concurrency must not be zero'); } function _insert(q, data, pos, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0 && q.idle()) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, callback: callback || noop }; if (pos) { q.tasks.unshift(item); } else { q.tasks.push(item); } if (q.tasks.length === q.concurrency) { q.saturated(); } }); async.setImmediate(q.process); } function _next(q, tasks) { return function(){ workers -= 1; var removed = false; var args = arguments; _arrayEach(tasks, function (task) { _arrayEach(workersList, function (worker, index) { if (worker === task && !removed) { workersList.splice(index, 1); removed = true; } }); task.callback.apply(task, args); }); if (q.tasks.length + workers === 0) { q.drain(); } q.process(); }; } var workers = 0; var workersList = []; var q = { tasks: [], concurrency: concurrency, payload: payload, saturated: noop, empty: noop, drain: noop, started: false, paused: false, push: function (data, callback) { _insert(q, data, false, callback); }, kill: function () { q.drain = noop; q.tasks = []; }, unshift: function (data, callback) { _insert(q, data, true, callback); }, process: function () { while(!q.paused && workers < q.concurrency && q.tasks.length){ var tasks = q.payload ? q.tasks.splice(0, q.payload) : q.tasks.splice(0, q.tasks.length); var data = _map(tasks, function (task) { return task.data; }); if (q.tasks.length === 0) { q.empty(); } workers += 1; workersList.push(tasks[0]); var cb = only_once(_next(q, tasks)); worker(data, cb); } }, length: function () { return q.tasks.length; }, running: function () { return workers; }, workersList: function () { return workersList; }, idle: function() { return q.tasks.length + workers === 0; }, pause: function () { q.paused = true; }, resume: function () { if (q.paused === false) { return; } q.paused = false; var resumeCount = Math.min(q.concurrency, q.tasks.length); // Need to call q.process once per concurrent // worker to preserve full concurrency after pause for (var w = 1; w <= resumeCount; w++) { async.setImmediate(q.process); } } }; return q; } async.queue = function (worker, concurrency) { var q = _queue(function (items, cb) { worker(items[0], cb); }, concurrency, 1); return q; }; async.priorityQueue = function (worker, concurrency) { function _compareTasks(a, b){ return a.priority - b.priority; } function _binarySearch(sequence, item, compare) { var beg = -1, end = sequence.length - 1; while (beg < end) { var mid = beg + ((end - beg + 1) >>> 1); if (compare(item, sequence[mid]) >= 0) { beg = mid; } else { end = mid - 1; } } return beg; } function _insert(q, data, priority, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, priority: priority, callback: typeof callback === 'function' ? callback : noop }; q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); if (q.tasks.length === q.concurrency) { q.saturated(); } async.setImmediate(q.process); }); } // Start with a normal queue var q = async.queue(worker, concurrency); // Override push to accept second parameter representing priority q.push = function (data, priority, callback) { _insert(q, data, priority, callback); }; // Remove unshift function delete q.unshift; return q; }; async.cargo = function (worker, payload) { return _queue(worker, 1, payload); }; function _console_fn(name) { return _restParam(function (fn, args) { fn.apply(null, args.concat([_restParam(function (err, args) { if (typeof console === 'object') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { _arrayEach(args, function (x) { console[name](x); }); } } })])); }); } async.log = _console_fn('log'); async.dir = _console_fn('dir'); /*async.info = _console_fn('info'); async.warn = _console_fn('warn'); async.error = _console_fn('error');*/ async.memoize = function (fn, hasher) { var memo = {}; var queues = {}; var has = Object.prototype.hasOwnProperty; hasher = hasher || identity; var memoized = _restParam(function memoized(args) { var callback = args.pop(); var key = hasher.apply(null, args); if (has.call(memo, key)) { async.setImmediate(function () { callback.apply(null, memo[key]); }); } else if (has.call(queues, key)) { queues[key].push(callback); } else { queues[key] = [callback]; fn.apply(null, args.concat([_restParam(function (args) { memo[key] = args; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, args); } })])); } }); memoized.memo = memo; memoized.unmemoized = fn; return memoized; }; async.unmemoize = function (fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }; function _times(mapper) { return function (count, iterator, callback) { mapper(_range(count), iterator, callback); }; } async.times = _times(async.map); async.timesSeries = _times(async.mapSeries); async.timesLimit = function (count, limit, iterator, callback) { return async.mapLimit(_range(count), limit, iterator, callback); }; async.seq = function (/* functions... */) { var fns = arguments; return _restParam(function (args) { var that = this; var callback = args[args.length - 1]; if (typeof callback == 'function') { args.pop(); } else { callback = noop; } async.reduce(fns, args, function (newargs, fn, cb) { fn.apply(that, newargs.concat([_restParam(function (err, nextargs) { cb(err, nextargs); })])); }, function (err, results) { callback.apply(that, [err].concat(results)); }); }); }; async.compose = function (/* functions... */) { return async.seq.apply(null, Array.prototype.reverse.call(arguments)); }; function _applyEach(eachfn) { return _restParam(function(fns, args) { var go = _restParam(function(args) { var that = this; var callback = args.pop(); return eachfn(fns, function (fn, _, cb) { fn.apply(that, args.concat([cb])); }, callback); }); if (args.length) { return go.apply(this, args); } else { return go; } }); } async.applyEach = _applyEach(async.eachOf); async.applyEachSeries = _applyEach(async.eachOfSeries); async.forever = function (fn, callback) { var done = only_once(callback || noop); var task = ensureAsync(fn); function next(err) { if (err) { return done(err); } task(next); } next(); }; function ensureAsync(fn) { return _restParam(function (args) { var callback = args.pop(); args.push(function () { var innerArgs = arguments; if (sync) { async.setImmediate(function () { callback.apply(null, innerArgs); }); } else { callback.apply(null, innerArgs); } }); var sync = true; fn.apply(this, args); sync = false; }); } async.ensureAsync = ensureAsync; async.constant = _restParam(function(values) { var args = [null].concat(values); return function (callback) { return callback.apply(this, args); }; }); async.wrapSync = async.asyncify = function asyncify(func) { return _restParam(function (args) { var callback = args.pop(); var result; try { result = func.apply(this, args); } catch (e) { return callback(e); } // if result is Promise object if (_isObject(result) && typeof result.then === "function") { result.then(function(value) { callback(null, value); })["catch"](function(err) { callback(err.message ? err : new Error(err)); }); } else { callback(null, result); } }); }; // Node.js if (typeof module === 'object' && module.exports) { module.exports = async; } // AMD / RequireJS else if (typeof define === 'function' && define.amd) { define([], function () { return async; }); } // included directly via <script> tag else { root.async = async; } }()); }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":101}],46:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Lookup tables var SBOX = []; var INV_SBOX = []; var SUB_MIX_0 = []; var SUB_MIX_1 = []; var SUB_MIX_2 = []; var SUB_MIX_3 = []; var INV_SUB_MIX_0 = []; var INV_SUB_MIX_1 = []; var INV_SUB_MIX_2 = []; var INV_SUB_MIX_3 = []; // Compute lookup tables (function () { // Compute double table var d = []; for (var i = 0; i < 256; i++) { if (i < 128) { d[i] = i << 1; } else { d[i] = (i << 1) ^ 0x11b; } } // Walk GF(2^8) var x = 0; var xi = 0; for (var i = 0; i < 256; i++) { // Compute sbox var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; SBOX[x] = sx; INV_SBOX[sx] = x; // Compute multiplication var x2 = d[x]; var x4 = d[x2]; var x8 = d[x4]; // Compute sub bytes, mix columns tables var t = (d[sx] * 0x101) ^ (sx * 0x1010100); SUB_MIX_0[x] = (t << 24) | (t >>> 8); SUB_MIX_1[x] = (t << 16) | (t >>> 16); SUB_MIX_2[x] = (t << 8) | (t >>> 24); SUB_MIX_3[x] = t; // Compute inv sub bytes, inv mix columns tables var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); INV_SUB_MIX_3[sx] = t; // Compute next counter if (!x) { x = xi = 1; } else { x = x2 ^ d[d[d[x8 ^ x2]]]; xi ^= d[d[xi]]; } } }()); // Precomputed Rcon lookup var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; /** * AES block cipher algorithm. */ var AES = C_algo.AES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySize = key.sigBytes / 4; // Compute number of rounds var nRounds = this._nRounds = keySize + 6 // Compute number of key schedule rows var ksRows = (nRounds + 1) * 4; // Compute key schedule var keySchedule = this._keySchedule = []; for (var ksRow = 0; ksRow < ksRows; ksRow++) { if (ksRow < keySize) { keySchedule[ksRow] = keyWords[ksRow]; } else { var t = keySchedule[ksRow - 1]; if (!(ksRow % keySize)) { // Rot word t = (t << 8) | (t >>> 24); // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; // Mix Rcon t ^= RCON[(ksRow / keySize) | 0] << 24; } else if (keySize > 6 && ksRow % keySize == 4) { // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; } keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; } } // Compute inv key schedule var invKeySchedule = this._invKeySchedule = []; for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { var ksRow = ksRows - invKsRow; if (invKsRow % 4) { var t = keySchedule[ksRow]; } else { var t = keySchedule[ksRow - 4]; } if (invKsRow < 4 || ksRow <= 4) { invKeySchedule[invKsRow] = t; } else { invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; } } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); }, decryptBlock: function (M, offset) { // Swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); // Inv swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; }, _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { // Shortcut var nRounds = this._nRounds; // Get input, add round key var s0 = M[offset] ^ keySchedule[0]; var s1 = M[offset + 1] ^ keySchedule[1]; var s2 = M[offset + 2] ^ keySchedule[2]; var s3 = M[offset + 3] ^ keySchedule[3]; // Key schedule row counter var ksRow = 4; // Rounds for (var round = 1; round < nRounds; round++) { // Shift rows, sub bytes, mix columns, add round key var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; // Update state s0 = t0; s1 = t1; s2 = t2; s3 = t3; } // Shift rows, sub bytes, add round key var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; // Set output M[offset] = t0; M[offset + 1] = t1; M[offset + 2] = t2; M[offset + 3] = t3; }, keySize: 256/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); */ C.AES = BlockCipher._createHelper(AES); }()); return CryptoJS.AES; })); },{"./cipher-core":47,"./core":48,"./enc-base64":49,"./evpkdf":51,"./md5":56}],47:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher core components. */ CryptoJS.lib.Cipher || (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var Base64 = C_enc.Base64; var C_algo = C.algo; var EvpKDF = C_algo.EvpKDF; /** * Abstract base cipher template. * * @property {number} keySize This cipher's key size. Default: 4 (128 bits) * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. */ var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ /** * Configuration options. * * @property {WordArray} iv The IV to use for this operation. */ cfg: Base.extend(), /** * Creates this cipher in encryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); */ createEncryptor: function (key, cfg) { return this.create(this._ENC_XFORM_MODE, key, cfg); }, /** * Creates this cipher in decryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); */ createDecryptor: function (key, cfg) { return this.create(this._DEC_XFORM_MODE, key, cfg); }, /** * Initializes a newly created cipher. * * @param {number} xformMode Either the encryption or decryption transormation mode constant. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @example * * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); */ init: function (xformMode, key, cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Store transform mode and key this._xformMode = xformMode; this._key = key; // Set initial values this.reset(); }, /** * Resets this cipher to its initial state. * * @example * * cipher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-cipher logic this._doReset(); }, /** * Adds data to be encrypted or decrypted. * * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. * * @return {WordArray} The data after processing. * * @example * * var encrypted = cipher.process('data'); * var encrypted = cipher.process(wordArray); */ process: function (dataUpdate) { // Append this._append(dataUpdate); // Process available blocks return this._process(); }, /** * Finalizes the encryption or decryption process. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. * * @return {WordArray} The data after final processing. * * @example * * var encrypted = cipher.finalize(); * var encrypted = cipher.finalize('data'); * var encrypted = cipher.finalize(wordArray); */ finalize: function (dataUpdate) { // Final data update if (dataUpdate) { this._append(dataUpdate); } // Perform concrete-cipher logic var finalProcessedData = this._doFinalize(); return finalProcessedData; }, keySize: 128/32, ivSize: 128/32, _ENC_XFORM_MODE: 1, _DEC_XFORM_MODE: 2, /** * Creates shortcut functions to a cipher's object interface. * * @param {Cipher} cipher The cipher to create a helper for. * * @return {Object} An object with encrypt and decrypt shortcut functions. * * @static * * @example * * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); */ _createHelper: (function () { function selectCipherStrategy(key) { if (typeof key == 'string') { return PasswordBasedCipher; } else { return SerializableCipher; } } return function (cipher) { return { encrypt: function (message, key, cfg) { return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); }, decrypt: function (ciphertext, key, cfg) { return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); } }; }; }()) }); /** * Abstract base stream cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) */ var StreamCipher = C_lib.StreamCipher = Cipher.extend({ _doFinalize: function () { // Process partial blocks var finalProcessedBlocks = this._process(!!'flush'); return finalProcessedBlocks; }, blockSize: 1 }); /** * Mode namespace. */ var C_mode = C.mode = {}; /** * Abstract base block cipher mode template. */ var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ /** * Creates this mode for encryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); */ createEncryptor: function (cipher, iv) { return this.Encryptor.create(cipher, iv); }, /** * Creates this mode for decryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); */ createDecryptor: function (cipher, iv) { return this.Decryptor.create(cipher, iv); }, /** * Initializes a newly created mode. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @example * * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); */ init: function (cipher, iv) { this._cipher = cipher; this._iv = iv; } }); /** * Cipher Block Chaining mode. */ var CBC = C_mode.CBC = (function () { /** * Abstract base CBC mode. */ var CBC = BlockCipherMode.extend(); /** * CBC encryptor. */ CBC.Encryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // XOR and encrypt xorBlock.call(this, words, offset, blockSize); cipher.encryptBlock(words, offset); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); /** * CBC decryptor. */ CBC.Decryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); // Decrypt and XOR cipher.decryptBlock(words, offset); xorBlock.call(this, words, offset, blockSize); // This block becomes the previous block this._prevBlock = thisBlock; } }); function xorBlock(words, offset, blockSize) { // Shortcut var iv = this._iv; // Choose mixing block if (iv) { var block = iv; // Remove IV for subsequent blocks this._iv = undefined; } else { var block = this._prevBlock; } // XOR blocks for (var i = 0; i < blockSize; i++) { words[offset + i] ^= block[i]; } } return CBC; }()); /** * Padding namespace. */ var C_pad = C.pad = {}; /** * PKCS #5/7 padding strategy. */ var Pkcs7 = C_pad.Pkcs7 = { /** * Pads data using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to pad. * @param {number} blockSize The multiple that the data should be padded to. * * @static * * @example * * CryptoJS.pad.Pkcs7.pad(wordArray, 4); */ pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Create padding word var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; // Create padding var paddingWords = []; for (var i = 0; i < nPaddingBytes; i += 4) { paddingWords.push(paddingWord); } var padding = WordArray.create(paddingWords, nPaddingBytes); // Add padding data.concat(padding); }, /** * Unpads data that had been padded using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to unpad. * * @static * * @example * * CryptoJS.pad.Pkcs7.unpad(wordArray); */ unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; /** * Abstract base block cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) */ var BlockCipher = C_lib.BlockCipher = Cipher.extend({ /** * Configuration options. * * @property {Mode} mode The block mode to use. Default: CBC * @property {Padding} padding The padding strategy to use. Default: Pkcs7 */ cfg: Cipher.cfg.extend({ mode: CBC, padding: Pkcs7 }), reset: function () { // Reset cipher Cipher.reset.call(this); // Shortcuts var cfg = this.cfg; var iv = cfg.iv; var mode = cfg.mode; // Reset block mode if (this._xformMode == this._ENC_XFORM_MODE) { var modeCreator = mode.createEncryptor; } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { var modeCreator = mode.createDecryptor; // Keep at least one block in the buffer for unpadding this._minBufferSize = 1; } this._mode = modeCreator.call(mode, this, iv && iv.words); }, _doProcessBlock: function (words, offset) { this._mode.processBlock(words, offset); }, _doFinalize: function () { // Shortcut var padding = this.cfg.padding; // Finalize if (this._xformMode == this._ENC_XFORM_MODE) { // Pad data padding.pad(this._data, this.blockSize); // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); // Unpad data padding.unpad(finalProcessedBlocks); } return finalProcessedBlocks; }, blockSize: 128/32 }); /** * A collection of cipher parameters. * * @property {WordArray} ciphertext The raw ciphertext. * @property {WordArray} key The key to this ciphertext. * @property {WordArray} iv The IV used in the ciphering operation. * @property {WordArray} salt The salt used with a key derivation function. * @property {Cipher} algorithm The cipher algorithm. * @property {Mode} mode The block mode used in the ciphering operation. * @property {Padding} padding The padding scheme used in the ciphering operation. * @property {number} blockSize The block size of the cipher. * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. */ var CipherParams = C_lib.CipherParams = Base.extend({ /** * Initializes a newly created cipher params object. * * @param {Object} cipherParams An object with any of the possible cipher parameters. * * @example * * var cipherParams = CryptoJS.lib.CipherParams.create({ * ciphertext: ciphertextWordArray, * key: keyWordArray, * iv: ivWordArray, * salt: saltWordArray, * algorithm: CryptoJS.algo.AES, * mode: CryptoJS.mode.CBC, * padding: CryptoJS.pad.PKCS7, * blockSize: 4, * formatter: CryptoJS.format.OpenSSL * }); */ init: function (cipherParams) { this.mixIn(cipherParams); }, /** * Converts this cipher params object to a string. * * @param {Format} formatter (Optional) The formatting strategy to use. * * @return {string} The stringified cipher params. * * @throws Error If neither the formatter nor the default formatter is set. * * @example * * var string = cipherParams + ''; * var string = cipherParams.toString(); * var string = cipherParams.toString(CryptoJS.format.OpenSSL); */ toString: function (formatter) { return (formatter || this.formatter).stringify(this); } }); /** * Format namespace. */ var C_format = C.format = {}; /** * OpenSSL formatting strategy. */ var OpenSSLFormatter = C_format.OpenSSL = { /** * Converts a cipher params object to an OpenSSL-compatible string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The OpenSSL-compatible string. * * @static * * @example * * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); */ stringify: function (cipherParams) { // Shortcuts var ciphertext = cipherParams.ciphertext; var salt = cipherParams.salt; // Format if (salt) { var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); } else { var wordArray = ciphertext; } return wordArray.toString(Base64); }, /** * Converts an OpenSSL-compatible string to a cipher params object. * * @param {string} openSSLStr The OpenSSL-compatible string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); */ parse: function (openSSLStr) { // Parse base64 var ciphertext = Base64.parse(openSSLStr); // Shortcut var ciphertextWords = ciphertext.words; // Test for salt if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { // Extract salt var salt = WordArray.create(ciphertextWords.slice(2, 4)); // Remove salt from ciphertext ciphertextWords.splice(0, 4); ciphertext.sigBytes -= 16; } return CipherParams.create({ ciphertext: ciphertext, salt: salt }); } }; /** * A cipher wrapper that returns ciphertext as a serializable cipher params object. */ var SerializableCipher = C_lib.SerializableCipher = Base.extend({ /** * Configuration options. * * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL */ cfg: Base.extend({ format: OpenSSLFormatter }), /** * Encrypts a message. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Encrypt var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); // Shortcut var cipherCfg = encryptor.cfg; // Create and return serializable cipher params return CipherParams.create({ ciphertext: ciphertext, key: key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); }, /** * Decrypts serialized ciphertext. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }, /** * Converts serialized ciphertext to CipherParams, * else assumed CipherParams already and returns ciphertext unchanged. * * @param {CipherParams|string} ciphertext The ciphertext. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. * * @return {CipherParams} The unserialized ciphertext. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); */ _parse: function (ciphertext, format) { if (typeof ciphertext == 'string') { return format.parse(ciphertext, this); } else { return ciphertext; } } }); /** * Key derivation function namespace. */ var C_kdf = C.kdf = {}; /** * OpenSSL key derivation function. */ var OpenSSLKdf = C_kdf.OpenSSL = { /** * Derives a key and IV from a password. * * @param {string} password The password to derive from. * @param {number} keySize The size in words of the key to generate. * @param {number} ivSize The size in words of the IV to generate. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. * * @return {CipherParams} A cipher params object with the key, IV, and salt. * * @static * * @example * * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ execute: function (password, keySize, ivSize, salt) { // Generate random salt if (!salt) { salt = WordArray.random(64/8); } // Derive key and IV var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); // Separate key and IV var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; // Return params return CipherParams.create({ key: key, iv: iv, salt: salt }); } }; /** * A serializable cipher wrapper that derives the key from a password, * and returns ciphertext as a serializable cipher params object. */ var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ /** * Configuration options. * * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL */ cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }()); })); },{"./core":48}],48:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(); } else if (typeof define === "function" && define.amd) { // AMD define([], factory); } else { // Global (browser) root.CryptoJS = factory(); } }(this, function () { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { function F() {} return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn F.prototype = this; var subtype = new F(); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init')) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); },{}],49:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex != -1) { base64StrLength = paddingIndex; } } // Convert var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); var bitsCombined = bits1 | bits2; words[nBytes >>> 2] |= (bitsCombined) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; }()); return CryptoJS.enc.Base64; })); },{"./core":48}],50:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * UTF-16 BE encoding strategy. */ var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { /** * Converts a word array to a UTF-16 BE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 BE string. * * @static * * @example * * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 BE string to a word array. * * @param {string} utf16Str The UTF-16 BE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); } return WordArray.create(words, utf16StrLength * 2); } }; /** * UTF-16 LE encoding strategy. */ C_enc.Utf16LE = { /** * Converts a word array to a UTF-16 LE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 LE string. * * @static * * @example * * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 LE string to a word array. * * @param {string} utf16Str The UTF-16 LE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); } return WordArray.create(words, utf16StrLength * 2); } }; function swapEndian(word) { return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); } }()); return CryptoJS.enc.Utf16; })); },{"./core":48}],51:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var MD5 = C_algo.MD5; /** * This key derivation function is meant to conform with EVP_BytesToKey. * www.openssl.org/docs/crypto/EVP_BytesToKey.html */ var EvpKDF = C_algo.EvpKDF = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hash algorithm to use. Default: MD5 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: MD5, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.EvpKDF.create(); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init hasher var hasher = cfg.hasher.create(); // Initial values var derivedKey = WordArray.create(); // Shortcuts var derivedKeyWords = derivedKey.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { if (block) { hasher.update(block); } var block = hasher.update(password).finalize(salt); hasher.reset(); // Iterations for (var i = 1; i < iterations; i++) { block = hasher.finalize(block); hasher.reset(); } derivedKey.concat(block); } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.EvpKDF(password, salt); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); */ C.EvpKDF = function (password, salt, cfg) { return EvpKDF.create(cfg).compute(password, salt); }; }()); return CryptoJS.EvpKDF; })); },{"./core":48,"./hmac":53,"./sha1":72}],52:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var CipherParams = C_lib.CipherParams; var C_enc = C.enc; var Hex = C_enc.Hex; var C_format = C.format; var HexFormatter = C_format.Hex = { /** * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The hexadecimally encoded string. * * @static * * @example * * var hexString = CryptoJS.format.Hex.stringify(cipherParams); */ stringify: function (cipherParams) { return cipherParams.ciphertext.toString(Hex); }, /** * Converts a hexadecimally encoded ciphertext string to a cipher params object. * * @param {string} input The hexadecimally encoded string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.Hex.parse(hexString); */ parse: function (input) { var ciphertext = Hex.parse(input); return CipherParams.create({ ciphertext: ciphertext }); } }; }()); return CryptoJS.format.Hex; })); },{"./cipher-core":47,"./core":48}],53:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var C_algo = C.algo; /** * HMAC algorithm. */ var HMAC = C_algo.HMAC = Base.extend({ /** * Initializes a newly created HMAC. * * @param {Hasher} hasher The hash algorithm to use. * @param {WordArray|string} key The secret key. * * @example * * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); */ init: function (hasher, key) { // Init hasher hasher = this._hasher = new hasher.init(); // Convert string to WordArray, else assume WordArray already if (typeof key == 'string') { key = Utf8.parse(key); } // Shortcuts var hasherBlockSize = hasher.blockSize; var hasherBlockSizeBytes = hasherBlockSize * 4; // Allow arbitrary length keys if (key.sigBytes > hasherBlockSizeBytes) { key = hasher.finalize(key); } // Clamp excess bits key.clamp(); // Clone key for inner and outer pads var oKey = this._oKey = key.clone(); var iKey = this._iKey = key.clone(); // Shortcuts var oKeyWords = oKey.words; var iKeyWords = iKey.words; // XOR keys with pad constants for (var i = 0; i < hasherBlockSize; i++) { oKeyWords[i] ^= 0x5c5c5c5c; iKeyWords[i] ^= 0x36363636; } oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; // Set initial values this.reset(); }, /** * Resets this HMAC to its initial state. * * @example * * hmacHasher.reset(); */ reset: function () { // Shortcut var hasher = this._hasher; // Reset hasher.reset(); hasher.update(this._iKey); }, /** * Updates this HMAC with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {HMAC} This HMAC instance. * * @example * * hmacHasher.update('message'); * hmacHasher.update(wordArray); */ update: function (messageUpdate) { this._hasher.update(messageUpdate); // Chainable return this; }, /** * Finalizes the HMAC computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The HMAC. * * @example * * var hmac = hmacHasher.finalize(); * var hmac = hmacHasher.finalize('message'); * var hmac = hmacHasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Shortcut var hasher = this._hasher; // Compute HMAC var innerHash = hasher.finalize(messageUpdate); hasher.reset(); var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); return hmac; } }); }()); })); },{"./core":48}],54:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory); } else { // Global (browser) root.CryptoJS = factory(root.CryptoJS); } }(this, function (CryptoJS) { return CryptoJS; })); },{"./aes":46,"./cipher-core":47,"./core":48,"./enc-base64":49,"./enc-utf16":50,"./evpkdf":51,"./format-hex":52,"./hmac":53,"./lib-typedarrays":55,"./md5":56,"./mode-cfb":57,"./mode-ctr":59,"./mode-ctr-gladman":58,"./mode-ecb":60,"./mode-ofb":61,"./pad-ansix923":62,"./pad-iso10126":63,"./pad-iso97971":64,"./pad-nopadding":65,"./pad-zeropadding":66,"./pbkdf2":67,"./rabbit":69,"./rabbit-legacy":68,"./rc4":70,"./ripemd160":71,"./sha1":72,"./sha224":73,"./sha256":74,"./sha3":75,"./sha384":76,"./sha512":77,"./tripledes":78,"./x64-core":79}],55:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Check if typed arrays are supported if (typeof ArrayBuffer != 'function') { return; } // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; // Reference original init var superInit = WordArray.init; // Augment WordArray.init to handle typed arrays var subInit = WordArray.init = function (typedArray) { // Convert buffers to uint8 if (typedArray instanceof ArrayBuffer) { typedArray = new Uint8Array(typedArray); } // Convert other array views to uint8 if ( typedArray instanceof Int8Array || (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array ) { typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); } // Handle Uint8Array if (typedArray instanceof Uint8Array) { // Shortcut var typedArrayByteLength = typedArray.byteLength; // Extract bytes var words = []; for (var i = 0; i < typedArrayByteLength; i++) { words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); } // Initialize this word array superInit.call(this, words, typedArrayByteLength); } else { // Else call normal init superInit.apply(this, arguments); } }; subInit.prototype = WordArray; }()); return CryptoJS.lib.WordArray; })); },{"./core":48}],56:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var T = []; // Compute constants (function () { for (var i = 0; i < 64; i++) { T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; } }()); /** * MD5 hash algorithm. */ var MD5 = C_algo.MD5 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 ]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcuts var H = this._hash.words; var M_offset_0 = M[offset + 0]; var M_offset_1 = M[offset + 1]; var M_offset_2 = M[offset + 2]; var M_offset_3 = M[offset + 3]; var M_offset_4 = M[offset + 4]; var M_offset_5 = M[offset + 5]; var M_offset_6 = M[offset + 6]; var M_offset_7 = M[offset + 7]; var M_offset_8 = M[offset + 8]; var M_offset_9 = M[offset + 9]; var M_offset_10 = M[offset + 10]; var M_offset_11 = M[offset + 11]; var M_offset_12 = M[offset + 12]; var M_offset_13 = M[offset + 13]; var M_offset_14 = M[offset + 14]; var M_offset_15 = M[offset + 15]; // Working varialbes var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; // Computation a = FF(a, b, c, d, M_offset_0, 7, T[0]); d = FF(d, a, b, c, M_offset_1, 12, T[1]); c = FF(c, d, a, b, M_offset_2, 17, T[2]); b = FF(b, c, d, a, M_offset_3, 22, T[3]); a = FF(a, b, c, d, M_offset_4, 7, T[4]); d = FF(d, a, b, c, M_offset_5, 12, T[5]); c = FF(c, d, a, b, M_offset_6, 17, T[6]); b = FF(b, c, d, a, M_offset_7, 22, T[7]); a = FF(a, b, c, d, M_offset_8, 7, T[8]); d = FF(d, a, b, c, M_offset_9, 12, T[9]); c = FF(c, d, a, b, M_offset_10, 17, T[10]); b = FF(b, c, d, a, M_offset_11, 22, T[11]); a = FF(a, b, c, d, M_offset_12, 7, T[12]); d = FF(d, a, b, c, M_offset_13, 12, T[13]); c = FF(c, d, a, b, M_offset_14, 17, T[14]); b = FF(b, c, d, a, M_offset_15, 22, T[15]); a = GG(a, b, c, d, M_offset_1, 5, T[16]); d = GG(d, a, b, c, M_offset_6, 9, T[17]); c = GG(c, d, a, b, M_offset_11, 14, T[18]); b = GG(b, c, d, a, M_offset_0, 20, T[19]); a = GG(a, b, c, d, M_offset_5, 5, T[20]); d = GG(d, a, b, c, M_offset_10, 9, T[21]); c = GG(c, d, a, b, M_offset_15, 14, T[22]); b = GG(b, c, d, a, M_offset_4, 20, T[23]); a = GG(a, b, c, d, M_offset_9, 5, T[24]); d = GG(d, a, b, c, M_offset_14, 9, T[25]); c = GG(c, d, a, b, M_offset_3, 14, T[26]); b = GG(b, c, d, a, M_offset_8, 20, T[27]); a = GG(a, b, c, d, M_offset_13, 5, T[28]); d = GG(d, a, b, c, M_offset_2, 9, T[29]); c = GG(c, d, a, b, M_offset_7, 14, T[30]); b = GG(b, c, d, a, M_offset_12, 20, T[31]); a = HH(a, b, c, d, M_offset_5, 4, T[32]); d = HH(d, a, b, c, M_offset_8, 11, T[33]); c = HH(c, d, a, b, M_offset_11, 16, T[34]); b = HH(b, c, d, a, M_offset_14, 23, T[35]); a = HH(a, b, c, d, M_offset_1, 4, T[36]); d = HH(d, a, b, c, M_offset_4, 11, T[37]); c = HH(c, d, a, b, M_offset_7, 16, T[38]); b = HH(b, c, d, a, M_offset_10, 23, T[39]); a = HH(a, b, c, d, M_offset_13, 4, T[40]); d = HH(d, a, b, c, M_offset_0, 11, T[41]); c = HH(c, d, a, b, M_offset_3, 16, T[42]); b = HH(b, c, d, a, M_offset_6, 23, T[43]); a = HH(a, b, c, d, M_offset_9, 4, T[44]); d = HH(d, a, b, c, M_offset_12, 11, T[45]); c = HH(c, d, a, b, M_offset_15, 16, T[46]); b = HH(b, c, d, a, M_offset_2, 23, T[47]); a = II(a, b, c, d, M_offset_0, 6, T[48]); d = II(d, a, b, c, M_offset_7, 10, T[49]); c = II(c, d, a, b, M_offset_14, 15, T[50]); b = II(b, c, d, a, M_offset_5, 21, T[51]); a = II(a, b, c, d, M_offset_12, 6, T[52]); d = II(d, a, b, c, M_offset_3, 10, T[53]); c = II(c, d, a, b, M_offset_10, 15, T[54]); b = II(b, c, d, a, M_offset_1, 21, T[55]); a = II(a, b, c, d, M_offset_8, 6, T[56]); d = II(d, a, b, c, M_offset_15, 10, T[57]); c = II(c, d, a, b, M_offset_6, 15, T[58]); b = II(b, c, d, a, M_offset_13, 21, T[59]); a = II(a, b, c, d, M_offset_4, 6, T[60]); d = II(d, a, b, c, M_offset_11, 10, T[61]); c = II(c, d, a, b, M_offset_2, 15, T[62]); b = II(b, c, d, a, M_offset_9, 21, T[63]); // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); var nBitsTotalL = nBitsTotal; dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) ); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 4; i++) { // Shortcut var H_i = H[i]; H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function FF(a, b, c, d, x, s, t) { var n = a + ((b & c) | (~b & d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function GG(a, b, c, d, x, s, t) { var n = a + ((b & d) | (c & ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function HH(a, b, c, d, x, s, t) { var n = a + (b ^ c ^ d) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function II(a, b, c, d, x, s, t) { var n = a + (c ^ (b | ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.MD5('message'); * var hash = CryptoJS.MD5(wordArray); */ C.MD5 = Hasher._createHelper(MD5); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacMD5(message, key); */ C.HmacMD5 = Hasher._createHmacHelper(MD5); }(Math)); return CryptoJS.MD5; })); },{"./core":48}],57:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher Feedback block mode. */ CryptoJS.mode.CFB = (function () { var CFB = CryptoJS.lib.BlockCipherMode.extend(); CFB.Encryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); CFB.Decryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // This block becomes the previous block this._prevBlock = thisBlock; } }); function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { // Shortcut var iv = this._iv; // Generate keystream if (iv) { var keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } else { var keystream = this._prevBlock; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } return CFB; }()); return CryptoJS.mode.CFB; })); },{"./cipher-core":47,"./core":48}],58:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve * Counter block mode compatible with Dr Brian Gladman fileenc.c * derived from CryptoJS.mode.CTR * Jan Hruby jhruby.web@gmail.com */ CryptoJS.mode.CTRGladman = (function () { var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); function incWord(word) { if (((word >> 24) & 0xff) === 0xff) { //overflow var b1 = (word >> 16)&0xff; var b2 = (word >> 8)&0xff; var b3 = word & 0xff; if (b1 === 0xff) // overflow b1 { b1 = 0; if (b2 === 0xff) { b2 = 0; if (b3 === 0xff) { b3 = 0; } else { ++b3; } } else { ++b2; } } else { ++b1; } word = 0; word += (b1 << 16); word += (b2 << 8); word += b3; } else { word += (0x01 << 24); } return word; } function incCounter(counter) { if ((counter[0] = incWord(counter[0])) === 0) { // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 counter[1] = incWord(counter[1]); } return counter; } var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } incCounter(counter); var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTRGladman.Decryptor = Encryptor; return CTRGladman; }()); return CryptoJS.mode.CTRGladman; })); },{"./cipher-core":47,"./core":48}],59:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Counter block mode. */ CryptoJS.mode.CTR = (function () { var CTR = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = CTR.Encryptor = CTR.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Increment counter counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTR.Decryptor = Encryptor; return CTR; }()); return CryptoJS.mode.CTR; })); },{"./cipher-core":47,"./core":48}],60:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Electronic Codebook block mode. */ CryptoJS.mode.ECB = (function () { var ECB = CryptoJS.lib.BlockCipherMode.extend(); ECB.Encryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.encryptBlock(words, offset); } }); ECB.Decryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.decryptBlock(words, offset); } }); return ECB; }()); return CryptoJS.mode.ECB; })); },{"./cipher-core":47,"./core":48}],61:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Output Feedback block mode. */ CryptoJS.mode.OFB = (function () { var OFB = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = OFB.Encryptor = OFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var keystream = this._keystream; // Generate keystream if (iv) { keystream = this._keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); OFB.Decryptor = Encryptor; return OFB; }()); return CryptoJS.mode.OFB; })); },{"./cipher-core":47,"./core":48}],62:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ANSI X.923 padding strategy. */ CryptoJS.pad.AnsiX923 = { pad: function (data, blockSize) { // Shortcuts var dataSigBytes = data.sigBytes; var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; // Compute last byte position var lastBytePos = dataSigBytes + nPaddingBytes - 1; // Pad data.clamp(); data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); data.sigBytes += nPaddingBytes; }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Ansix923; })); },{"./cipher-core":47,"./core":48}],63:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO 10126 padding strategy. */ CryptoJS.pad.Iso10126 = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Pad data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Iso10126; })); },{"./cipher-core":47,"./core":48}],64:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO/IEC 9797-1 Padding Method 2. */ CryptoJS.pad.Iso97971 = { pad: function (data, blockSize) { // Add 0x80 byte data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); // Zero pad the rest CryptoJS.pad.ZeroPadding.pad(data, blockSize); }, unpad: function (data) { // Remove zero padding CryptoJS.pad.ZeroPadding.unpad(data); // Remove one more byte -- the 0x80 byte data.sigBytes--; } }; return CryptoJS.pad.Iso97971; })); },{"./cipher-core":47,"./core":48}],65:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * A noop padding strategy. */ CryptoJS.pad.NoPadding = { pad: function () { }, unpad: function () { } }; return CryptoJS.pad.NoPadding; })); },{"./cipher-core":47,"./core":48}],66:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Zero padding strategy. */ CryptoJS.pad.ZeroPadding = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Pad data.clamp(); data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); }, unpad: function (data) { // Shortcut var dataWords = data.words; // Unpad var i = data.sigBytes - 1; while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { i--; } data.sigBytes = i + 1; } }; return CryptoJS.pad.ZeroPadding; })); },{"./cipher-core":47,"./core":48}],67:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA1 = C_algo.SHA1; var HMAC = C_algo.HMAC; /** * Password-Based Key Derivation Function 2 algorithm. */ var PBKDF2 = C_algo.PBKDF2 = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hasher to use. Default: SHA1 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: SHA1, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.PBKDF2.create(); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init HMAC var hmac = HMAC.create(cfg.hasher, password); // Initial values var derivedKey = WordArray.create(); var blockIndex = WordArray.create([0x00000001]); // Shortcuts var derivedKeyWords = derivedKey.words; var blockIndexWords = blockIndex.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { var block = hmac.update(salt).finalize(blockIndex); hmac.reset(); // Shortcuts var blockWords = block.words; var blockWordsLength = blockWords.length; // Iterations var intermediate = block; for (var i = 1; i < iterations; i++) { intermediate = hmac.finalize(intermediate); hmac.reset(); // Shortcut var intermediateWords = intermediate.words; // XOR intermediate with block for (var j = 0; j < blockWordsLength; j++) { blockWords[j] ^= intermediateWords[j]; } } derivedKey.concat(block); blockIndexWords[0]++; } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.PBKDF2(password, salt); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); */ C.PBKDF2 = function (password, salt, cfg) { return PBKDF2.create(cfg).compute(password, salt); }; }()); return CryptoJS.PBKDF2; })); },{"./core":48,"./hmac":53,"./sha1":72}],68:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm. * * This is a legacy version that neglected to convert the key to little-endian. * This error doesn't affect the cipher's security, * but it does affect its compatibility with other implementations. */ var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); */ C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); }()); return CryptoJS.RabbitLegacy; })); },{"./cipher-core":47,"./core":48,"./enc-base64":49,"./evpkdf":51,"./md5":56}],69:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm */ var Rabbit = C_algo.Rabbit = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Swap endian for (var i = 0; i < 4; i++) { K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); } // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); */ C.Rabbit = StreamCipher._createHelper(Rabbit); }()); return CryptoJS.Rabbit; })); },{"./cipher-core":47,"./core":48,"./enc-base64":49,"./evpkdf":51,"./md5":56}],70:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; /** * RC4 stream cipher algorithm. */ var RC4 = C_algo.RC4 = StreamCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySigBytes = key.sigBytes; // Init sbox var S = this._S = []; for (var i = 0; i < 256; i++) { S[i] = i; } // Key setup for (var i = 0, j = 0; i < 256; i++) { var keyByteIndex = i % keySigBytes; var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; j = (j + S[i] + keyByte) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; } // Counters this._i = this._j = 0; }, _doProcessBlock: function (M, offset) { M[offset] ^= generateKeystreamWord.call(this); }, keySize: 256/32, ivSize: 0 }); function generateKeystreamWord() { // Shortcuts var S = this._S; var i = this._i; var j = this._j; // Generate keystream word var keystreamWord = 0; for (var n = 0; n < 4; n++) { i = (i + 1) % 256; j = (j + S[i]) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); } // Update counters this._i = i; this._j = j; return keystreamWord; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); */ C.RC4 = StreamCipher._createHelper(RC4); /** * Modified RC4 stream cipher algorithm. */ var RC4Drop = C_algo.RC4Drop = RC4.extend({ /** * Configuration options. * * @property {number} drop The number of keystream words to drop. Default 192 */ cfg: RC4.cfg.extend({ drop: 192 }), _doReset: function () { RC4._doReset.call(this); // Drop for (var i = this.cfg.drop; i > 0; i--) { generateKeystreamWord.call(this); } } }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); */ C.RC4Drop = StreamCipher._createHelper(RC4Drop); }()); return CryptoJS.RC4; })); },{"./cipher-core":47,"./core":48,"./enc-base64":49,"./evpkdf":51,"./md5":56}],71:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var _zl = WordArray.create([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); var _zr = WordArray.create([ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); var _sl = WordArray.create([ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); var _sr = WordArray.create([ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); /** * RIPEMD160 hash algorithm. */ var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ _doReset: function () { this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; // Swap M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcut var H = this._hash.words; var hl = _hl.words; var hr = _hr.words; var zl = _zl.words; var zr = _zr.words; var sl = _sl.words; var sr = _sr.words; // Working variables var al, bl, cl, dl, el; var ar, br, cr, dr, er; ar = al = H[0]; br = bl = H[1]; cr = cl = H[2]; dr = dl = H[3]; er = el = H[4]; // Computation var t; for (var i = 0; i < 80; i += 1) { t = (al + M[offset+zl[i]])|0; if (i<16){ t += f1(bl,cl,dl) + hl[0]; } else if (i<32) { t += f2(bl,cl,dl) + hl[1]; } else if (i<48) { t += f3(bl,cl,dl) + hl[2]; } else if (i<64) { t += f4(bl,cl,dl) + hl[3]; } else {// if (i<80) { t += f5(bl,cl,dl) + hl[4]; } t = t|0; t = rotl(t,sl[i]); t = (t+el)|0; al = el; el = dl; dl = rotl(cl, 10); cl = bl; bl = t; t = (ar + M[offset+zr[i]])|0; if (i<16){ t += f5(br,cr,dr) + hr[0]; } else if (i<32) { t += f4(br,cr,dr) + hr[1]; } else if (i<48) { t += f3(br,cr,dr) + hr[2]; } else if (i<64) { t += f2(br,cr,dr) + hr[3]; } else {// if (i<80) { t += f1(br,cr,dr) + hr[4]; } t = t|0; t = rotl(t,sr[i]) ; t = (t+er)|0; ar = er; er = dr; dr = rotl(cr, 10); cr = br; br = t; } // Intermediate hash value t = (H[1] + cl + dr)|0; H[1] = (H[2] + dl + er)|0; H[2] = (H[3] + el + ar)|0; H[3] = (H[4] + al + br)|0; H[4] = (H[0] + bl + cr)|0; H[0] = t; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 5; i++) { // Shortcut var H_i = H[i]; // Swap H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function f1(x, y, z) { return ((x) ^ (y) ^ (z)); } function f2(x, y, z) { return (((x)&(y)) | ((~x)&(z))); } function f3(x, y, z) { return (((x) | (~(y))) ^ (z)); } function f4(x, y, z) { return (((x) & (z)) | ((y)&(~(z)))); } function f5(x, y, z) { return ((x) ^ ((y) |(~(z)))); } function rotl(x,n) { return (x<<n) | (x>>>(32-n)); } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.RIPEMD160('message'); * var hash = CryptoJS.RIPEMD160(wordArray); */ C.RIPEMD160 = Hasher._createHelper(RIPEMD160); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacRIPEMD160(message, key); */ C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); }(Math)); return CryptoJS.RIPEMD160; })); },{"./core":48}],72:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Reusable object var W = []; /** * SHA-1 hash algorithm. */ var SHA1 = C_algo.SHA1 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; // Computation for (var i = 0; i < 80; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; W[i] = (n << 1) | (n >>> 31); } var t = ((a << 5) | (a >>> 27)) + e + W[i]; if (i < 20) { t += ((b & c) | (~b & d)) + 0x5a827999; } else if (i < 40) { t += (b ^ c ^ d) + 0x6ed9eba1; } else if (i < 60) { t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; } else /* if (i < 80) */ { t += (b ^ c ^ d) - 0x359d3e2a; } e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA1('message'); * var hash = CryptoJS.SHA1(wordArray); */ C.SHA1 = Hasher._createHelper(SHA1); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA1(message, key); */ C.HmacSHA1 = Hasher._createHmacHelper(SHA1); }()); return CryptoJS.SHA1; })); },{"./core":48}],73:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha256"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA256 = C_algo.SHA256; /** * SHA-224 hash algorithm. */ var SHA224 = C_algo.SHA224 = SHA256.extend({ _doReset: function () { this._hash = new WordArray.init([ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]); }, _doFinalize: function () { var hash = SHA256._doFinalize.call(this); hash.sigBytes -= 4; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA224('message'); * var hash = CryptoJS.SHA224(wordArray); */ C.SHA224 = SHA256._createHelper(SHA224); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA224(message, key); */ C.HmacSHA224 = SHA256._createHmacHelper(SHA224); }()); return CryptoJS.SHA224; })); },{"./core":48,"./sha256":74}],74:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Initialization and round constants tables var H = []; var K = []; // Compute constants (function () { function isPrime(n) { var sqrtN = Math.sqrt(n); for (var factor = 2; factor <= sqrtN; factor++) { if (!(n % factor)) { return false; } } return true; } function getFractionalBits(n) { return ((n - (n | 0)) * 0x100000000) | 0; } var n = 2; var nPrime = 0; while (nPrime < 64) { if (isPrime(n)) { if (nPrime < 8) { H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); } K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); nPrime++; } n++; } }()); // Reusable object var W = []; /** * SHA-256 hash algorithm. */ var SHA256 = C_algo.SHA256 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init(H.slice(0)); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; var f = H[5]; var g = H[6]; var h = H[7]; // Computation for (var i = 0; i < 64; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var gamma0x = W[i - 15]; var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ ((gamma0x << 14) | (gamma0x >>> 18)) ^ (gamma0x >>> 3); var gamma1x = W[i - 2]; var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ ((gamma1x << 13) | (gamma1x >>> 19)) ^ (gamma1x >>> 10); W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; } var ch = (e & f) ^ (~e & g); var maj = (a & b) ^ (a & c) ^ (b & c); var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); var t1 = h + sigma1 + ch + K[i] + W[i]; var t2 = sigma0 + maj; h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA256('message'); * var hash = CryptoJS.SHA256(wordArray); */ C.SHA256 = Hasher._createHelper(SHA256); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA256(message, key); */ C.HmacSHA256 = Hasher._createHmacHelper(SHA256); }(Math)); return CryptoJS.SHA256; })); },{"./core":48}],75:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var C_algo = C.algo; // Constants tables var RHO_OFFSETS = []; var PI_INDEXES = []; var ROUND_CONSTANTS = []; // Compute Constants (function () { // Compute rho offset constants var x = 1, y = 0; for (var t = 0; t < 24; t++) { RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; var newX = y % 5; var newY = (2 * x + 3 * y) % 5; x = newX; y = newY; } // Compute pi index constants for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; } } // Compute round constants var LFSR = 0x01; for (var i = 0; i < 24; i++) { var roundConstantMsw = 0; var roundConstantLsw = 0; for (var j = 0; j < 7; j++) { if (LFSR & 0x01) { var bitPosition = (1 << j) - 1; if (bitPosition < 32) { roundConstantLsw ^= 1 << bitPosition; } else /* if (bitPosition >= 32) */ { roundConstantMsw ^= 1 << (bitPosition - 32); } } // Compute next LFSR if (LFSR & 0x80) { // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 LFSR = (LFSR << 1) ^ 0x71; } else { LFSR <<= 1; } } ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); } }()); // Reusable objects for temporary values var T = []; (function () { for (var i = 0; i < 25; i++) { T[i] = X64Word.create(); } }()); /** * SHA-3 hash algorithm. */ var SHA3 = C_algo.SHA3 = Hasher.extend({ /** * Configuration options. * * @property {number} outputLength * The desired number of bits in the output hash. * Only values permitted are: 224, 256, 384, 512. * Default: 512 */ cfg: Hasher.cfg.extend({ outputLength: 512 }), _doReset: function () { var state = this._state = [] for (var i = 0; i < 25; i++) { state[i] = new X64Word.init(); } this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; }, _doProcessBlock: function (M, offset) { // Shortcuts var state = this._state; var nBlockSizeLanes = this.blockSize / 2; // Absorb for (var i = 0; i < nBlockSizeLanes; i++) { // Shortcuts var M2i = M[offset + 2 * i]; var M2i1 = M[offset + 2 * i + 1]; // Swap endian M2i = ( (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) ); M2i1 = ( (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) ); // Absorb message into state var lane = state[i]; lane.high ^= M2i1; lane.low ^= M2i; } // Rounds for (var round = 0; round < 24; round++) { // Theta for (var x = 0; x < 5; x++) { // Mix column lanes var tMsw = 0, tLsw = 0; for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; tMsw ^= lane.high; tLsw ^= lane.low; } // Temporary values var Tx = T[x]; Tx.high = tMsw; Tx.low = tLsw; } for (var x = 0; x < 5; x++) { // Shortcuts var Tx4 = T[(x + 4) % 5]; var Tx1 = T[(x + 1) % 5]; var Tx1Msw = Tx1.high; var Tx1Lsw = Tx1.low; // Mix surrounding columns var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; lane.high ^= tMsw; lane.low ^= tLsw; } } // Rho Pi for (var laneIndex = 1; laneIndex < 25; laneIndex++) { // Shortcuts var lane = state[laneIndex]; var laneMsw = lane.high; var laneLsw = lane.low; var rhoOffset = RHO_OFFSETS[laneIndex]; // Rotate lanes if (rhoOffset < 32) { var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); } else /* if (rhoOffset >= 32) */ { var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); } // Transpose lanes var TPiLane = T[PI_INDEXES[laneIndex]]; TPiLane.high = tMsw; TPiLane.low = tLsw; } // Rho pi at x = y = 0 var T0 = T[0]; var state0 = state[0]; T0.high = state0.high; T0.low = state0.low; // Chi for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { // Shortcuts var laneIndex = x + 5 * y; var lane = state[laneIndex]; var TLane = T[laneIndex]; var Tx1Lane = T[((x + 1) % 5) + 5 * y]; var Tx2Lane = T[((x + 2) % 5) + 5 * y]; // Mix rows lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); } } // Iota var lane = state[0]; var roundConstant = ROUND_CONSTANTS[round]; lane.high ^= roundConstant.high; lane.low ^= roundConstant.low;; } }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; var blockSizeBits = this.blockSize * 32; // Add padding dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Shortcuts var state = this._state; var outputLengthBytes = this.cfg.outputLength / 8; var outputLengthLanes = outputLengthBytes / 8; // Squeeze var hashWords = []; for (var i = 0; i < outputLengthLanes; i++) { // Shortcuts var lane = state[i]; var laneMsw = lane.high; var laneLsw = lane.low; // Swap endian laneMsw = ( (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) ); laneLsw = ( (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) ); // Squeeze state to retrieve hash hashWords.push(laneLsw); hashWords.push(laneMsw); } // Return final computed hash return new WordArray.init(hashWords, outputLengthBytes); }, clone: function () { var clone = Hasher.clone.call(this); var state = clone._state = this._state.slice(0); for (var i = 0; i < 25; i++) { state[i] = state[i].clone(); } return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA3('message'); * var hash = CryptoJS.SHA3(wordArray); */ C.SHA3 = Hasher._createHelper(SHA3); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA3(message, key); */ C.HmacSHA3 = Hasher._createHmacHelper(SHA3); }(Math)); return CryptoJS.SHA3; })); },{"./core":48,"./x64-core":79}],76:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./sha512"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; var SHA512 = C_algo.SHA512; /** * SHA-384 hash algorithm. */ var SHA384 = C_algo.SHA384 = SHA512.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) ]); }, _doFinalize: function () { var hash = SHA512._doFinalize.call(this); hash.sigBytes -= 16; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA384('message'); * var hash = CryptoJS.SHA384(wordArray); */ C.SHA384 = SHA512._createHelper(SHA384); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA384(message, key); */ C.HmacSHA384 = SHA512._createHmacHelper(SHA384); }()); return CryptoJS.SHA384; })); },{"./core":48,"./sha512":77,"./x64-core":79}],77:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; function X64Word_create() { return X64Word.create.apply(X64Word, arguments); } // Constants var K = [ X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) ]; // Reusable objects var W = []; (function () { for (var i = 0; i < 80; i++) { W[i] = X64Word_create(); } }()); /** * SHA-512 hash algorithm. */ var SHA512 = C_algo.SHA512 = Hasher.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) ]); }, _doProcessBlock: function (M, offset) { // Shortcuts var H = this._hash.words; var H0 = H[0]; var H1 = H[1]; var H2 = H[2]; var H3 = H[3]; var H4 = H[4]; var H5 = H[5]; var H6 = H[6]; var H7 = H[7]; var H0h = H0.high; var H0l = H0.low; var H1h = H1.high; var H1l = H1.low; var H2h = H2.high; var H2l = H2.low; var H3h = H3.high; var H3l = H3.low; var H4h = H4.high; var H4l = H4.low; var H5h = H5.high; var H5l = H5.low; var H6h = H6.high; var H6l = H6.low; var H7h = H7.high; var H7l = H7.low; // Working variables var ah = H0h; var al = H0l; var bh = H1h; var bl = H1l; var ch = H2h; var cl = H2l; var dh = H3h; var dl = H3l; var eh = H4h; var el = H4l; var fh = H5h; var fl = H5l; var gh = H6h; var gl = H6l; var hh = H7h; var hl = H7l; // Rounds for (var i = 0; i < 80; i++) { // Shortcut var Wi = W[i]; // Extend message if (i < 16) { var Wih = Wi.high = M[offset + i * 2] | 0; var Wil = Wi.low = M[offset + i * 2 + 1] | 0; } else { // Gamma0 var gamma0x = W[i - 15]; var gamma0xh = gamma0x.high; var gamma0xl = gamma0x.low; var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); // Gamma1 var gamma1x = W[i - 2]; var gamma1xh = gamma1x.high; var gamma1xl = gamma1x.low; var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] var Wi7 = W[i - 7]; var Wi7h = Wi7.high; var Wi7l = Wi7.low; var Wi16 = W[i - 16]; var Wi16h = Wi16.high; var Wi16l = Wi16.low; var Wil = gamma0l + Wi7l; var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); var Wil = Wil + gamma1l; var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); var Wil = Wil + Wi16l; var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); Wi.high = Wih; Wi.low = Wil; } var chh = (eh & fh) ^ (~eh & gh); var chl = (el & fl) ^ (~el & gl); var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); var majl = (al & bl) ^ (al & cl) ^ (bl & cl); var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); // t1 = h + sigma1 + ch + K[i] + W[i] var Ki = K[i]; var Kih = Ki.high; var Kil = Ki.low; var t1l = hl + sigma1l; var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); var t1l = t1l + chl; var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); var t1l = t1l + Kil; var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); var t1l = t1l + Wil; var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); // t2 = sigma0 + maj var t2l = sigma0l + majl; var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); // Update working variables hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; el = (dl + t1l) | 0; eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; al = (t1l + t2l) | 0; ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; } // Intermediate hash value H0l = H0.low = (H0l + al); H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); H1l = H1.low = (H1l + bl); H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); H2l = H2.low = (H2l + cl); H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); H3l = H3.low = (H3l + dl); H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); H4l = H4.low = (H4l + el); H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); H5l = H5.low = (H5l + fl); H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); H6l = H6.low = (H6l + gl); H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); H7l = H7.low = (H7l + hl); H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Convert hash to 32-bit word array before returning var hash = this._hash.toX32(); // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; }, blockSize: 1024/32 }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA512('message'); * var hash = CryptoJS.SHA512(wordArray); */ C.SHA512 = Hasher._createHelper(SHA512); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA512(message, key); */ C.HmacSHA512 = Hasher._createHmacHelper(SHA512); }()); return CryptoJS.SHA512; })); },{"./core":48,"./x64-core":79}],78:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Permuted Choice 1 constants var PC1 = [ 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 ]; // Permuted Choice 2 constants var PC2 = [ 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 ]; // Cumulative bit shift constants var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; // SBOXes and round permutation constants var SBOX_P = [ { 0x0: 0x808200, 0x10000000: 0x8000, 0x20000000: 0x808002, 0x30000000: 0x2, 0x40000000: 0x200, 0x50000000: 0x808202, 0x60000000: 0x800202, 0x70000000: 0x800000, 0x80000000: 0x202, 0x90000000: 0x800200, 0xa0000000: 0x8200, 0xb0000000: 0x808000, 0xc0000000: 0x8002, 0xd0000000: 0x800002, 0xe0000000: 0x0, 0xf0000000: 0x8202, 0x8000000: 0x0, 0x18000000: 0x808202, 0x28000000: 0x8202, 0x38000000: 0x8000, 0x48000000: 0x808200, 0x58000000: 0x200, 0x68000000: 0x808002, 0x78000000: 0x2, 0x88000000: 0x800200, 0x98000000: 0x8200, 0xa8000000: 0x808000, 0xb8000000: 0x800202, 0xc8000000: 0x800002, 0xd8000000: 0x8002, 0xe8000000: 0x202, 0xf8000000: 0x800000, 0x1: 0x8000, 0x10000001: 0x2, 0x20000001: 0x808200, 0x30000001: 0x800000, 0x40000001: 0x808002, 0x50000001: 0x8200, 0x60000001: 0x200, 0x70000001: 0x800202, 0x80000001: 0x808202, 0x90000001: 0x808000, 0xa0000001: 0x800002, 0xb0000001: 0x8202, 0xc0000001: 0x202, 0xd0000001: 0x800200, 0xe0000001: 0x8002, 0xf0000001: 0x0, 0x8000001: 0x808202, 0x18000001: 0x808000, 0x28000001: 0x800000, 0x38000001: 0x200, 0x48000001: 0x8000, 0x58000001: 0x800002, 0x68000001: 0x2, 0x78000001: 0x8202, 0x88000001: 0x8002, 0x98000001: 0x800202, 0xa8000001: 0x202, 0xb8000001: 0x808200, 0xc8000001: 0x800200, 0xd8000001: 0x0, 0xe8000001: 0x8200, 0xf8000001: 0x808002 }, { 0x0: 0x40084010, 0x1000000: 0x4000, 0x2000000: 0x80000, 0x3000000: 0x40080010, 0x4000000: 0x40000010, 0x5000000: 0x40084000, 0x6000000: 0x40004000, 0x7000000: 0x10, 0x8000000: 0x84000, 0x9000000: 0x40004010, 0xa000000: 0x40000000, 0xb000000: 0x84010, 0xc000000: 0x80010, 0xd000000: 0x0, 0xe000000: 0x4010, 0xf000000: 0x40080000, 0x800000: 0x40004000, 0x1800000: 0x84010, 0x2800000: 0x10, 0x3800000: 0x40004010, 0x4800000: 0x40084010, 0x5800000: 0x40000000, 0x6800000: 0x80000, 0x7800000: 0x40080010, 0x8800000: 0x80010, 0x9800000: 0x0, 0xa800000: 0x4000, 0xb800000: 0x40080000, 0xc800000: 0x40000010, 0xd800000: 0x84000, 0xe800000: 0x40084000, 0xf800000: 0x4010, 0x10000000: 0x0, 0x11000000: 0x40080010, 0x12000000: 0x40004010, 0x13000000: 0x40084000, 0x14000000: 0x40080000, 0x15000000: 0x10, 0x16000000: 0x84010, 0x17000000: 0x4000, 0x18000000: 0x4010, 0x19000000: 0x80000, 0x1a000000: 0x80010, 0x1b000000: 0x40000010, 0x1c000000: 0x84000, 0x1d000000: 0x40004000, 0x1e000000: 0x40000000, 0x1f000000: 0x40084010, 0x10800000: 0x84010, 0x11800000: 0x80000, 0x12800000: 0x40080000, 0x13800000: 0x4000, 0x14800000: 0x40004000, 0x15800000: 0x40084010, 0x16800000: 0x10, 0x17800000: 0x40000000, 0x18800000: 0x40084000, 0x19800000: 0x40000010, 0x1a800000: 0x40004010, 0x1b800000: 0x80010, 0x1c800000: 0x0, 0x1d800000: 0x4010, 0x1e800000: 0x40080010, 0x1f800000: 0x84000 }, { 0x0: 0x104, 0x100000: 0x0, 0x200000: 0x4000100, 0x300000: 0x10104, 0x400000: 0x10004, 0x500000: 0x4000004, 0x600000: 0x4010104, 0x700000: 0x4010000, 0x800000: 0x4000000, 0x900000: 0x4010100, 0xa00000: 0x10100, 0xb00000: 0x4010004, 0xc00000: 0x4000104, 0xd00000: 0x10000, 0xe00000: 0x4, 0xf00000: 0x100, 0x80000: 0x4010100, 0x180000: 0x4010004, 0x280000: 0x0, 0x380000: 0x4000100, 0x480000: 0x4000004, 0x580000: 0x10000, 0x680000: 0x10004, 0x780000: 0x104, 0x880000: 0x4, 0x980000: 0x100, 0xa80000: 0x4010000, 0xb80000: 0x10104, 0xc80000: 0x10100, 0xd80000: 0x4000104, 0xe80000: 0x4010104, 0xf80000: 0x4000000, 0x1000000: 0x4010100, 0x1100000: 0x10004, 0x1200000: 0x10000, 0x1300000: 0x4000100, 0x1400000: 0x100, 0x1500000: 0x4010104, 0x1600000: 0x4000004, 0x1700000: 0x0, 0x1800000: 0x4000104, 0x1900000: 0x4000000, 0x1a00000: 0x4, 0x1b00000: 0x10100, 0x1c00000: 0x4010000, 0x1d00000: 0x104, 0x1e00000: 0x10104, 0x1f00000: 0x4010004, 0x1080000: 0x4000000, 0x1180000: 0x104, 0x1280000: 0x4010100, 0x1380000: 0x0, 0x1480000: 0x10004, 0x1580000: 0x4000100, 0x1680000: 0x100, 0x1780000: 0x4010004, 0x1880000: 0x10000, 0x1980000: 0x4010104, 0x1a80000: 0x10104, 0x1b80000: 0x4000004, 0x1c80000: 0x4000104, 0x1d80000: 0x4010000, 0x1e80000: 0x4, 0x1f80000: 0x10100 }, { 0x0: 0x80401000, 0x10000: 0x80001040, 0x20000: 0x401040, 0x30000: 0x80400000, 0x40000: 0x0, 0x50000: 0x401000, 0x60000: 0x80000040, 0x70000: 0x400040, 0x80000: 0x80000000, 0x90000: 0x400000, 0xa0000: 0x40, 0xb0000: 0x80001000, 0xc0000: 0x80400040, 0xd0000: 0x1040, 0xe0000: 0x1000, 0xf0000: 0x80401040, 0x8000: 0x80001040, 0x18000: 0x40, 0x28000: 0x80400040, 0x38000: 0x80001000, 0x48000: 0x401000, 0x58000: 0x80401040, 0x68000: 0x0, 0x78000: 0x80400000, 0x88000: 0x1000, 0x98000: 0x80401000, 0xa8000: 0x400000, 0xb8000: 0x1040, 0xc8000: 0x80000000, 0xd8000: 0x400040, 0xe8000: 0x401040, 0xf8000: 0x80000040, 0x100000: 0x400040, 0x110000: 0x401000, 0x120000: 0x80000040, 0x130000: 0x0, 0x140000: 0x1040, 0x150000: 0x80400040, 0x160000: 0x80401000, 0x170000: 0x80001040, 0x180000: 0x80401040, 0x190000: 0x80000000, 0x1a0000: 0x80400000, 0x1b0000: 0x401040, 0x1c0000: 0x80001000, 0x1d0000: 0x400000, 0x1e0000: 0x40, 0x1f0000: 0x1000, 0x108000: 0x80400000, 0x118000: 0x80401040, 0x128000: 0x0, 0x138000: 0x401000, 0x148000: 0x400040, 0x158000: 0x80000000, 0x168000: 0x80001040, 0x178000: 0x40, 0x188000: 0x80000040, 0x198000: 0x1000, 0x1a8000: 0x80001000, 0x1b8000: 0x80400040, 0x1c8000: 0x1040, 0x1d8000: 0x80401000, 0x1e8000: 0x400000, 0x1f8000: 0x401040 }, { 0x0: 0x80, 0x1000: 0x1040000, 0x2000: 0x40000, 0x3000: 0x20000000, 0x4000: 0x20040080, 0x5000: 0x1000080, 0x6000: 0x21000080, 0x7000: 0x40080, 0x8000: 0x1000000, 0x9000: 0x20040000, 0xa000: 0x20000080, 0xb000: 0x21040080, 0xc000: 0x21040000, 0xd000: 0x0, 0xe000: 0x1040080, 0xf000: 0x21000000, 0x800: 0x1040080, 0x1800: 0x21000080, 0x2800: 0x80, 0x3800: 0x1040000, 0x4800: 0x40000, 0x5800: 0x20040080, 0x6800: 0x21040000, 0x7800: 0x20000000, 0x8800: 0x20040000, 0x9800: 0x0, 0xa800: 0x21040080, 0xb800: 0x1000080, 0xc800: 0x20000080, 0xd800: 0x21000000, 0xe800: 0x1000000, 0xf800: 0x40080, 0x10000: 0x40000, 0x11000: 0x80, 0x12000: 0x20000000, 0x13000: 0x21000080, 0x14000: 0x1000080, 0x15000: 0x21040000, 0x16000: 0x20040080, 0x17000: 0x1000000, 0x18000: 0x21040080, 0x19000: 0x21000000, 0x1a000: 0x1040000, 0x1b000: 0x20040000, 0x1c000: 0x40080, 0x1d000: 0x20000080, 0x1e000: 0x0, 0x1f000: 0x1040080, 0x10800: 0x21000080, 0x11800: 0x1000000, 0x12800: 0x1040000, 0x13800: 0x20040080, 0x14800: 0x20000000, 0x15800: 0x1040080, 0x16800: 0x80, 0x17800: 0x21040000, 0x18800: 0x40080, 0x19800: 0x21040080, 0x1a800: 0x0, 0x1b800: 0x21000000, 0x1c800: 0x1000080, 0x1d800: 0x40000, 0x1e800: 0x20040000, 0x1f800: 0x20000080 }, { 0x0: 0x10000008, 0x100: 0x2000, 0x200: 0x10200000, 0x300: 0x10202008, 0x400: 0x10002000, 0x500: 0x200000, 0x600: 0x200008, 0x700: 0x10000000, 0x800: 0x0, 0x900: 0x10002008, 0xa00: 0x202000, 0xb00: 0x8, 0xc00: 0x10200008, 0xd00: 0x202008, 0xe00: 0x2008, 0xf00: 0x10202000, 0x80: 0x10200000, 0x180: 0x10202008, 0x280: 0x8, 0x380: 0x200000, 0x480: 0x202008, 0x580: 0x10000008, 0x680: 0x10002000, 0x780: 0x2008, 0x880: 0x200008, 0x980: 0x2000, 0xa80: 0x10002008, 0xb80: 0x10200008, 0xc80: 0x0, 0xd80: 0x10202000, 0xe80: 0x202000, 0xf80: 0x10000000, 0x1000: 0x10002000, 0x1100: 0x10200008, 0x1200: 0x10202008, 0x1300: 0x2008, 0x1400: 0x200000, 0x1500: 0x10000000, 0x1600: 0x10000008, 0x1700: 0x202000, 0x1800: 0x202008, 0x1900: 0x0, 0x1a00: 0x8, 0x1b00: 0x10200000, 0x1c00: 0x2000, 0x1d00: 0x10002008, 0x1e00: 0x10202000, 0x1f00: 0x200008, 0x1080: 0x8, 0x1180: 0x202000, 0x1280: 0x200000, 0x1380: 0x10000008, 0x1480: 0x10002000, 0x1580: 0x2008, 0x1680: 0x10202008, 0x1780: 0x10200000, 0x1880: 0x10202000, 0x1980: 0x10200008, 0x1a80: 0x2000, 0x1b80: 0x202008, 0x1c80: 0x200008, 0x1d80: 0x0, 0x1e80: 0x10000000, 0x1f80: 0x10002008 }, { 0x0: 0x100000, 0x10: 0x2000401, 0x20: 0x400, 0x30: 0x100401, 0x40: 0x2100401, 0x50: 0x0, 0x60: 0x1, 0x70: 0x2100001, 0x80: 0x2000400, 0x90: 0x100001, 0xa0: 0x2000001, 0xb0: 0x2100400, 0xc0: 0x2100000, 0xd0: 0x401, 0xe0: 0x100400, 0xf0: 0x2000000, 0x8: 0x2100001, 0x18: 0x0, 0x28: 0x2000401, 0x38: 0x2100400, 0x48: 0x100000, 0x58: 0x2000001, 0x68: 0x2000000, 0x78: 0x401, 0x88: 0x100401, 0x98: 0x2000400, 0xa8: 0x2100000, 0xb8: 0x100001, 0xc8: 0x400, 0xd8: 0x2100401, 0xe8: 0x1, 0xf8: 0x100400, 0x100: 0x2000000, 0x110: 0x100000, 0x120: 0x2000401, 0x130: 0x2100001, 0x140: 0x100001, 0x150: 0x2000400, 0x160: 0x2100400, 0x170: 0x100401, 0x180: 0x401, 0x190: 0x2100401, 0x1a0: 0x100400, 0x1b0: 0x1, 0x1c0: 0x0, 0x1d0: 0x2100000, 0x1e0: 0x2000001, 0x1f0: 0x400, 0x108: 0x100400, 0x118: 0x2000401, 0x128: 0x2100001, 0x138: 0x1, 0x148: 0x2000000, 0x158: 0x100000, 0x168: 0x401, 0x178: 0x2100400, 0x188: 0x2000001, 0x198: 0x2100000, 0x1a8: 0x0, 0x1b8: 0x2100401, 0x1c8: 0x100401, 0x1d8: 0x400, 0x1e8: 0x2000400, 0x1f8: 0x100001 }, { 0x0: 0x8000820, 0x1: 0x20000, 0x2: 0x8000000, 0x3: 0x20, 0x4: 0x20020, 0x5: 0x8020820, 0x6: 0x8020800, 0x7: 0x800, 0x8: 0x8020000, 0x9: 0x8000800, 0xa: 0x20800, 0xb: 0x8020020, 0xc: 0x820, 0xd: 0x0, 0xe: 0x8000020, 0xf: 0x20820, 0x80000000: 0x800, 0x80000001: 0x8020820, 0x80000002: 0x8000820, 0x80000003: 0x8000000, 0x80000004: 0x8020000, 0x80000005: 0x20800, 0x80000006: 0x20820, 0x80000007: 0x20, 0x80000008: 0x8000020, 0x80000009: 0x820, 0x8000000a: 0x20020, 0x8000000b: 0x8020800, 0x8000000c: 0x0, 0x8000000d: 0x8020020, 0x8000000e: 0x8000800, 0x8000000f: 0x20000, 0x10: 0x20820, 0x11: 0x8020800, 0x12: 0x20, 0x13: 0x800, 0x14: 0x8000800, 0x15: 0x8000020, 0x16: 0x8020020, 0x17: 0x20000, 0x18: 0x0, 0x19: 0x20020, 0x1a: 0x8020000, 0x1b: 0x8000820, 0x1c: 0x8020820, 0x1d: 0x20800, 0x1e: 0x820, 0x1f: 0x8000000, 0x80000010: 0x20000, 0x80000011: 0x800, 0x80000012: 0x8020020, 0x80000013: 0x20820, 0x80000014: 0x20, 0x80000015: 0x8020000, 0x80000016: 0x8000000, 0x80000017: 0x8000820, 0x80000018: 0x8020820, 0x80000019: 0x8000020, 0x8000001a: 0x8000800, 0x8000001b: 0x0, 0x8000001c: 0x20800, 0x8000001d: 0x820, 0x8000001e: 0x20020, 0x8000001f: 0x8020800 } ]; // Masks that select the SBOX input var SBOX_MASK = [ 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f ]; /** * DES block cipher algorithm. */ var DES = C_algo.DES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Select 56 bits according to PC1 var keyBits = []; for (var i = 0; i < 56; i++) { var keyBitPos = PC1[i] - 1; keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; } // Assemble 16 subkeys var subKeys = this._subKeys = []; for (var nSubKey = 0; nSubKey < 16; nSubKey++) { // Create subkey var subKey = subKeys[nSubKey] = []; // Shortcut var bitShift = BIT_SHIFTS[nSubKey]; // Select 48 bits according to PC2 for (var i = 0; i < 24; i++) { // Select from the left 28 key bits subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); // Select from the right 28 key bits subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); } // Since each subkey is applied to an expanded 32-bit input, // the subkey can be broken into 8 values scaled to 32-bits, // which allows the key to be used without expansion subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); for (var i = 1; i < 7; i++) { subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); } subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); } // Compute inverse subkeys var invSubKeys = this._invSubKeys = []; for (var i = 0; i < 16; i++) { invSubKeys[i] = subKeys[15 - i]; } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._subKeys); }, decryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._invSubKeys); }, _doCryptBlock: function (M, offset, subKeys) { // Get input this._lBlock = M[offset]; this._rBlock = M[offset + 1]; // Initial permutation exchangeLR.call(this, 4, 0x0f0f0f0f); exchangeLR.call(this, 16, 0x0000ffff); exchangeRL.call(this, 2, 0x33333333); exchangeRL.call(this, 8, 0x00ff00ff); exchangeLR.call(this, 1, 0x55555555); // Rounds for (var round = 0; round < 16; round++) { // Shortcuts var subKey = subKeys[round]; var lBlock = this._lBlock; var rBlock = this._rBlock; // Feistel function var f = 0; for (var i = 0; i < 8; i++) { f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; } this._lBlock = rBlock; this._rBlock = lBlock ^ f; } // Undo swap from last round var t = this._lBlock; this._lBlock = this._rBlock; this._rBlock = t; // Final permutation exchangeLR.call(this, 1, 0x55555555); exchangeRL.call(this, 8, 0x00ff00ff); exchangeRL.call(this, 2, 0x33333333); exchangeLR.call(this, 16, 0x0000ffff); exchangeLR.call(this, 4, 0x0f0f0f0f); // Set output M[offset] = this._lBlock; M[offset + 1] = this._rBlock; }, keySize: 64/32, ivSize: 64/32, blockSize: 64/32 }); // Swap bits across the left and right words function exchangeLR(offset, mask) { var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; this._rBlock ^= t; this._lBlock ^= t << offset; } function exchangeRL(offset, mask) { var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; this._lBlock ^= t; this._rBlock ^= t << offset; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); */ C.DES = BlockCipher._createHelper(DES); /** * Triple-DES block cipher algorithm. */ var TripleDES = C_algo.TripleDES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Create DES instances this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2))); this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4))); this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6))); }, encryptBlock: function (M, offset) { this._des1.encryptBlock(M, offset); this._des2.decryptBlock(M, offset); this._des3.encryptBlock(M, offset); }, decryptBlock: function (M, offset) { this._des3.decryptBlock(M, offset); this._des2.encryptBlock(M, offset); this._des1.decryptBlock(M, offset); }, keySize: 192/32, ivSize: 64/32, blockSize: 64/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); */ C.TripleDES = BlockCipher._createHelper(TripleDES); }()); return CryptoJS.TripleDES; })); },{"./cipher-core":47,"./core":48,"./enc-base64":49,"./evpkdf":51,"./md5":56}],79:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var X32WordArray = C_lib.WordArray; /** * x64 namespace. */ var C_x64 = C.x64 = {}; /** * A 64-bit word. */ var X64Word = C_x64.Word = Base.extend({ /** * Initializes a newly created 64-bit word. * * @param {number} high The high 32 bits. * @param {number} low The low 32 bits. * * @example * * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); */ init: function (high, low) { this.high = high; this.low = low; } /** * Bitwise NOTs this word. * * @return {X64Word} A new x64-Word object after negating. * * @example * * var negated = x64Word.not(); */ // not: function () { // var high = ~this.high; // var low = ~this.low; // return X64Word.create(high, low); // }, /** * Bitwise ANDs this word with the passed word. * * @param {X64Word} word The x64-Word to AND with this word. * * @return {X64Word} A new x64-Word object after ANDing. * * @example * * var anded = x64Word.and(anotherX64Word); */ // and: function (word) { // var high = this.high & word.high; // var low = this.low & word.low; // return X64Word.create(high, low); // }, /** * Bitwise ORs this word with the passed word. * * @param {X64Word} word The x64-Word to OR with this word. * * @return {X64Word} A new x64-Word object after ORing. * * @example * * var ored = x64Word.or(anotherX64Word); */ // or: function (word) { // var high = this.high | word.high; // var low = this.low | word.low; // return X64Word.create(high, low); // }, /** * Bitwise XORs this word with the passed word. * * @param {X64Word} word The x64-Word to XOR with this word. * * @return {X64Word} A new x64-Word object after XORing. * * @example * * var xored = x64Word.xor(anotherX64Word); */ // xor: function (word) { // var high = this.high ^ word.high; // var low = this.low ^ word.low; // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the left. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftL(25); */ // shiftL: function (n) { // if (n < 32) { // var high = (this.high << n) | (this.low >>> (32 - n)); // var low = this.low << n; // } else { // var high = this.low << (n - 32); // var low = 0; // } // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the right. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftR(7); */ // shiftR: function (n) { // if (n < 32) { // var low = (this.low >>> n) | (this.high << (32 - n)); // var high = this.high >>> n; // } else { // var low = this.high >>> (n - 32); // var high = 0; // } // return X64Word.create(high, low); // }, /** * Rotates this word n bits to the left. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotL(25); */ // rotL: function (n) { // return this.shiftL(n).or(this.shiftR(64 - n)); // }, /** * Rotates this word n bits to the right. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotR(7); */ // rotR: function (n) { // return this.shiftR(n).or(this.shiftL(64 - n)); // }, /** * Adds this word with the passed word. * * @param {X64Word} word The x64-Word to add with this word. * * @return {X64Word} A new x64-Word object after adding. * * @example * * var added = x64Word.add(anotherX64Word); */ // add: function (word) { // var low = (this.low + word.low) | 0; // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; // var high = (this.high + word.high + carry) | 0; // return X64Word.create(high, low); // } }); /** * An array of 64-bit words. * * @property {Array} words The array of CryptoJS.x64.Word objects. * @property {number} sigBytes The number of significant bytes in this word array. */ var X64WordArray = C_x64.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.x64.WordArray.create(); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ]); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ], 10); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 8; } }, /** * Converts this 64-bit word array to a 32-bit word array. * * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. * * @example * * var x32WordArray = x64WordArray.toX32(); */ toX32: function () { // Shortcuts var x64Words = this.words; var x64WordsLength = x64Words.length; // Convert var x32Words = []; for (var i = 0; i < x64WordsLength; i++) { var x64Word = x64Words[i]; x32Words.push(x64Word.high); x32Words.push(x64Word.low); } return X32WordArray.create(x32Words, this.sigBytes); }, /** * Creates a copy of this word array. * * @return {X64WordArray} The clone. * * @example * * var clone = x64WordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); // Clone "words" array var words = clone.words = this.words.slice(0); // Clone each X64Word object var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { words[i] = words[i].clone(); } return clone; } }); }()); return CryptoJS; })); },{"./core":48}],80:[function(_dereq_,module,exports){ // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). (function() { 'use strict'; // Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; // If IndexedDB isn't available, we get outta here! if (!indexedDB) { return; } var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; var supportsBlobs; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (e) { if (e.name !== 'TypeError') { throw e; } var BlobBuilder = window.BlobBuilder || window.MSBlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Transform a binary string to an array buffer, because otherwise // weird stuff happens when you try to work with the binary string directly. // It is known. // From http://stackoverflow.com/questions/14967647/ (continues on next line) // encode-decode-image-with-base64-breaks-image (2013-04-21) function _binStringToArrayBuffer(bin) { var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } return buf; } // Fetch a blob using ajax. This reveals bugs in Chrome < 43. // For details on all this junk: // https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme function _blobAjax(url) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.withCredentials = true; xhr.responseType = 'arraybuffer'; xhr.onreadystatechange = function() { if (xhr.readyState !== 4) { return; } if (xhr.status === 200) { return resolve({ response: xhr.response, type: xhr.getResponseHeader('Content-Type') }); } reject({status: xhr.status, response: xhr.response}); }; xhr.send(); }); } // // Detect blob support. Chrome didn't support it until version 38. // In version 37 they had a broken version where PNGs (and possibly // other binary types) aren't stored correctly, because when you fetch // them, the content type is always null. // // Furthermore, they have some outstanding bugs where blobs occasionally // are read by FileReader as null, or by ajax as 404s. // // Sadly we use the 404 bug to detect the FileReader bug, so if they // get fixed independently and released in different versions of Chrome, // then the bug could come back. So it's worthwhile to watch these issues: // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 // function _checkBlobSupportWithoutCaching(idb) { return new Promise(function(resolve, reject) { var blob = _createBlob([''], {type: 'image/png'}); var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); txn.oncomplete = function() { // have to do it in a separate transaction, else the correct // content type is always returned var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); var getBlobReq = blobTxn.objectStore( DETECT_BLOB_SUPPORT_STORE).get('key'); getBlobReq.onerror = reject; getBlobReq.onsuccess = function(e) { var storedBlob = e.target.result; var url = URL.createObjectURL(storedBlob); _blobAjax(url).then(function(res) { resolve(!!(res && res.type === 'image/png')); }, function() { resolve(false); }).then(function() { URL.revokeObjectURL(url); }); }; }; })['catch'](function() { return false; // error, so assume unsupported }); } function _checkBlobSupport(idb) { if (typeof supportsBlobs === 'boolean') { return Promise.resolve(supportsBlobs); } return _checkBlobSupportWithoutCaching(idb).then(function(value) { supportsBlobs = value; return supportsBlobs; }); } // encode a blob for indexeddb engines that don't support blobs function _encodeBlob(blob) { return new Promise(function(resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function(e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); } // decode an encoded blob function _decodeBlob(encodedBlob) { var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); return _createBlob([arrayBuff], { type: encodedBlob.type}); } // is this one of our fancy encoded blobs? function _isEncodedBlob(value) { return value && value.__local_forage_encoded_blob; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } return new Promise(function(resolve, reject) { var openreq = indexedDB.open(dbInfo.name, dbInfo.version); openreq.onerror = function() { reject(openreq.error); }; openreq.onupgradeneeded = function(e) { // First time setup: create an empty object store openreq.result.createObjectStore(dbInfo.storeName); if (e.oldVersion <= 1) { // added when support for blob shims was added openreq.result.createObjectStore(DETECT_BLOB_SUPPORT_STORE); } }; openreq.onsuccess = function() { dbInfo.db = openreq.result; self._dbInfo = dbInfo; resolve(); }; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.get(key); req.onsuccess = function() { var value = req.result; if (value === undefined) { value = null; } if (_isEncodedBlob(value)) { value = _decodeBlob(value); } resolve(value); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Iterate over all items stored in database. function iterate(iterator, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function() { var cursor = req.result; if (cursor) { var value = cursor.value; if (_isEncodedBlob(value)) { value = _decodeBlob(value); } var result = iterator(value, cursor.key, iterationNumber++); if (result !== void(0)) { resolve(result); } else { cursor['continue'](); } } else { resolve(); } }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { var dbInfo; self.ready().then(function() { dbInfo = self._dbInfo; return _checkBlobSupport(dbInfo.db); }).then(function(blobSupport) { if (!blobSupport && value instanceof Blob) { return _encodeBlob(value); } return value; }).then(function(value) { var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } var req = store.put(value, key); transaction.oncomplete = function() { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function() { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // We use a Grunt task to make this safe for IE and some // versions of Android (including those used by Cordova). // Normally IE won't like `['delete']()` and will insist on // using `['delete']()`, but we have a build step that // fixes this for us now. var req = store['delete'](key); transaction.oncomplete = function() { resolve(); }; transaction.onerror = function() { reject(req.error); }; // The request will be also be aborted if we've exceeded our storage // space. transaction.onabort = function() { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function clear(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); var req = store.clear(); transaction.oncomplete = function() { resolve(); }; transaction.onabort = transaction.onerror = function() { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function length(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.count(); req.onsuccess = function() { resolve(req.result); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function key(n, callback) { var self = this; var promise = new Promise(function(resolve, reject) { if (n < 0) { resolve(null); return; } self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var advanced = false; var req = store.openCursor(); req.onsuccess = function() { var cursor = req.result; if (!cursor) { // this means there weren't enough keys resolve(null); return; } if (n === 0) { // We have the first key, return it if that's what they // wanted. resolve(cursor.key); } else { if (!advanced) { // Otherwise, ask the cursor to skip ahead n // records. advanced = true; cursor.advance(n); } else { // When we get here, we've got the nth key. resolve(cursor.key); } } }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.openCursor(); var keys = []; req.onsuccess = function() { var cursor = req.result; if (!cursor) { resolve(keys); return; } keys.push(cursor.key); cursor['continue'](); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { module.exports = asyncStorage; } else if (typeof define === 'function' && define.amd) { define('asyncStorage', function() { return asyncStorage; }); } else { this.asyncStorage = asyncStorage; } }).call(window); },{"promise":103}],81:[function(_dereq_,module,exports){ // If IndexedDB isn't available, we'll fall back to localStorage. // Note that this will have considerable performance and storage // side-effects (all data will be serialized on save and only data that // can be converted to a string via `JSON.stringify()` will be saved). (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; var localStorage = null; // If the app is running inside a Google Chrome packaged webapp, or some // other context where localStorage isn't available, we don't use // localStorage. This feature detection is preferred over the old // `if (window.chrome && window.chrome.runtime)` code. // See: https://github.com/mozilla/localForage/issues/68 try { // If localStorage isn't available, we get outta here! // This should be inside a try catch if (!this.localStorage || !('setItem' in this.localStorage)) { return; } // Initialize localStorage and create a variable to use throughout // the code. localStorage = this.localStorage; } catch (e) { return; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Config the localStorage backend, using options set in the config. function _initStorage(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = dbInfo.name + '/'; self._dbInfo = dbInfo; var serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); return serializerPromise.then(function(lib) { serializer = lib; return Promise.resolve(); }); } // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear(callback) { var self = this; var promise = self.ready().then(function() { var keyPrefix = self._dbInfo.keyPrefix; for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); executeCallback(promise, callback); return promise; } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = serializer.deserialize(result); } return result; }); executeCallback(promise, callback); return promise; } // Iterate over all items in the store. function iterate(iterator, callback) { var self = this; var promise = self.ready().then(function() { var keyPrefix = self._dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; // We use a dedicated iterator instead of the `i` variable below // so other keys we fetch in localStorage aren't counted in // the `iterationNumber` argument passed to the `iterate()` // callback. // // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 var iterationNumber = 1; for (var i = 0; i < length; i++) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) !== 0) { continue; } var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); if (value !== void(0)) { return value; } } }); executeCallback(promise, callback); return promise; } // Same as localStorage's key() method, except takes a callback. function key(n, callback) { var self = this; var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var length = localStorage.length; var keys = []; for (var i = 0; i < length; i++) { if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); } } return keys; }); executeCallback(promise, callback); return promise; } // Supply the number of keys in the datastore to the callback function. function length(callback) { var self = this; var promise = self.keys().then(function(keys) { return keys.length; }); executeCallback(promise, callback); return promise; } // Remove an item from the store, nice and simple. function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; return new Promise(function(resolve, reject) { serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { try { var dbInfo = self._dbInfo; localStorage.setItem(dbInfo.keyPrefix + key, value); resolve(originalValue); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { reject(e); } reject(e); } } }); }); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage, // Default API, from Gaia/localStorage. iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (moduleType === ModuleType.EXPORT) { module.exports = localStorageWrapper; } else if (moduleType === ModuleType.DEFINE) { define('localStorageWrapper', function() { return localStorageWrapper; }); } else { this.localStorageWrapper = localStorageWrapper; } }).call(window); },{"./../utils/serializer":84,"promise":103}],82:[function(_dereq_,module,exports){ /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; var openDatabase = this.openDatabase; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof(options[i]) !== 'string' ? options[i].toString() : options[i]; } } var serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); var dbInfoPromise = new Promise(function(resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return self.setDriver(self.LOCALSTORAGE).then(function() { return self._initStorage(options); }).then(resolve)['catch'](reject); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function(t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function() { self._dbInfo = dbInfo; resolve(); }, function(t, error) { reject(error); }); }); }); return serializerPromise.then(function(lib) { serializer = lib; return dbInfoPromise; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function(t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = serializer.deserialize(result); } resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function iterate(iterator, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function(t, results) { var rows = results.rows; var length = rows.length; for (var i = 0; i < length; i++) { var item = rows.item(i); var result = item.value; // Check to see if this is serialized content // we need to unpack. if (result) { result = serializer.deserialize(result); } result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition // of `undefined`. if (result !== void(0)) { resolve(result); return; } } resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function() { resolve(originalValue); }, function(t, error) { reject(error); }); }, function(sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // TODO: Try to re-run the transaction. reject(sqlError); } }); } }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function() { resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function() { resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { // Ahhh, SQL makes this one soooooo easy. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function(t, results) { var result = results.rows.item(0).c; resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key(n, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function(t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function(t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { keys.push(results.rows.item(i).key); } resolve(keys); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (moduleType === ModuleType.DEFINE) { define('webSQLStorage', function() { return webSQLStorage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = webSQLStorage; } else { this.webSQLStorage = webSQLStorage; } }).call(window); },{"./../utils/serializer":84,"promise":103}],83:[function(_dereq_,module,exports){ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; // Custom drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. var CustomDrivers = {}; var DriverType = { INDEXEDDB: 'asyncStorage', LOCALSTORAGE: 'localStorageWrapper', WEBSQL: 'webSQLStorage' }; var DefaultDriverOrder = [ DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE ]; var LibraryMethods = [ 'clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem' ]; var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; var DefaultConfig = { description: '', driver: DefaultDriverOrder.slice(), name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 var driverSupport = (function(self) { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB; var result = {}; result[DriverType.WEBSQL] = !!self.openDatabase; result[DriverType.INDEXEDDB] = !!(function() { // We mimic PouchDB here; just UA test for Safari (which, as of // iOS 8/Yosemite, doesn't properly support IndexedDB). // IndexedDB support is broken and different from Blink's. // This is faster than the test case (and it's sync), so we just // do this. *SIGH* // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) { return false; } try { return indexedDB && typeof indexedDB.open === 'function' && // Some Samsung/HTC Android 4.0-4.3 devices // have older IndexedDB specs; if this isn't available // their IndexedDB is too old for us to use. // (Replaces the onupgradeneeded test.) typeof self.IDBKeyRange !== 'undefined'; } catch (e) { return false; } })(); result[DriverType.LOCALSTORAGE] = !!(function() { try { return (self.localStorage && ('setItem' in self.localStorage) && (self.localStorage.setItem)); } catch (e) { return false; } })(); return result; })(this); var isArray = Array.isArray || function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function() { var _args = arguments; return localForageInstance.ready().then(function() { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var key in arg) { if (arg.hasOwnProperty(key)) { if (isArray(arg[key])) { arguments[0][key] = arg[key].slice(); } else { arguments[0][key] = arg[key]; } } } } } return arguments[0]; } function isLibraryDriver(driverName) { for (var driver in DriverType) { if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { return true; } } return false; } var globalObject = this; function LocalForage(options) { this._config = extend({}, DefaultConfig, options); this._driverSet = null; this._ready = false; this._dbInfo = null; // Add a stub for each driver API method that delays the call to the // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. for (var i = 0; i < LibraryMethods.length; i++) { callWhenReady(this, LibraryMethods[i]); } this.setDriver(this._config.driver); } LocalForage.prototype.INDEXEDDB = DriverType.INDEXEDDB; LocalForage.prototype.LOCALSTORAGE = DriverType.LOCALSTORAGE; LocalForage.prototype.WEBSQL = DriverType.WEBSQL; // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. LocalForage.prototype.config = function(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if (typeof(options) === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + 'has been used.'); } for (var i in options) { if (i === 'storeName') { options[i] = options[i].replace(/\W/g, '_'); } this._config[i] = options[i]; } // after all config options are set and // the driver option is used, try setting it if ('driver' in options && options.driver) { this.setDriver(this._config.driver); } return true; } else if (typeof(options) === 'string') { return this._config[options]; } else { return this._config; } }; // Used to define a custom driver, shared across all instances of // localForage. LocalForage.prototype.defineDriver = function(driverObject, callback, errorCallback) { var defineDriver = new Promise(function(resolve, reject) { try { var driverName = driverObject._driver; var complianceError = new Error( 'Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver' ); var namingError = new Error( 'Custom driver name already in use: ' + driverObject._driver ); // A driver name should be defined and not overlap with the // library-defined, default drivers. if (!driverObject._driver) { reject(complianceError); return; } if (isLibraryDriver(driverObject._driver)) { reject(namingError); return; } var customDriverMethods = LibraryMethods.concat('_initStorage'); for (var i = 0; i < customDriverMethods.length; i++) { var customDriverMethod = customDriverMethods[i]; if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { reject(complianceError); return; } } var supportPromise = Promise.resolve(true); if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { supportPromise = driverObject._support(); } else { supportPromise = Promise.resolve(!!driverObject._support); } } supportPromise.then(function(supportResult) { driverSupport[driverName] = supportResult; CustomDrivers[driverName] = driverObject; resolve(); }, reject); } catch (e) { reject(e); } }); defineDriver.then(callback, errorCallback); return defineDriver; }; LocalForage.prototype.driver = function() { return this._driver || null; }; LocalForage.prototype.ready = function(callback) { var self = this; var ready = new Promise(function(resolve, reject) { self._driverSet.then(function() { if (self._ready === null) { self._ready = self._initStorage(self._config); } self._ready.then(resolve, reject); })['catch'](reject); }); ready.then(callback, callback); return ready; }; LocalForage.prototype.setDriver = function(drivers, callback, errorCallback) { var self = this; if (typeof drivers === 'string') { drivers = [drivers]; } this._driverSet = new Promise(function(resolve, reject) { var driverName = self._getFirstSupportedDriver(drivers); var error = new Error('No available storage method found.'); if (!driverName) { self._driverSet = Promise.reject(error); reject(error); return; } self._dbInfo = null; self._ready = null; if (isLibraryDriver(driverName)) { var driverPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_([driverName], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly switch (driverName) { case self.INDEXEDDB: resolve(_dereq_('./drivers/indexeddb')); break; case self.LOCALSTORAGE: resolve(_dereq_('./drivers/localstorage')); break; case self.WEBSQL: resolve(_dereq_('./drivers/websql')); break; } } else { resolve(globalObject[driverName]); } }); driverPromise.then(function(driver) { self._extend(driver); resolve(); }); } else if (CustomDrivers[driverName]) { self._extend(CustomDrivers[driverName]); resolve(); } else { self._driverSet = Promise.reject(error); reject(error); } }); function setDriverToConfig() { self._config.driver = self.driver(); } this._driverSet.then(setDriverToConfig, setDriverToConfig); this._driverSet.then(callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; // Used to determine which driver we should use as the backend for this // instance of localForage. LocalForage.prototype._getFirstSupportedDriver = function(drivers) { if (drivers && isArray(drivers)) { for (var i = 0; i < drivers.length; i++) { var driver = drivers[i]; if (this.supports(driver)) { return driver; } } } return null; }; LocalForage.prototype.createInstance = function(options) { return new LocalForage(options); }; // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. var localForage = new LocalForage(); // We allow localForage to be declared as a module or as a library // available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { define('localforage', function() { return localForage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = localForage; } else { this.localforage = localForage; } }).call(window); },{"./drivers/indexeddb":80,"./drivers/localstorage":81,"./drivers/websql":82,"promise":103}],84:[function(_dereq_,module,exports){ (function() { 'use strict'; // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var BLOB_TYPE_PREFIX = '~~local_forage_type~'; var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; // Get out of our habit of using `window` inline, at least. var globalObject = this; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (err) { if (err.name !== 'TypeError') { throw err; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueString === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function() { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return _createBlob([buffer], {type: blobType}); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i+=4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i+1]); encoded3 = BASE_CHARS.indexOf(serializedString[i+2]); encoded4 = BASE_CHARS.indexOf(serializedString[i+3]); /*jslint bitwise: true */ bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; base64String += BASE_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if ((bytes.length % 3) === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { module.exports = localforageSerializer; } else if (typeof define === 'function' && define.amd) { define('localforageSerializer', function() { return localforageSerializer; }); } else { this.localforageSerializer = localforageSerializer; } }).call(window); },{}],85:[function(_dereq_,module,exports){ // Top level file is just a mixin of submodules & constants 'use strict'; var assign = _dereq_('./lib/utils/common').assign; var deflate = _dereq_('./lib/deflate'); var inflate = _dereq_('./lib/inflate'); var constants = _dereq_('./lib/zlib/constants'); var pako = {}; assign(pako, deflate, inflate, constants); module.exports = pako; },{"./lib/deflate":86,"./lib/inflate":87,"./lib/utils/common":88,"./lib/zlib/constants":91}],86:[function(_dereq_,module,exports){ 'use strict'; var zlib_deflate = _dereq_('./zlib/deflate'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var msg = _dereq_('./zlib/messages'); var ZStream = _dereq_('./zlib/zstream'); var toString = Object.prototype.toString; /* Public constants ==========================================================*/ /* ===========================================================================*/ var Z_NO_FLUSH = 0; var Z_FINISH = 4; var Z_OK = 0; var Z_STREAM_END = 1; var Z_SYNC_FLUSH = 2; var Z_DEFAULT_COMPRESSION = -1; var Z_DEFAULT_STRATEGY = 0; var Z_DEFLATED = 8; /* ===========================================================================*/ /** * class Deflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[deflate]], * [[deflateRaw]] and [[gzip]]. **/ /* internal * Deflate.chunks -> Array * * Chunks of output data, if [[Deflate#onData]] not overriden. **/ /** * Deflate.result -> Uint8Array|Array * * Compressed result, generated by default [[Deflate#onData]] * and [[Deflate#onEnd]] handlers. Filled after you push last chunk * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Deflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Deflate.err -> Number * * Error code after deflate finished. 0 (Z_OK) on success. * You will not need it in real life, because deflate errors * are possible only on wrong options or bad `onData` / `onEnd` * custom handlers. **/ /** * Deflate.msg -> String * * Error message, if [[Deflate.err]] != 0 **/ /** * new Deflate(options) * - options (Object): zlib deflate options. * * Creates new deflator instance with specified params. Throws exception * on bad params. Supported options: * * - `level` * - `windowBits` * - `memLevel` * - `strategy` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw deflate * - `gzip` (Boolean) - create gzip wrapper * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * - `header` (Object) - custom header for gzip * - `text` (Boolean) - true if compressed data believed to be text * - `time` (Number) - modification time, unix timestamp * - `os` (Number) - operation system code * - `extra` (Array) - array of bytes with extra data (max 65536) * - `name` (String) - file name (binary string) * - `comment` (String) - comment (binary string) * - `hcrc` (Boolean) - true if header crc should be added * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var deflate = new pako.Deflate({ level: 3}); * * deflate.push(chunk1, false); * deflate.push(chunk2, true); // true -> last chunk * * if (deflate.err) { throw new Error(deflate.err); } * * console.log(deflate.result); * ``` **/ function Deflate(options) { if (!(this instanceof Deflate)) return new Deflate(options); this.options = utils.assign({ level: Z_DEFAULT_COMPRESSION, method: Z_DEFLATED, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: Z_DEFAULT_STRATEGY, to: '' }, options || {}); var opt = this.options; if (opt.raw && (opt.windowBits > 0)) { opt.windowBits = -opt.windowBits; } else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { opt.windowBits += 16; } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new ZStream(); this.strm.avail_out = 0; var status = zlib_deflate.deflateInit2( this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy ); if (status !== Z_OK) { throw new Error(msg[status]); } if (opt.header) { zlib_deflate.deflateSetHeader(this.strm, opt.header); } } /** * Deflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be * converted to utf8 byte sequence. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with * new compressed chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the compression context. * * On fail call [[Deflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * array format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Deflate.prototype.push = function (data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // If we need to compress text, change encoding to utf8. strm.input = strings.string2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ if (status !== Z_STREAM_END && status !== Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { if (this.options.to === 'string') { this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); // Finalize on the last chunk. if (_mode === Z_FINISH) { status = zlib_deflate.deflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === Z_SYNC_FLUSH) { this.onEnd(Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Deflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Deflate.prototype.onData = function (chunk) { this.chunks.push(chunk); }; /** * Deflate#onEnd(status) -> Void * - status (Number): deflate status. 0 (Z_OK) on success, * other if not. * * Called once after you tell deflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Deflate.prototype.onEnd = function (status) { // On success - join if (status === Z_OK) { if (this.options.to === 'string') { this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * deflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * Compress `data` with deflate algorithm and `options`. * * Supported options are: * * - level * - windowBits * - memLevel * - strategy * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * * ##### Example: * * ```javascript * var pako = require('pako') * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); * * console.log(pako.deflate(data)); * ``` **/ function deflate(input, options) { var deflator = new Deflate(options); deflator.push(input, true); // That will never happens, if you don't cheat with options :) if (deflator.err) { throw deflator.msg; } return deflator.result; } /** * deflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function deflateRaw(input, options) { options = options || {}; options.raw = true; return deflate(input, options); } /** * gzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but create gzip wrapper instead of * deflate one. **/ function gzip(input, options) { options = options || {}; options.gzip = true; return deflate(input, options); } exports.Deflate = Deflate; exports.deflate = deflate; exports.deflateRaw = deflateRaw; exports.gzip = gzip; },{"./utils/common":88,"./utils/strings":89,"./zlib/deflate":93,"./zlib/messages":98,"./zlib/zstream":100}],87:[function(_dereq_,module,exports){ 'use strict'; var zlib_inflate = _dereq_('./zlib/inflate'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var c = _dereq_('./zlib/constants'); var msg = _dereq_('./zlib/messages'); var ZStream = _dereq_('./zlib/zstream'); var GZheader = _dereq_('./zlib/gzheader'); var toString = Object.prototype.toString; /** * class Inflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[inflate]] * and [[inflateRaw]]. **/ /* internal * inflate.chunks -> Array * * Chunks of output data, if [[Inflate#onData]] not overriden. **/ /** * Inflate.result -> Uint8Array|Array|String * * Uncompressed result, generated by default [[Inflate#onData]] * and [[Inflate#onEnd]] handlers. Filled after you push last chunk * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Inflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Inflate.err -> Number * * Error code after inflate finished. 0 (Z_OK) on success. * Should be checked if broken data possible. **/ /** * Inflate.msg -> String * * Error message, if [[Inflate.err]] != 0 **/ /** * new Inflate(options) * - options (Object): zlib inflate options. * * Creates new inflator instance with specified params. Throws exception * on bad params. Supported options: * * - `windowBits` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw inflate * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * By default, when no options set, autodetect deflate/gzip data format via * wrapper header. * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var inflate = new pako.Inflate({ level: 3}); * * inflate.push(chunk1, false); * inflate.push(chunk2, true); // true -> last chunk * * if (inflate.err) { throw new Error(inflate.err); } * * console.log(inflate.result); * ``` **/ function Inflate(options) { if (!(this instanceof Inflate)) return new Inflate(options); this.options = utils.assign({ chunkSize: 16384, windowBits: 0, to: '' }, options || {}); var opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { opt.windowBits = -opt.windowBits; if (opt.windowBits === 0) { opt.windowBits = -15; } } // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate if ((opt.windowBits >= 0) && (opt.windowBits < 16) && !(options && options.windowBits)) { opt.windowBits += 32; } // Gzip header has no info about windows size, we can do autodetect only // for deflate. So, if window size not set, force it to max when gzip possible if ((opt.windowBits > 15) && (opt.windowBits < 48)) { // bit 3 (16) -> gzipped data // bit 4 (32) -> autodetect gzip/deflate if ((opt.windowBits & 15) === 0) { opt.windowBits |= 15; } } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new ZStream(); this.strm.avail_out = 0; var status = zlib_inflate.inflateInit2( this.strm, opt.windowBits ); if (status !== c.Z_OK) { throw new Error(msg[status]); } this.header = new GZheader(); zlib_inflate.inflateGetHeader(this.strm, this.header); } /** * Inflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with * new output chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the decompression context. * * On fail call [[Inflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Inflate.prototype.push = function (data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; var next_out_utf8, tail, utf8str; // Flag to properly process Z_BUF_ERROR on testing inflate call // when we check that all output data was flushed. var allowBufError = false; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // Only binary strings can be decompressed on practice strm.input = strings.binstring2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ if (status === c.Z_BUF_ERROR && allowBufError === true) { status = c.Z_OK; allowBufError = false; } if (status !== c.Z_STREAM_END && status !== c.Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.next_out) { if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { if (this.options.to === 'string') { next_out_utf8 = strings.utf8border(strm.output, strm.next_out); tail = strm.next_out - next_out_utf8; utf8str = strings.buf2string(strm.output, next_out_utf8); // move tail strm.next_out = tail; strm.avail_out = chunkSize - tail; if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } this.onData(utf8str); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } // When no more input data, we should check that internal inflate buffers // are flushed. The only way to do it when avail_out = 0 - run one more // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. // Here we set flag to process this error properly. // // NOTE. Deflate does not return error in this case and does not needs such // logic. if (strm.avail_in === 0 && strm.avail_out === 0) { allowBufError = true; } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); if (status === c.Z_STREAM_END) { _mode = c.Z_FINISH; } // Finalize on the last chunk. if (_mode === c.Z_FINISH) { status = zlib_inflate.inflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === c.Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === c.Z_SYNC_FLUSH) { this.onEnd(c.Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Inflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Inflate.prototype.onData = function (chunk) { this.chunks.push(chunk); }; /** * Inflate#onEnd(status) -> Void * - status (Number): inflate status. 0 (Z_OK) on success, * other if not. * * Called either after you tell inflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Inflate.prototype.onEnd = function (status) { // On success - join if (status === c.Z_OK) { if (this.options.to === 'string') { // Glue & convert here, until we teach pako to send // utf8 alligned strings to onData this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * inflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Decompress `data` with inflate/ungzip and `options`. Autodetect * format via wrapper header by default. That's why we don't provide * separate `ungzip` method. * * Supported options are: * * - windowBits * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * * ##### Example: * * ```javascript * var pako = require('pako') * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) * , output; * * try { * output = pako.inflate(input); * } catch (err) * console.log(err); * } * ``` **/ function inflate(input, options) { var inflator = new Inflate(options); inflator.push(input, true); // That will never happens, if you don't cheat with options :) if (inflator.err) { throw inflator.msg; } return inflator.result; } /** * inflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * The same as [[inflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function inflateRaw(input, options) { options = options || {}; options.raw = true; return inflate(input, options); } /** * ungzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Just shortcut to [[inflate]], because it autodetects format * by header.content. Done for convenience. **/ exports.Inflate = Inflate; exports.inflate = inflate; exports.inflateRaw = inflateRaw; exports.ungzip = inflate; },{"./utils/common":88,"./utils/strings":89,"./zlib/constants":91,"./zlib/gzheader":94,"./zlib/inflate":96,"./zlib/messages":98,"./zlib/zstream":100}],88:[function(_dereq_,module,exports){ 'use strict'; var TYPED_OK = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Int32Array !== 'undefined'); exports.assign = function (obj /*from1, from2, from3, ...*/) { var sources = Array.prototype.slice.call(arguments, 1); while (sources.length) { var source = sources.shift(); if (!source) { continue; } if (typeof source !== 'object') { throw new TypeError(source + 'must be non-object'); } for (var p in source) { if (source.hasOwnProperty(p)) { obj[p] = source[p]; } } } return obj; }; // reduce buffer size, avoiding mem copy exports.shrinkBuf = function (buf, size) { if (buf.length === size) { return buf; } if (buf.subarray) { return buf.subarray(0, size); } buf.length = size; return buf; }; var fnTyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { if (src.subarray && dest.subarray) { dest.set(src.subarray(src_offs, src_offs + len), dest_offs); return; } // Fallback to ordinary array for (var i = 0; i < len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function (chunks) { var i, l, len, pos, chunk, result; // calculate data length len = 0; for (i = 0, l = chunks.length; i < l; i++) { len += chunks[i].length; } // join chunks result = new Uint8Array(len); pos = 0; for (i = 0, l = chunks.length; i < l; i++) { chunk = chunks[i]; result.set(chunk, pos); pos += chunk.length; } return result; } }; var fnUntyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { for (var i = 0; i < len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function (chunks) { return [].concat.apply([], chunks); } }; // Enable/Disable typed arrays use, for testing // exports.setTyped = function (on) { if (on) { exports.Buf8 = Uint8Array; exports.Buf16 = Uint16Array; exports.Buf32 = Int32Array; exports.assign(exports, fnTyped); } else { exports.Buf8 = Array; exports.Buf16 = Array; exports.Buf32 = Array; exports.assign(exports, fnUntyped); } }; exports.setTyped(TYPED_OK); },{}],89:[function(_dereq_,module,exports){ // String encode/decode helpers 'use strict'; var utils = _dereq_('./common'); // Quick check if we can use fast array to bin string conversion // // - apply(Array) can fail on Android 2.2 // - apply(Uint8Array) can fail on iOS 5.1 Safary // var STR_APPLY_OK = true; var STR_APPLY_UIA_OK = true; try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; } try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } // Table with utf8 lengths (calculated by first byte of sequence) // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // because max possible codepoint is 0x10ffff var _utf8len = new utils.Buf8(256); for (var q = 0; q < 256; q++) { _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); } _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start // convert string to array (typed, when possible) exports.string2buf = function (str) { var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; // count binary size for (m_pos = 0; m_pos < str_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { c2 = str.charCodeAt(m_pos + 1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } // allocate buffer buf = new utils.Buf8(buf_len); // convert for (i = 0, m_pos = 0; i < buf_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { c2 = str.charCodeAt(m_pos + 1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } if (c < 0x80) { /* one byte */ buf[i++] = c; } else if (c < 0x800) { /* two bytes */ buf[i++] = 0xC0 | (c >>> 6); buf[i++] = 0x80 | (c & 0x3f); } else if (c < 0x10000) { /* three bytes */ buf[i++] = 0xE0 | (c >>> 12); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } else { /* four bytes */ buf[i++] = 0xf0 | (c >>> 18); buf[i++] = 0x80 | (c >>> 12 & 0x3f); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } } return buf; }; // Helper (used in 2 places) function buf2binstring(buf, len) { // use fallback for big arrays to avoid stack overflow if (len < 65537) { if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); } } var result = ''; for (var i = 0; i < len; i++) { result += String.fromCharCode(buf[i]); } return result; } // Convert byte array to binary string exports.buf2binstring = function (buf) { return buf2binstring(buf, buf.length); }; // Convert binary string (typed, when possible) exports.binstring2buf = function (str) { var buf = new utils.Buf8(str.length); for (var i = 0, len = buf.length; i < len; i++) { buf[i] = str.charCodeAt(i); } return buf; }; // convert array to string exports.buf2string = function (buf, max) { var i, out, c, c_len; var len = max || buf.length; // Reserve max possible length (2 words per char) // NB: by unknown reasons, Array is significantly faster for // String.fromCharCode.apply than Uint16Array. var utf16buf = new Array(len * 2); for (out = 0, i = 0; i < len;) { c = buf[i++]; // quick process ascii if (c < 0x80) { utf16buf[out++] = c; continue; } c_len = _utf8len[c]; // skip 5 & 6 byte codes if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } // apply mask on first byte c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest while (c_len > 1 && i < len) { c = (c << 6) | (buf[i++] & 0x3f); c_len--; } // terminated by end of string? if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } if (c < 0x10000) { utf16buf[out++] = c; } else { c -= 0x10000; utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); utf16buf[out++] = 0xdc00 | (c & 0x3ff); } } return buf2binstring(utf16buf, out); }; // Calculate max possible position in utf8 buffer, // that will not break sequence. If that's not possible // - (very small limits) return max size as is. // // buf[] - utf8 bytes array // max - length limit (mandatory); exports.utf8border = function (buf, max) { var pos; max = max || buf.length; if (max > buf.length) { max = buf.length; } // go back from last position, until start of sequence found pos = max - 1; while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } // Fuckup - very small and broken sequence, // return max, because we should return something anyway. if (pos < 0) { return max; } // If we came to start of buffer - that means vuffer is too small, // return max too. if (pos === 0) { return max; } return (pos + _utf8len[buf[pos]] > max) ? pos : max; }; },{"./common":88}],90:[function(_dereq_,module,exports){ 'use strict'; // Note: adler32 takes 12% for level 0 and 2% for level 6. // It doesn't worth to make additional optimizationa as in original. // Small size is preferable. function adler32(adler, buf, len, pos) { var s1 = (adler & 0xffff) |0, s2 = ((adler >>> 16) & 0xffff) |0, n = 0; while (len !== 0) { // Set limit ~ twice less than 5552, to keep // s2 in 31-bits, because we force signed ints. // in other case %= will fail. n = len > 2000 ? 2000 : len; len -= n; do { s1 = (s1 + buf[pos++]) |0; s2 = (s2 + s1) |0; } while (--n); s1 %= 65521; s2 %= 65521; } return (s1 | (s2 << 16)) |0; } module.exports = adler32; },{}],91:[function(_dereq_,module,exports){ 'use strict'; module.exports = { /* Allowed flush values; see deflate() and inflate() below for details */ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, //Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, //Z_VERSION_ERROR: -6, /* compression levels */ Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, /* Possible values of the data_type field (though see inflate()) */ Z_BINARY: 0, Z_TEXT: 1, //Z_ASCII: 1, // = Z_TEXT (deprecated) Z_UNKNOWN: 2, /* The deflate compression method */ Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type }; },{}],92:[function(_dereq_,module,exports){ 'use strict'; // Note: we can't get significant speed boost here. // So write code to minimize size - no pregenerated tables // and array tools dependencies. // Use ordinary array, since untyped makes no boost here function makeTable() { var c, table = []; for (var n = 0; n < 256; n++) { c = n; for (var k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); } table[n] = c; } return table; } // Create table on load. Just 255 signed longs. Not a problem. var crcTable = makeTable(); function crc32(crc, buf, len, pos) { var t = crcTable, end = pos + len; crc ^= -1; for (var i = pos; i < end; i++) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = crc32; },{}],93:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var trees = _dereq_('./trees'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var msg = _dereq_('./messages'); /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ var Z_NO_FLUSH = 0; var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; //var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; //var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; //var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* compression levels */ //var Z_NO_COMPRESSION = 0; //var Z_BEST_SPEED = 1; //var Z_BEST_COMPRESSION = 9; var Z_DEFAULT_COMPRESSION = -1; var Z_FILTERED = 1; var Z_HUFFMAN_ONLY = 2; var Z_RLE = 3; var Z_FIXED = 4; var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ //var Z_BINARY = 0; //var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /* The deflate compression method */ var Z_DEFLATED = 8; /*============================================================================*/ var MAX_MEM_LEVEL = 9; /* Maximum value for memLevel in deflateInit2 */ var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_MEM_LEVEL = 8; var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2 * L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var MIN_MATCH = 3; var MAX_MATCH = 258; var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); var PRESET_DICT = 0x20; var INIT_STATE = 42; var EXTRA_STATE = 69; var NAME_STATE = 73; var COMMENT_STATE = 91; var HCRC_STATE = 103; var BUSY_STATE = 113; var FINISH_STATE = 666; var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ var BS_BLOCK_DONE = 2; /* block flush performed */ var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. function err(strm, errorCode) { strm.msg = msg[errorCode]; return errorCode; } function rank(f) { return ((f) << 1) - ((f) > 4 ? 9 : 0); } function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->output buffer and copying into it. * (See also read_buf()). */ function flush_pending(strm) { var s = strm.state; //_tr_flush_bits(s); var len = s.pending; if (len > strm.avail_out) { len = strm.avail_out; } if (len === 0) { return; } utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); strm.next_out += len; s.pending_out += len; strm.total_out += len; strm.avail_out -= len; s.pending -= len; if (s.pending === 0) { s.pending_out = 0; } } function flush_block_only(s, last) { trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); s.block_start = s.strstart; flush_pending(s.strm); } function put_byte(s, b) { s.pending_buf[s.pending++] = b; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ function putShortMSB(s, b) { // put_byte(s, (Byte)(b >> 8)); // put_byte(s, (Byte)(b & 0xff)); s.pending_buf[s.pending++] = (b >>> 8) & 0xff; s.pending_buf[s.pending++] = b & 0xff; } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->input buffer and copying from it. * (See also flush_pending()). */ function read_buf(strm, buf, start, size) { var len = strm.avail_in; if (len > size) { len = size; } if (len === 0) { return 0; } strm.avail_in -= len; utils.arraySet(buf, strm.input, strm.next_in, len, start); if (strm.state.wrap === 1) { strm.adler = adler32(strm.adler, buf, len, start); } else if (strm.state.wrap === 2) { strm.adler = crc32(strm.adler, buf, len, start); } strm.next_in += len; strm.total_in += len; return len; } /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ function longest_match(s, cur_match) { var chain_length = s.max_chain_length; /* max hash chain length */ var scan = s.strstart; /* current string */ var match; /* matched string */ var len; /* length of current match */ var best_len = s.prev_length; /* best match length so far */ var nice_match = s.nice_match; /* stop if match long enough */ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; var _win = s.window; // shortcut var wmask = s.w_mask; var prev = s.prev; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ var strend = s.strstart + MAX_MATCH; var scan_end1 = _win[scan + best_len - 1]; var scan_end = _win[scan + best_len]; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s.prev_length >= s.good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (nice_match > s.lookahead) { nice_match = s.lookahead; } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { // Assert(cur_match < s->strstart, "no future"); match = cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { continue; } /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2; match++; // Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { /*jshint noempty:false*/ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) { s.match_start = cur_match; best_len = len; if (len >= nice_match) { break; } scan_end1 = _win[scan + best_len - 1]; scan_end = _win[scan + best_len]; } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); if (best_len <= s.lookahead) { return best_len; } return s.lookahead; } /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ function fill_window(s) { var _w_size = s.w_size; var p, n, m, more, str; //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); do { more = s.window_size - s.lookahead - s.strstart; // JS ints have 32 bit, block below not needed /* Deal with !@#$% 64K limit: */ //if (sizeof(int) <= 2) { // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { // more = wsize; // // } else if (more == (unsigned)(-1)) { // /* Very unlikely, but possible on 16 bit machine if // * strstart == 0 && lookahead == 1 (input done a byte at time) // */ // more--; // } //} /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { utils.arraySet(s.window, s.window, _w_size, _w_size, 0); s.match_start -= _w_size; s.strstart -= _w_size; /* we now have strstart >= MAX_DIST */ s.block_start -= _w_size; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s.hash_size; p = n; do { m = s.head[--p]; s.head[p] = (m >= _w_size ? m - _w_size : 0); } while (--n); n = _w_size; p = n; do { m = s.prev[--p]; s.prev[p] = (m >= _w_size ? m - _w_size : 0); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); more += _w_size; } if (s.strm.avail_in === 0) { break; } /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ //Assert(more >= 2, "more < 2"); n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); s.lookahead += n; /* Initialize the hash value now that we have some input: */ if (s.lookahead + s.insert >= MIN_MATCH) { str = s.strstart - s.insert; s.ins_h = s.window[str]; /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call update_hash() MIN_MATCH-3 more times //#endif while (s.insert) { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; s.insert--; if (s.lookahead + s.insert < MIN_MATCH) { break; } } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ // if (s.high_water < s.window_size) { // var curr = s.strstart + s.lookahead; // var init = 0; // // if (s.high_water < curr) { // /* Previous high water mark below current data -- zero WIN_INIT // * bytes or up to end of window, whichever is less. // */ // init = s.window_size - curr; // if (init > WIN_INIT) // init = WIN_INIT; // zmemzero(s->window + curr, (unsigned)init); // s->high_water = curr + init; // } // else if (s->high_water < (ulg)curr + WIN_INIT) { // /* High water mark at or above current data, but below current data // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up // * to end of window, whichever is less. // */ // init = (ulg)curr + WIN_INIT - s->high_water; // if (init > s->window_size - s->high_water) // init = s->window_size - s->high_water; // zmemzero(s->window + s->high_water, (unsigned)init); // s->high_water += init; // } // } // // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, // "not enough room for search"); } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ function deflate_stored(s, flush) { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ var max_block_size = 0xffff; if (max_block_size > s.pending_buf_size - 5) { max_block_size = s.pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s.lookahead <= 1) { //Assert(s->strstart < s->w_size+MAX_DIST(s) || // s->block_start >= (long)s->w_size, "slide too late"); // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || // s.block_start >= s.w_size)) { // throw new Error("slide too late"); // } fill_window(s); if (s.lookahead === 0 && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } //Assert(s->block_start >= 0L, "block gone"); // if (s.block_start < 0) throw new Error("block gone"); s.strstart += s.lookahead; s.lookahead = 0; /* Emit a stored block if pending_buf will be full: */ var max_start = s.block_start + max_block_size; if (s.strstart === 0 || s.strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s.lookahead = s.strstart - max_start; s.strstart = max_start; /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.strstart > s.block_start) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_NEED_MORE; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ function deflate_fast(s, flush) { var hash_head; /* head of the hash chain */ var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; /* flush the current block */ } } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ } if (s.match_length >= MIN_MATCH) { // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only /*** _tr_tally_dist(s, s.strstart - s.match_start, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { s.match_length--; /* string at strstart already in table */ do { s.strstart++; /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s.match_length !== 0); s.strstart++; } else { s.strstart += s.match_length; s.match_length = 0; s.ins_h = s.window[s.strstart]; /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call UPDATE_HASH() MIN_MATCH-3 more times //#endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s.window[s.strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ function deflate_slow(s, flush) { var hash_head; /* head of hash chain */ var bflush; /* set if current block must be flushed */ var max_insert; /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. */ s.prev_length = s.match_length; s.prev_match = s.match_start; s.match_length = MIN_MATCH - 1; if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ if (s.match_length <= 5 && (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s.match_length = MIN_MATCH - 1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { max_insert = s.strstart + s.lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ //check_match(s, s.strstart-1, s.prev_match, s.prev_length); /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH, bflush);***/ bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s.lookahead -= s.prev_length - 1; s.prev_length -= 2; do { if (++s.strstart <= max_insert) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } } while (--s.prev_length !== 0); s.match_available = 0; s.match_length = MIN_MATCH - 1; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } else if (s.match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); if (bflush) { /*** FLUSH_BLOCK_ONLY(s, 0) ***/ flush_block_only(s, false); /***/ } s.strstart++; s.lookahead--; if (s.strm.avail_out === 0) { return BS_NEED_MORE; } } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s.match_available = 1; s.strstart++; s.lookahead--; } } //Assert (flush != Z_NO_FLUSH, "no flush?"); if (s.match_available) { //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); s.match_available = 0; } s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ function deflate_rle(s, flush) { var bflush; /* set if current block must be flushed */ var prev; /* byte at distance one to match */ var scan, strend; /* scan goes up to strend for length of run */ var _win = s.window; for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest run, plus one for the unrolled loop. */ if (s.lookahead <= MAX_MATCH) { fill_window(s); if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* See how many times the previous byte repeats */ s.match_length = 0; if (s.lookahead >= MIN_MATCH && s.strstart > 0) { scan = s.strstart - 1; prev = _win[scan]; if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { strend = s.strstart + MAX_MATCH; do { /*jshint noempty:false*/ } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); s.match_length = MAX_MATCH - (strend - scan); if (s.match_length > s.lookahead) { s.match_length = s.lookahead; } } //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s.match_length >= MIN_MATCH) { //check_match(s, s.strstart, s.strstart - 1, s.match_length); /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; s.strstart += s.match_length; s.match_length = 0; } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ function deflate_huff(s, flush) { var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s.lookahead === 0) { fill_window(s); if (s.lookahead === 0) { if (flush === Z_NO_FLUSH) { return BS_NEED_MORE; } break; /* flush the current block */ } } /* Output a literal byte */ s.match_length = 0; //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ function Config(good_length, max_lazy, nice_length, max_chain, func) { this.good_length = good_length; this.max_lazy = max_lazy; this.nice_length = nice_length; this.max_chain = max_chain; this.func = func; } var configuration_table; configuration_table = [ /* good lazy nice chain */ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ new Config(4, 5, 16, 8, deflate_fast), /* 2 */ new Config(4, 6, 32, 32, deflate_fast), /* 3 */ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ new Config(8, 16, 32, 32, deflate_slow), /* 5 */ new Config(8, 16, 128, 128, deflate_slow), /* 6 */ new Config(8, 32, 128, 256, deflate_slow), /* 7 */ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ ]; /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ function lm_init(s) { s.window_size = 2 * s.w_size; /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); /* Set the default configuration parameters: */ s.max_lazy_match = configuration_table[s.level].max_lazy; s.good_match = configuration_table[s.level].good_length; s.nice_match = configuration_table[s.level].nice_length; s.max_chain_length = configuration_table[s.level].max_chain; s.strstart = 0; s.block_start = 0; s.lookahead = 0; s.insert = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; s.ins_h = 0; } function DeflateState() { this.strm = null; /* pointer back to this zlib stream */ this.status = 0; /* as the name implies */ this.pending_buf = null; /* output still pending */ this.pending_buf_size = 0; /* size of pending_buf */ this.pending_out = 0; /* next pending byte to output to the stream */ this.pending = 0; /* nb of bytes in the pending buffer */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.gzhead = null; /* gzip header information to write */ this.gzindex = 0; /* where in extra, name, or comment */ this.method = Z_DEFLATED; /* can only be DEFLATED */ this.last_flush = -1; /* value of flush param for previous deflate call */ this.w_size = 0; /* LZ77 window size (32K by default) */ this.w_bits = 0; /* log2(w_size) (8..16) */ this.w_mask = 0; /* w_size - 1 */ this.window = null; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. */ this.window_size = 0; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ this.prev = null; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ this.head = null; /* Heads of the hash chains or NIL. */ this.ins_h = 0; /* hash index of string to be inserted */ this.hash_size = 0; /* number of elements in hash table */ this.hash_bits = 0; /* log2(hash_size) */ this.hash_mask = 0; /* hash_size-1 */ this.hash_shift = 0; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ this.block_start = 0; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ this.match_length = 0; /* length of best match */ this.prev_match = 0; /* previous match */ this.match_available = 0; /* set if previous match exists */ this.strstart = 0; /* start of string to insert */ this.match_start = 0; /* start of matching string */ this.lookahead = 0; /* number of valid bytes ahead in window */ this.prev_length = 0; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ this.max_chain_length = 0; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ this.max_lazy_match = 0; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ // That's alias to max_lazy_match, don't use directly //this.max_insert_length = 0; /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ this.level = 0; /* compression level (1..9) */ this.strategy = 0; /* favor or force Huffman coding*/ this.good_match = 0; /* Use a faster search when the previous match is longer than this */ this.nice_match = 0; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to suppress compiler warning */ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ // Use flat array of DOUBLE size, with interleaved fata, // because JS does not support effective this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); zero(this.dyn_ltree); zero(this.dyn_dtree); zero(this.bl_tree); this.l_desc = null; /* desc. for literal tree */ this.d_desc = null; /* desc. for distance tree */ this.bl_desc = null; /* desc. for bit length tree */ //ush bl_count[MAX_BITS+1]; this.bl_count = new utils.Buf16(MAX_BITS + 1); /* number of codes at each bit length for an optimal tree */ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ zero(this.heap); this.heap_len = 0; /* number of elements in the heap */ this.heap_max = 0; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; zero(this.depth); /* Depth of each subtree used as tie breaker for trees of equal frequency */ this.l_buf = 0; /* buffer index for literals or lengths */ this.lit_bufsize = 0; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ this.last_lit = 0; /* running index in l_buf */ this.d_buf = 0; /* Buffer index for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ this.opt_len = 0; /* bit length of current block with optimal trees */ this.static_len = 0; /* bit length of current block with static trees */ this.matches = 0; /* number of string matches in current block */ this.insert = 0; /* bytes at end of window left to insert */ this.bi_buf = 0; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ this.bi_valid = 0; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ // Used for window memory init. We safely ignore it for JS. That makes // sense only for pointers and memory check tools. //this.high_water = 0; /* High water mark offset in window for initialized bytes -- bytes above * this are set to zero in order to avoid memory check warnings when * longest match routines access bytes past the input. This is then * updated to the new high water mark. */ } function deflateResetKeep(strm) { var s; if (!strm || !strm.state) { return err(strm, Z_STREAM_ERROR); } strm.total_in = strm.total_out = 0; strm.data_type = Z_UNKNOWN; s = strm.state; s.pending = 0; s.pending_out = 0; if (s.wrap < 0) { s.wrap = -s.wrap; /* was made negative by deflate(..., Z_FINISH); */ } s.status = (s.wrap ? INIT_STATE : BUSY_STATE); strm.adler = (s.wrap === 2) ? 0 // crc32(0, Z_NULL, 0) : 1; // adler32(0, Z_NULL, 0) s.last_flush = Z_NO_FLUSH; trees._tr_init(s); return Z_OK; } function deflateReset(strm) { var ret = deflateResetKeep(strm); if (ret === Z_OK) { lm_init(strm.state); } return ret; } function deflateSetHeader(strm, head) { if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } strm.state.gzhead = head; return Z_OK; } function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { if (!strm) { // === Z_NULL return Z_STREAM_ERROR; } var wrap = 1; if (level === Z_DEFAULT_COMPRESSION) { level = 6; } if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return err(strm, Z_STREAM_ERROR); } if (windowBits === 8) { windowBits = 9; } /* until 256-byte window bug fixed */ var s = new DeflateState(); strm.state = s; s.strm = strm; s.wrap = wrap; s.gzhead = null; s.w_bits = windowBits; s.w_size = 1 << s.w_bits; s.w_mask = s.w_size - 1; s.hash_bits = memLevel + 7; s.hash_size = 1 << s.hash_bits; s.hash_mask = s.hash_size - 1; s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); s.window = new utils.Buf8(s.w_size * 2); s.head = new utils.Buf16(s.hash_size); s.prev = new utils.Buf16(s.w_size); // Don't need mem init magic for JS. //s.high_water = 0; /* nothing written to s->window yet */ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ s.pending_buf_size = s.lit_bufsize * 4; s.pending_buf = new utils.Buf8(s.pending_buf_size); s.d_buf = s.lit_bufsize >> 1; s.l_buf = (1 + 2) * s.lit_bufsize; s.level = level; s.strategy = strategy; s.method = method; return deflateReset(strm); } function deflateInit(strm, level) { return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); } function deflate(strm, flush) { var old_flush, s; var beg, val; // for gzip header write only if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; } s = strm.state; if (!strm.output || (!strm.input && strm.avail_in !== 0) || (s.status === FINISH_STATE && flush !== Z_FINISH)) { return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); } s.strm = strm; /* just in case */ old_flush = s.last_flush; s.last_flush = flush; /* Write the header */ if (s.status === INIT_STATE) { if (s.wrap === 2) { // GZIP header strm.adler = 0; //crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (!s.gzhead) { // s->gzhead == Z_NULL put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s.status = BUSY_STATE; } else { put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) ); put_byte(s, s.gzhead.time & 0xff); put_byte(s, (s.gzhead.time >> 8) & 0xff); put_byte(s, (s.gzhead.time >> 16) & 0xff); put_byte(s, (s.gzhead.time >> 24) & 0xff); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, s.gzhead.os & 0xff); if (s.gzhead.extra && s.gzhead.extra.length) { put_byte(s, s.gzhead.extra.length & 0xff); put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); } if (s.gzhead.hcrc) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); } s.gzindex = 0; s.status = EXTRA_STATE; } } else // DEFLATE header { var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; var level_flags = -1; if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { level_flags = 0; } else if (s.level < 6) { level_flags = 1; } else if (s.level === 6) { level_flags = 2; } else { level_flags = 3; } header |= (level_flags << 6); if (s.strstart !== 0) { header |= PRESET_DICT; } header += 31 - (header % 31); s.status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s.strstart !== 0) { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } strm.adler = 1; // adler32(0L, Z_NULL, 0); } } //#ifdef GZIP if (s.status === EXTRA_STATE) { if (s.gzhead.extra/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { break; } } put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); s.gzindex++; } if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (s.gzindex === s.gzhead.extra.length) { s.gzindex = 0; s.status = NAME_STATE; } } else { s.status = NAME_STATE; } } if (s.status === NAME_STATE) { if (s.gzhead.name/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.name.length) { val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.gzindex = 0; s.status = COMMENT_STATE; } } else { s.status = COMMENT_STATE; } } if (s.status === COMMENT_STATE) { if (s.gzhead.comment/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.comment.length) { val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.status = HCRC_STATE; } } else { s.status = HCRC_STATE; } } if (s.status === HCRC_STATE) { if (s.gzhead.hcrc) { if (s.pending + 2 > s.pending_buf_size) { flush_pending(strm); } if (s.pending + 2 <= s.pending_buf_size) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); strm.adler = 0; //crc32(0L, Z_NULL, 0); s.status = BUSY_STATE; } } else { s.status = BUSY_STATE; } } //#endif /* Flush as much pending output as possible */ if (s.pending !== 0) { flush_pending(strm); if (strm.avail_out === 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s.last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { return err(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s.status === FINISH_STATE && strm.avail_in !== 0) { return err(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm.avail_in !== 0 || s.lookahead !== 0 || (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : (s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush)); if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { s.status = FINISH_STATE; } if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate === BS_BLOCK_DONE) { if (flush === Z_PARTIAL_FLUSH) { trees._tr_align(s); } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ trees._tr_stored_block(s, 0, 0, false); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush === Z_FULL_FLUSH) { /*** CLEAR_HASH(s); ***/ /* forget history */ zero(s.head); // Fill with NIL (= 0); if (s.lookahead === 0) { s.strstart = 0; s.block_start = 0; s.insert = 0; } } } flush_pending(strm); if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } //Assert(strm->avail_out > 0, "bug2"); //if (strm.avail_out <= 0) { throw new Error("bug2");} if (flush !== Z_FINISH) { return Z_OK; } if (s.wrap <= 0) { return Z_STREAM_END; } /* Write the trailer */ if (s.wrap === 2) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); put_byte(s, (strm.adler >> 16) & 0xff); put_byte(s, (strm.adler >> 24) & 0xff); put_byte(s, strm.total_in & 0xff); put_byte(s, (strm.total_in >> 8) & 0xff); put_byte(s, (strm.total_in >> 16) & 0xff); put_byte(s, (strm.total_in >> 24) & 0xff); } else { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s.wrap > 0) { s.wrap = -s.wrap; } /* write the trailer only once! */ return s.pending !== 0 ? Z_OK : Z_STREAM_END; } function deflateEnd(strm) { var status; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } status = strm.state.status; if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE ) { return err(strm, Z_STREAM_ERROR); } strm.state = null; return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; } /* ========================================================================= * Copy the source state to the destination state */ //function deflateCopy(dest, source) { // //} exports.deflateInit = deflateInit; exports.deflateInit2 = deflateInit2; exports.deflateReset = deflateReset; exports.deflateResetKeep = deflateResetKeep; exports.deflateSetHeader = deflateSetHeader; exports.deflate = deflate; exports.deflateEnd = deflateEnd; exports.deflateInfo = 'pako deflate (from Nodeca project)'; /* Not implemented exports.deflateBound = deflateBound; exports.deflateCopy = deflateCopy; exports.deflateSetDictionary = deflateSetDictionary; exports.deflateParams = deflateParams; exports.deflatePending = deflatePending; exports.deflatePrime = deflatePrime; exports.deflateTune = deflateTune; */ },{"../utils/common":88,"./adler32":90,"./crc32":92,"./messages":98,"./trees":99}],94:[function(_dereq_,module,exports){ 'use strict'; function GZheader() { /* true if compressed data believed to be text */ this.text = 0; /* modification time */ this.time = 0; /* extra flags (not used when writing a gzip file) */ this.xflags = 0; /* operating system */ this.os = 0; /* pointer to extra field or Z_NULL if none */ this.extra = null; /* extra field length (valid if extra != Z_NULL) */ this.extra_len = 0; // Actually, we don't need it in JS, // but leave for few code modifications // // Setup limits is not necessary because in js we should not preallocate memory // for inflate use constant limit in 65536 bytes // /* space at extra (only when reading header) */ // this.extra_max = 0; /* pointer to zero-terminated file name or Z_NULL */ this.name = ''; /* space at name (only when reading header) */ // this.name_max = 0; /* pointer to zero-terminated comment or Z_NULL */ this.comment = ''; /* space at comment (only when reading header) */ // this.comm_max = 0; /* true if there was or will be a header crc */ this.hcrc = 0; /* true when done reading gzip header (not used when writing a gzip file) */ this.done = false; } module.exports = GZheader; },{}],95:[function(_dereq_,module,exports){ 'use strict'; // See state defs from inflate.js var BAD = 30; /* got a data error -- remain here until reset */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state.mode === LEN strm.avail_in >= 6 strm.avail_out >= 258 start >= strm.avail_out state.bits < 8 On return, state.mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm.avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm.avail_out >= 258 for each loop to avoid checking for output space. */ module.exports = function inflate_fast(strm, start) { var state; var _in; /* local strm.input */ var last; /* have enough input while in < last */ var _out; /* local strm.output */ var beg; /* inflate()'s initial strm.output */ var end; /* while out < end, enough space available */ //#ifdef INFLATE_STRICT var dmax; /* maximum distance from zlib header */ //#endif var wsize; /* window size or zero if not using window */ var whave; /* valid bytes in the window */ var wnext; /* window write index */ // Use `s_window` instead `window`, avoid conflict with instrumentation tools var s_window; /* allocated sliding window, if wsize != 0 */ var hold; /* local strm.hold */ var bits; /* local strm.bits */ var lcode; /* local strm.lencode */ var dcode; /* local strm.distcode */ var lmask; /* mask for first level of length codes */ var dmask; /* mask for first level of distance codes */ var here; /* retrieved table entry */ var op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ var len; /* match length, unused bytes */ var dist; /* match distance */ var from; /* where to copy match from */ var from_source; var input, output; // JS specific, because we have no pointers /* copy state to local variables */ state = strm.state; //here = state.here; _in = strm.next_in; input = strm.input; last = _in + (strm.avail_in - 5); _out = strm.next_out; output = strm.output; beg = _out - (start - strm.avail_out); end = _out + (strm.avail_out - 257); //#ifdef INFLATE_STRICT dmax = state.dmax; //#endif wsize = state.wsize; whave = state.whave; wnext = state.wnext; s_window = state.window; hold = state.hold; bits = state.bits; lcode = state.lencode; dcode = state.distcode; lmask = (1 << state.lenbits) - 1; dmask = (1 << state.distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ top: do { if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = lcode[hold & lmask]; dolen: for (;;) { // Goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op === 0) { /* literal */ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); output[_out++] = here & 0xffff/*here.val*/; } else if (op & 16) { /* length base */ len = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += input[_in++] << bits; bits += 8; } len += hold & ((1 << op) - 1); hold >>>= op; bits -= op; } //Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = dcode[hold & dmask]; dodist: for (;;) { // goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op & 16) { /* distance base */ dist = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (bits < op) { hold += input[_in++] << bits; bits += 8; if (bits < op) { hold += input[_in++] << bits; bits += 8; } } dist += hold & ((1 << op) - 1); //#ifdef INFLATE_STRICT if (dist > dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } //#endif hold >>>= op; bits -= op; //Tracevv((stderr, "inflate: distance %u\n", dist)); op = _out - beg; /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // if (len <= op - whave) { // do { // output[_out++] = 0; // } while (--len); // continue top; // } // len -= op - whave; // do { // output[_out++] = 0; // } while (--op > whave); // if (op === 0) { // from = _out - dist; // do { // output[_out++] = output[from++]; // } while (--len); // continue top; // } //#endif } from = 0; // window index from_source = s_window; if (wnext === 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = 0; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } while (len > 2) { output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; len -= 3; } if (len) { output[_out++] = from_source[from++]; if (len > 1) { output[_out++] = from_source[from++]; } } } else { from = _out - dist; /* copy direct from output */ do { /* minimum length is three */ output[_out++] = output[from++]; output[_out++] = output[from++]; output[_out++] = output[from++]; len -= 3; } while (len > 2); if (len) { output[_out++] = output[from++]; if (len > 1) { output[_out++] = output[from++]; } } } } else if ((op & 64) === 0) { /* 2nd level distance code */ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dodist; } else { strm.msg = 'invalid distance code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } else if ((op & 64) === 0) { /* 2nd level length code */ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dolen; } else if (op & 32) { /* end-of-block */ //Tracevv((stderr, "inflate: end of block\n")); state.mode = TYPE; break top; } else { strm.msg = 'invalid literal/length code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } while (_in < last && _out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; _in -= len; bits -= len << 3; hold &= (1 << bits) - 1; /* update state and return */ strm.next_in = _in; strm.next_out = _out; strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); state.hold = hold; state.bits = bits; return; }; },{}],96:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var inflate_fast = _dereq_('./inffast'); var inflate_table = _dereq_('./inftrees'); var CODES = 0; var LENS = 1; var DISTS = 2; /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ //var Z_NO_FLUSH = 0; //var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; //var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* The deflate compression method */ var Z_DEFLATED = 8; /* STATES ====================================================================*/ /* ===========================================================================*/ var HEAD = 1; /* i: waiting for magic header */ var FLAGS = 2; /* i: waiting for method and flags (gzip) */ var TIME = 3; /* i: waiting for modification time (gzip) */ var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ var EXLEN = 5; /* i: waiting for extra length (gzip) */ var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ var NAME = 7; /* i: waiting for end of file name (gzip) */ var COMMENT = 8; /* i: waiting for end of comment (gzip) */ var HCRC = 9; /* i: waiting for header crc (gzip) */ var DICTID = 10; /* i: waiting for dictionary check value */ var DICT = 11; /* waiting for inflateSetDictionary() call */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ var STORED = 14; /* i: waiting for stored size (length and complement) */ var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ var COPY = 16; /* i/o: waiting for input or output to copy stored block */ var TABLE = 17; /* i: waiting for dynamic block table lengths */ var LENLENS = 18; /* i: waiting for code length code lengths */ var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ var LEN_ = 20; /* i: same as LEN below, but only first time in */ var LEN = 21; /* i: waiting for length/lit/eob code */ var LENEXT = 22; /* i: waiting for length extra bits */ var DIST = 23; /* i: waiting for distance code */ var DISTEXT = 24; /* i: waiting for distance extra bits */ var MATCH = 25; /* o: waiting for output space to copy string */ var LIT = 26; /* o: waiting for output space to write literal */ var CHECK = 27; /* i: waiting for 32-bit check value */ var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ var DONE = 29; /* finished check, done -- remain here until reset */ var BAD = 30; /* got a data error -- remain here until reset */ var MEM = 31; /* got an inflate() memory error -- remain here until reset */ var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ /* ===========================================================================*/ var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_WBITS = MAX_WBITS; function zswap32(q) { return (((q >>> 24) & 0xff) + ((q >>> 8) & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24)); } function InflateState() { this.mode = 0; /* current inflate mode */ this.last = false; /* true if processing last block */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.havedict = false; /* true if dictionary provided */ this.flags = 0; /* gzip header method and flags (0 if zlib) */ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ this.check = 0; /* protected copy of check value */ this.total = 0; /* protected copy of output count */ // TODO: may be {} this.head = null; /* where to save gzip header information */ /* sliding window */ this.wbits = 0; /* log base 2 of requested window size */ this.wsize = 0; /* window size or zero if not using window */ this.whave = 0; /* valid bytes in the window */ this.wnext = 0; /* window write index */ this.window = null; /* allocated sliding window, if needed */ /* bit accumulator */ this.hold = 0; /* input bit accumulator */ this.bits = 0; /* number of bits in "in" */ /* for string and stored block copying */ this.length = 0; /* literal or length of data to copy */ this.offset = 0; /* distance back to copy string from */ /* for table and code decoding */ this.extra = 0; /* extra bits needed */ /* fixed and dynamic code tables */ this.lencode = null; /* starting table for length/literal codes */ this.distcode = null; /* starting table for distance codes */ this.lenbits = 0; /* index bits for lencode */ this.distbits = 0; /* index bits for distcode */ /* dynamic table building */ this.ncode = 0; /* number of code length code lengths */ this.nlen = 0; /* number of length code lengths */ this.ndist = 0; /* number of distance code lengths */ this.have = 0; /* number of code lengths in lens[] */ this.next = null; /* next available space in codes[] */ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ this.work = new utils.Buf16(288); /* work area for code table building */ /* because we don't have pointers in js, we use lencode and distcode directly as buffers so we don't need codes */ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ this.distdyn = null; /* dynamic table for distance codes (JS specific) */ this.sane = 0; /* if false, allow invalid distance too far */ this.back = 0; /* bits back of last unprocessed length/lit */ this.was = 0; /* initial length of match */ } function inflateResetKeep(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; strm.total_in = strm.total_out = state.total = 0; strm.msg = ''; /*Z_NULL*/ if (state.wrap) { /* to support ill-conceived Java test suite */ strm.adler = state.wrap & 1; } state.mode = HEAD; state.last = 0; state.havedict = 0; state.dmax = 32768; state.head = null/*Z_NULL*/; state.hold = 0; state.bits = 0; //state.lencode = state.distcode = state.next = state.codes; state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); state.sane = 1; state.back = -1; //Tracev((stderr, "inflate: reset\n")); return Z_OK; } function inflateReset(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; state.wsize = 0; state.whave = 0; state.wnext = 0; return inflateResetKeep(strm); } function inflateReset2(strm, windowBits) { var wrap; var state; /* get the state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; if (windowBits < 48) { windowBits &= 15; } } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.window !== null && state.wbits !== windowBits) { state.window = null; } /* update state and reset the rest of it */ state.wrap = wrap; state.wbits = windowBits; return inflateReset(strm); } function inflateInit2(strm, windowBits) { var ret; var state; if (!strm) { return Z_STREAM_ERROR; } //strm.msg = Z_NULL; /* in case we return an error */ state = new InflateState(); //if (state === Z_NULL) return Z_MEM_ERROR; //Tracev((stderr, "inflate: allocated\n")); strm.state = state; state.window = null/*Z_NULL*/; ret = inflateReset2(strm, windowBits); if (ret !== Z_OK) { strm.state = null/*Z_NULL*/; } return ret; } function inflateInit(strm) { return inflateInit2(strm, DEF_WBITS); } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ var virgin = true; var lenfix, distfix; // We have no pointers in JS, so keep tables separate function fixedtables(state) { /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { var sym; lenfix = new utils.Buf32(512); distfix = new utils.Buf32(32); /* literal/length table */ sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } while (sym < 288) { state.lens[sym++] = 8; } inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); /* distance table */ sym = 0; while (sym < 32) { state.lens[sym++] = 5; } inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); /* do this just once */ virgin = false; } state.lencode = lenfix; state.lenbits = 9; state.distcode = distfix; state.distbits = 5; } /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ function updatewindow(strm, src, end, copy) { var dist; var state = strm.state; /* if it hasn't been done already, allocate space for the window */ if (state.window === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.window = new utils.Buf8(state.wsize); } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state.wsize) { utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); state.wnext = 0; state.whave = state.wsize; } else { dist = state.wsize - state.wnext; if (dist > copy) { dist = copy; } //zmemcpy(state->window + state->wnext, end - copy, dist); utils.arraySet(state.window, src, end - copy, dist, state.wnext); copy -= dist; if (copy) { //zmemcpy(state->window, end - copy, copy); utils.arraySet(state.window, src, end - copy, copy, 0); state.wnext = copy; state.whave = state.wsize; } else { state.wnext += dist; if (state.wnext === state.wsize) { state.wnext = 0; } if (state.whave < state.wsize) { state.whave += dist; } } } return 0; } function inflate(strm, flush) { var state; var input, output; // input/output buffers var next; /* next input INDEX */ var put; /* next output INDEX */ var have, left; /* available input and output */ var hold; /* bit buffer */ var bits; /* bits in bit buffer */ var _in, _out; /* save starting available input and output */ var copy; /* number of stored or match bytes to copy */ var from; /* where to copy match bytes from */ var from_source; var here = 0; /* current decoding table entry */ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) //var last; /* parent table entry */ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) var len; /* length to copy for repeats, bits to drop */ var ret; /* return code */ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ var opts; var n; // temporary var for NEED_BITS var order = /* permutation of code lengths */ [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; if (!strm || !strm.state || !strm.output || (!strm.input && strm.avail_in !== 0)) { return Z_STREAM_ERROR; } state = strm.state; if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- _in = have; _out = left; ret = Z_OK; inf_leave: // goto emulation for (;;) { switch (state.mode) { case HEAD: if (state.wrap === 0) { state.mode = TYPEDO; break; } //=== NEEDBITS(16); while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ state.check = 0/*crc32(0L, Z_NULL, 0)*/; //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = FLAGS; break; } state.flags = 0; /* expect zlib header */ if (state.head) { state.head.done = false; } if (!(state.wrap & 1) || /* check if zlib header allowed */ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { strm.msg = 'incorrect header check'; state.mode = BAD; break; } if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// len = (hold & 0x0f)/*BITS(4)*/ + 8; if (state.wbits === 0) { state.wbits = len; } else if (len > state.wbits) { strm.msg = 'invalid window size'; state.mode = BAD; break; } state.dmax = 1 << len; //Tracev((stderr, "inflate: zlib header ok\n")); strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = hold & 0x200 ? DICTID : TYPE; //=== INITBITS(); hold = 0; bits = 0; //===// break; case FLAGS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.flags = hold; if ((state.flags & 0xff) !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } if (state.flags & 0xe000) { strm.msg = 'unknown header flags set'; state.mode = BAD; break; } if (state.head) { state.head.text = ((hold >> 8) & 1); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = TIME; /* falls through */ case TIME: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.time = hold; } if (state.flags & 0x0200) { //=== CRC4(state.check, hold) hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; hbuf[2] = (hold >>> 16) & 0xff; hbuf[3] = (hold >>> 24) & 0xff; state.check = crc32(state.check, hbuf, 4, 0); //=== } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = OS; /* falls through */ case OS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.xflags = (hold & 0xff); state.head.os = (hold >> 8); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = EXLEN; /* falls through */ case EXLEN: if (state.flags & 0x0400) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length = hold; if (state.head) { state.head.extra_len = hold; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// } else if (state.head) { state.head.extra = null/*Z_NULL*/; } state.mode = EXTRA; /* falls through */ case EXTRA: if (state.flags & 0x0400) { copy = state.length; if (copy > have) { copy = have; } if (copy) { if (state.head) { len = state.head.extra_len - state.length; if (!state.head.extra) { // Use untyped array for more conveniend processing later state.head.extra = new Array(state.head.extra_len); } utils.arraySet( state.head.extra, input, next, // extra field is limited to 65536 bytes // - no need for additional size check copy, /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ len ); //zmemcpy(state.head.extra + len, next, // len + copy > state.head.extra_max ? // state.head.extra_max - len : copy); } if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; state.length -= copy; } if (state.length) { break inf_leave; } } state.length = 0; state.mode = NAME; /* falls through */ case NAME: if (state.flags & 0x0800) { if (have === 0) { break inf_leave; } copy = 0; do { // TODO: 2 or 1 bytes? len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.name_max*/)) { state.head.name += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.name = null; } state.length = 0; state.mode = COMMENT; /* falls through */ case COMMENT: if (state.flags & 0x1000) { if (have === 0) { break inf_leave; } copy = 0; do { len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.comm_max*/)) { state.head.comment += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.comment = null; } state.mode = HCRC; /* falls through */ case HCRC: if (state.flags & 0x0200) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.check & 0xffff)) { strm.msg = 'header crc mismatch'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// } if (state.head) { state.head.hcrc = ((state.flags >> 9) & 1); state.head.done = true; } strm.adler = state.check = 0; state.mode = TYPE; break; case DICTID: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// strm.adler = state.check = zswap32(hold); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = DICT; /* falls through */ case DICT: if (state.havedict === 0) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- return Z_NEED_DICT; } strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = TYPE; /* falls through */ case TYPE: if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } /* falls through */ case TYPEDO: if (state.last) { //--- BYTEBITS() ---// hold >>>= bits & 7; bits -= bits & 7; //---// state.mode = CHECK; break; } //=== NEEDBITS(3); */ while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.last = (hold & 0x01)/*BITS(1)*/; //--- DROPBITS(1) ---// hold >>>= 1; bits -= 1; //---// switch ((hold & 0x03)/*BITS(2)*/) { case 0: /* stored block */ //Tracev((stderr, "inflate: stored block%s\n", // state.last ? " (last)" : "")); state.mode = STORED; break; case 1: /* fixed block */ fixedtables(state); //Tracev((stderr, "inflate: fixed codes block%s\n", // state.last ? " (last)" : "")); state.mode = LEN_; /* decode codes */ if (flush === Z_TREES) { //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break inf_leave; } break; case 2: /* dynamic block */ //Tracev((stderr, "inflate: dynamic codes block%s\n", // state.last ? " (last)" : "")); state.mode = TABLE; break; case 3: strm.msg = 'invalid block type'; state.mode = BAD; } //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break; case STORED: //--- BYTEBITS() ---// /* go to byte boundary */ hold >>>= bits & 7; bits -= bits & 7; //---// //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { strm.msg = 'invalid stored block lengths'; state.mode = BAD; break; } state.length = hold & 0xffff; //Tracev((stderr, "inflate: stored length %u\n", // state.length)); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = COPY_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case COPY_: state.mode = COPY; /* falls through */ case COPY: copy = state.length; if (copy) { if (copy > have) { copy = have; } if (copy > left) { copy = left; } if (copy === 0) { break inf_leave; } //--- zmemcpy(put, next, copy); --- utils.arraySet(output, input, next, copy, put); //---// have -= copy; next += copy; left -= copy; put += copy; state.length -= copy; break; } //Tracev((stderr, "inflate: stored end\n")); state.mode = TYPE; break; case TABLE: //=== NEEDBITS(14); */ while (bits < 14) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// //#ifndef PKZIP_BUG_WORKAROUND if (state.nlen > 286 || state.ndist > 30) { strm.msg = 'too many length or distance symbols'; state.mode = BAD; break; } //#endif //Tracev((stderr, "inflate: table sizes ok\n")); state.have = 0; state.mode = LENLENS; /* falls through */ case LENLENS: while (state.have < state.ncode) { //=== NEEDBITS(3); while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } while (state.have < 19) { state.lens[order[state.have++]] = 0; } // We have separate tables & no pointers. 2 commented lines below not needed. //state.next = state.codes; //state.lencode = state.next; // Switch to use dynamic table state.lencode = state.lendyn; state.lenbits = 7; opts = { bits: state.lenbits }; ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); state.lenbits = opts.bits; if (ret) { strm.msg = 'invalid code lengths set'; state.mode = BAD; break; } //Tracev((stderr, "inflate: code lengths ok\n")); state.have = 0; state.mode = CODELENS; /* falls through */ case CODELENS: while (state.have < state.nlen + state.ndist) { for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_val < 16) { //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.lens[state.have++] = here_val; } else { if (here_val === 16) { //=== NEEDBITS(here.bits + 2); n = here_bits + 2; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// if (state.have === 0) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } len = state.lens[state.have - 1]; copy = 3 + (hold & 0x03);//BITS(2); //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// } else if (here_val === 17) { //=== NEEDBITS(here.bits + 3); n = here_bits + 3; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 3 + (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } else { //=== NEEDBITS(here.bits + 7); n = here_bits + 7; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 11 + (hold & 0x7f);//BITS(7); //--- DROPBITS(7) ---// hold >>>= 7; bits -= 7; //---// } if (state.have + copy > state.nlen + state.ndist) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } while (copy--) { state.lens[state.have++] = len; } } } /* handle error breaks in while */ if (state.mode === BAD) { break; } /* check for end-of-block code (better have one) */ if (state.lens[256] === 0) { strm.msg = 'invalid code -- missing end-of-block'; state.mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state.lenbits = 9; opts = { bits: state.lenbits }; ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.lenbits = opts.bits; // state.lencode = state.next; if (ret) { strm.msg = 'invalid literal/lengths set'; state.mode = BAD; break; } state.distbits = 6; //state.distcode.copy(state.codes); // Switch to use dynamic table state.distcode = state.distdyn; opts = { bits: state.distbits }; ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.distbits = opts.bits; // state.distcode = state.next; if (ret) { strm.msg = 'invalid distances set'; state.mode = BAD; break; } //Tracev((stderr, 'inflate: codes ok\n')); state.mode = LEN_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case LEN_: state.mode = LEN; /* falls through */ case LEN: if (have >= 6 && left >= 258) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- inflate_fast(strm, _out); //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- if (state.mode === TYPE) { state.back = -1; } break; } state.back = 0; for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_op && (here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.lencode[last_val + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; state.length = here_val; if (here_op === 0) { //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); state.mode = LIT; break; } if (here_op & 32) { //Tracevv((stderr, "inflate: end of block\n")); state.back = -1; state.mode = TYPE; break; } if (here_op & 64) { strm.msg = 'invalid literal/length code'; state.mode = BAD; break; } state.extra = here_op & 15; state.mode = LENEXT; /* falls through */ case LENEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //Tracevv((stderr, "inflate: length %u\n", state.length)); state.was = state.length; state.mode = DIST; /* falls through */ case DIST: for (;;) { here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if ((here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.distcode[last_val + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; if (here_op & 64) { strm.msg = 'invalid distance code'; state.mode = BAD; break; } state.offset = here_val; state.extra = (here_op) & 15; state.mode = DISTEXT; /* falls through */ case DISTEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //#ifdef INFLATE_STRICT if (state.offset > state.dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } //#endif //Tracevv((stderr, "inflate: distance %u\n", state.offset)); state.mode = MATCH; /* falls through */ case MATCH: if (left === 0) { break inf_leave; } copy = _out - left; if (state.offset > copy) { /* copy from window */ copy = state.offset - copy; if (copy > state.whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // Trace((stderr, "inflate.c too far\n")); // copy -= state.whave; // if (copy > state.length) { copy = state.length; } // if (copy > left) { copy = left; } // left -= copy; // state.length -= copy; // do { // output[put++] = 0; // } while (--copy); // if (state.length === 0) { state.mode = LEN; } // break; //#endif } if (copy > state.wnext) { copy -= state.wnext; from = state.wsize - copy; } else { from = state.wnext - copy; } if (copy > state.length) { copy = state.length; } from_source = state.window; } else { /* copy from output */ from_source = output; from = put - state.offset; copy = state.length; } if (copy > left) { copy = left; } left -= copy; state.length -= copy; do { output[put++] = from_source[from++]; } while (--copy); if (state.length === 0) { state.mode = LEN; } break; case LIT: if (left === 0) { break inf_leave; } output[put++] = state.length; left--; state.mode = LEN; break; case CHECK: if (state.wrap) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; // Use '|' insdead of '+' to make sure that result is signed hold |= input[next++] << bits; bits += 8; } //===// _out -= left; strm.total_out += _out; state.total += _out; if (_out) { strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); } _out = left; // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too if ((state.flags ? hold : zswap32(hold)) !== state.check) { strm.msg = 'incorrect data check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: check matches trailer\n")); } state.mode = LENGTH; /* falls through */ case LENGTH: if (state.wrap && state.flags) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.total & 0xffffffff)) { strm.msg = 'incorrect length check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: length matches trailer\n")); } state.mode = DONE; /* falls through */ case DONE: ret = Z_STREAM_END; break inf_leave; case BAD: ret = Z_DATA_ERROR; break inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* falls through */ default: return Z_STREAM_ERROR; } } // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH))) { if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { state.mode = MEM; return Z_MEM_ERROR; } } _in -= strm.avail_in; _out -= strm.avail_out; strm.total_in += _in; strm.total_out += _out; state.total += _out; if (state.wrap && _out) { strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); } strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { ret = Z_BUF_ERROR; } return ret; } function inflateEnd(strm) { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { return Z_STREAM_ERROR; } var state = strm.state; if (state.window) { state.window = null; } strm.state = null; return Z_OK; } function inflateGetHeader(strm, head) { var state; /* check state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } /* save header structure */ state.head = head; head.done = false; return Z_OK; } exports.inflateReset = inflateReset; exports.inflateReset2 = inflateReset2; exports.inflateResetKeep = inflateResetKeep; exports.inflateInit = inflateInit; exports.inflateInit2 = inflateInit2; exports.inflate = inflate; exports.inflateEnd = inflateEnd; exports.inflateGetHeader = inflateGetHeader; exports.inflateInfo = 'pako inflate (from Nodeca project)'; /* Not implemented exports.inflateCopy = inflateCopy; exports.inflateGetDictionary = inflateGetDictionary; exports.inflateMark = inflateMark; exports.inflatePrime = inflatePrime; exports.inflateSetDictionary = inflateSetDictionary; exports.inflateSync = inflateSync; exports.inflateSyncPoint = inflateSyncPoint; exports.inflateUndermine = inflateUndermine; */ },{"../utils/common":88,"./adler32":90,"./crc32":92,"./inffast":95,"./inftrees":97}],97:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var MAXBITS = 15; var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var CODES = 0; var LENS = 1; var DISTS = 2; var lbase = [ /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ]; var lext = [ /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 ]; var dbase = [ /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 ]; var dext = [ /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64 ]; module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { var bits = opts.bits; //here = opts.here; /* table entry for duplication */ var len = 0; /* a code's length in bits */ var sym = 0; /* index of code symbols */ var min = 0, max = 0; /* minimum and maximum code lengths */ var root = 0; /* number of index bits for root table */ var curr = 0; /* number of index bits for current table */ var drop = 0; /* code bits to drop for sub-table */ var left = 0; /* number of prefix codes available */ var used = 0; /* code entries in table used */ var huff = 0; /* Huffman code */ var incr; /* for incrementing code, index */ var fill; /* index for replicating entries */ var low; /* low bits for current root entry */ var mask; /* mask for low root bits */ var next; /* next available space in table */ var base = null; /* base value table to use */ var base_index = 0; // var shoextra; /* extra bits table to use */ var end; /* use base and extra for symbol > end */ var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ var extra = null; var extra_index = 0; var here_bits, here_op, here_val; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) { count[len] = 0; } for (sym = 0; sym < codes; sym++) { count[lens[lens_index + sym]]++; } /* bound code lengths, force root to be within code lengths */ root = bits; for (max = MAXBITS; max >= 1; max--) { if (count[max] !== 0) { break; } } if (root > max) { root = max; } if (max === 0) { /* no symbols to code at all */ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ //table.bits[opts.table_index] = 1; //here.bits = (var char)1; //table.val[opts.table_index++] = 0; //here.val = (var short)0; table[table_index++] = (1 << 24) | (64 << 16) | 0; //table.op[opts.table_index] = 64; //table.bits[opts.table_index] = 1; //table.val[opts.table_index++] = 0; table[table_index++] = (1 << 24) | (64 << 16) | 0; opts.bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) { if (count[min] !== 0) { break; } } if (root < min) { root = min; } /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) { return -1; } /* over-subscribed */ } if (left > 0 && (type === CODES || max !== 1)) { return -1; /* incomplete set */ } /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + count[len]; } /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) { if (lens[lens_index + sym] !== 0) { work[offs[lens[lens_index + sym]]++] = sym; } } /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ // poor man optimization - use if-else instead of switch, // to avoid deopts in old v8 if (type === CODES) { base = extra = work; /* dummy value--not used */ end = 19; } else if (type === LENS) { base = lbase; base_index -= 257; extra = lext; extra_index -= 257; end = 256; } else { /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize opts for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = table_index; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = -1; /* trigger new sub-table when len > root */ used = 1 << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } var i = 0; /* process all codes and make table entries */ for (;;) { i++; /* create table entry */ here_bits = len - drop; if (work[sym] < end) { here_op = 0; here_val = work[sym]; } else if (work[sym] > end) { here_op = extra[extra_index + work[sym]]; here_val = base[base_index + work[sym]]; } else { here_op = 32 + 64; /* end of block */ here_val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1 << (len - drop); fill = 1 << curr; min = fill; /* save offset to next table */ do { fill -= incr; table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; } while (fill !== 0); /* backwards increment the len-bit code huff */ incr = 1 << (len - 1); while (huff & incr) { incr >>= 1; } if (incr !== 0) { huff &= incr - 1; huff += incr; } else { huff = 0; } /* go to next symbol, update count, len */ sym++; if (--count[len] === 0) { if (len === max) { break; } len = lens[lens_index + work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) !== low) { /* if first time, transition to sub-tables */ if (drop === 0) { drop = root; } /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = 1 << curr; while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) { break; } curr++; left <<= 1; } /* check for enough space */ used += 1 << curr; if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* point entry in root table to sub-table */ low = huff & mask; /*table.op[low] = curr; table.bits[low] = root; table.val[low] = next - opts.table_index;*/ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff !== 0) { //table.op[next + huff] = 64; /* invalid code marker */ //table.bits[next + huff] = len - drop; //table.val[next + huff] = 0; table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; } /* set return parameters */ //opts.table_index += used; opts.bits = root; return 0; }; },{"../utils/common":88}],98:[function(_dereq_,module,exports){ 'use strict'; module.exports = { 2: 'need dictionary', /* Z_NEED_DICT 2 */ 1: 'stream end', /* Z_STREAM_END 1 */ 0: '', /* Z_OK 0 */ '-1': 'file error', /* Z_ERRNO (-1) */ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ '-3': 'data error', /* Z_DATA_ERROR (-3) */ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ }; },{}],99:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); /* Public constants ==========================================================*/ /* ===========================================================================*/ //var Z_FILTERED = 1; //var Z_HUFFMAN_ONLY = 2; //var Z_RLE = 3; var Z_FIXED = 4; //var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ var Z_BINARY = 0; var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /*============================================================================*/ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } // From zutil.h var STORED_BLOCK = 0; var STATIC_TREES = 1; var DYN_TREES = 2; /* The three kinds of block type */ var MIN_MATCH = 3; var MAX_MATCH = 258; /* The minimum and maximum match lengths */ // From deflate.h /* =========================================================================== * Internal compression state. */ var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2 * L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var Buf_size = 16; /* size of bit buffer in bi_buf */ /* =========================================================================== * Constants */ var MAX_BL_BITS = 7; /* Bit length codes must not exceed MAX_BL_BITS bits */ var END_BLOCK = 256; /* end of block literal code */ var REP_3_6 = 16; /* repeat previous bit length 3-6 times (2 bits of repeat count) */ var REPZ_3_10 = 17; /* repeat a zero length 3-10 times (3 bits of repeat count) */ var REPZ_11_138 = 18; /* repeat a zero length 11-138 times (7 bits of repeat count) */ /* eslint-disable comma-spacing,array-bracket-spacing */ var extra_lbits = /* extra bits for each length code */ [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; var extra_dbits = /* extra bits for each distance code */ [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; var extra_blbits = /* extra bits for each bit length code */ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; var bl_order = [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; /* eslint-enable comma-spacing,array-bracket-spacing */ /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ /* =========================================================================== * Local data. These are initialized only once. */ // We pre-fill arrays with 0 to avoid uninitialized gaps var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 var static_ltree = new Array((L_CODES + 2) * 2); zero(static_ltree); /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ var static_dtree = new Array(D_CODES * 2); zero(static_dtree); /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ var _dist_code = new Array(DIST_CODE_LEN); zero(_dist_code); /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); zero(_length_code); /* length code for each normalized match length (0 == MIN_MATCH) */ var base_length = new Array(LENGTH_CODES); zero(base_length); /* First normalized length for each code (0 = MIN_MATCH) */ var base_dist = new Array(D_CODES); zero(base_dist); /* First normalized distance for each code (0 = distance of 1) */ function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { this.static_tree = static_tree; /* static tree or NULL */ this.extra_bits = extra_bits; /* extra bits for each code or NULL */ this.extra_base = extra_base; /* base index for extra_bits */ this.elems = elems; /* max number of elements in the tree */ this.max_length = max_length; /* max bit length for the codes */ // show if `static_tree` has data or dummy - needed for monomorphic objects this.has_stree = static_tree && static_tree.length; } var static_l_desc; var static_d_desc; var static_bl_desc; function TreeDesc(dyn_tree, stat_desc) { this.dyn_tree = dyn_tree; /* the dynamic tree */ this.max_code = 0; /* largest code with non zero frequency */ this.stat_desc = stat_desc; /* the corresponding static tree */ } function d_code(dist) { return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; } /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ function put_short(s, w) { // put_byte(s, (uch)((w) & 0xff)); // put_byte(s, (uch)((ush)(w) >> 8)); s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff; } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ function send_bits(s, value, length) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += length; } } function send_code(s, c, tree) { send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ function bi_reverse(code, len) { var res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ function bi_flush(s) { if (s.bi_valid === 16) { put_short(s, s.bi_buf); s.bi_buf = 0; s.bi_valid = 0; } else if (s.bi_valid >= 8) { s.pending_buf[s.pending++] = s.bi_buf & 0xff; s.bi_buf >>= 8; s.bi_valid -= 8; } } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ function gen_bitlen(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var max_code = desc.max_code; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var extra = desc.stat_desc.extra_bits; var base = desc.stat_desc.extra_base; var max_length = desc.stat_desc.max_length; var h; /* heap index */ var n, m; /* iterate over the tree elements */ var bits; /* bit length */ var xbits; /* extra bits */ var f; /* frequency */ var overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) { s.bl_count[bits] = 0; } /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n * 2 + 1]/*.Len*/ = bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) { continue; } /* not a leaf node */ s.bl_count[bits]++; xbits = 0; if (n >= base) { xbits = extra[n - base]; } f = tree[n * 2]/*.Freq*/; s.opt_len += f * (bits + xbits); if (has_stree) { s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); } } if (overflow === 0) { return; } // Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length - 1; while (s.bl_count[bits] === 0) { bits--; } s.bl_count[bits]--; /* move one leaf down the tree */ s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ s.bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits !== 0; bits--) { n = s.bl_count[bits]; while (n !== 0) { m = s.heap[--h]; if (m > max_code) { continue; } if (tree[m * 2 + 1]/*.Len*/ !== bits) { // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; tree[m * 2 + 1]/*.Len*/ = bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ function gen_codes(tree, max_code, bl_count) // ct_data *tree; /* the tree to decorate */ // int max_code; /* largest code with non zero frequency */ // ushf *bl_count; /* number of codes at each bit length */ { var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ var code = 0; /* running code value */ var bits; /* bit index */ var n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits - 1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { var len = tree[n * 2 + 1]/*.Len*/; if (len === 0) { continue; } /* Now reverse the bits */ tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len); //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Initialize the various 'constant' tables. */ function tr_static_init() { var n; /* iterates over tree elements */ var bits; /* bit counter */ var length; /* length value */ var code; /* code value */ var dist; /* distance index */ var bl_count = new Array(MAX_BITS + 1); /* number of codes at each bit length for an optimal tree */ // do check in _tr_init() //if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ /*#ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif*/ /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES - 1; code++) { base_length[code] = length; for (n = 0; n < (1 << extra_lbits[code]); n++) { _length_code[length++] = code; } } //Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length - 1] = code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1 << extra_dbits[code]); n++) { _dist_code[dist++] = code; } } //Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for (; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { _dist_code[256 + dist++] = code; } } //Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) { bl_count[bits] = 0; } n = 0; while (n <= 143) { static_ltree[n * 2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } while (n <= 255) { static_ltree[n * 2 + 1]/*.Len*/ = 9; n++; bl_count[9]++; } while (n <= 279) { static_ltree[n * 2 + 1]/*.Len*/ = 7; n++; bl_count[7]++; } while (n <= 287) { static_ltree[n * 2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes(static_ltree, L_CODES + 1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n * 2 + 1]/*.Len*/ = 5; static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); } // Now data ready and we can init static trees static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); //static_init_done = true; } /* =========================================================================== * Initialize a new block. */ function init_block(s) { var n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; s.opt_len = s.static_len = 0; s.last_lit = s.matches = 0; } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ function bi_windup(s) { if (s.bi_valid > 8) { put_short(s, s.bi_buf); } else if (s.bi_valid > 0) { //put_byte(s, (Byte)s->bi_buf); s.pending_buf[s.pending++] = s.bi_buf; } s.bi_buf = 0; s.bi_valid = 0; } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ function copy_block(s, buf, len, header) //DeflateState *s; //charf *buf; /* the input data */ //unsigned len; /* its length */ //int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ if (header) { put_short(s, len); put_short(s, ~len); } // while (len--) { // put_byte(s, *buf++); // } utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); s.pending += len; } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ function smaller(tree, n, m, depth) { var _n2 = n * 2; var _m2 = m * 2; return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); } /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ function pqdownheap(s, tree, k) // deflate_state *s; // ct_data *tree; /* the tree to restore */ // int k; /* node to move down */ { var v = s.heap[k]; var j = k << 1; /* left son of k */ while (j <= s.heap_len) { /* Set j to the smallest of the two sons: */ if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s.heap[j], s.depth)) { break; } /* Exchange v with the smallest son */ s.heap[k] = s.heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s.heap[k] = v; } // inlined manually // var SMALLEST = 1; /* =========================================================================== * Send the block data compressed using the given Huffman trees */ function compress_block(s, ltree, dtree) // deflate_state *s; // const ct_data *ltree; /* literal tree */ // const ct_data *dtree; /* distance tree */ { var dist; /* distance of matched string */ var lc; /* match length or unmatched char (if dist == 0) */ var lx = 0; /* running index in l_buf */ var code; /* the code to send */ var extra; /* number of extra bits to send */ if (s.last_lit !== 0) { do { dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); lc = s.pending_buf[s.l_buf + lx]; lx++; if (dist === 0) { send_code(s, lc, ltree); /* send a literal byte */ //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code + LITERALS + 1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra !== 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); //Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra !== 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, // "pendingBuf overflow"); } while (lx < s.last_lit); } send_code(s, END_BLOCK, ltree); } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ function build_tree(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var elems = desc.stat_desc.elems; var n, m; /* iterate over heap elements */ var max_code = -1; /* largest code with non zero frequency */ var node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2]/*.Freq*/ !== 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n * 2 + 1]/*.Len*/ = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node * 2]/*.Freq*/ = 1; s.depth[node] = 0; s.opt_len--; if (has_stree) { s.static_len -= stree[node * 2 + 1]/*.Len*/; } /* node is 0 or 1 so it does not have extra bits */ } desc.max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { //pqremove(s, tree, n); /* n = node of least frequency */ /*** pqremove ***/ n = s.heap[1/*SMALLEST*/]; s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; pqdownheap(s, tree, 1/*SMALLEST*/); /***/ m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ s.heap[--s.heap_max] = m; /* Create a new node father of n and m */ tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; /* and insert the new node in the heap */ s.heap[1/*SMALLEST*/] = node++; pqdownheap(s, tree, 1/*SMALLEST*/); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, desc); /* The field len is now set, we can generate the bit codes */ gen_codes(tree, max_code, s.bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ function scan_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ if (nextlen === 0) { max_count = 138; min_count = 3; } tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { s.bl_tree[curlen * 2]/*.Freq*/ += count; } else if (curlen !== 0) { if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } s.bl_tree[REP_3_6 * 2]/*.Freq*/++; } else if (count <= 10) { s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; } else { s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ function send_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen === 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); } else if (curlen !== 0) { if (curlen !== prevlen) { send_code(s, curlen, s.bl_tree); count--; } //Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s.bl_tree); send_bits(s, count - 3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s.bl_tree); send_bits(s, count - 3, 3); } else { send_code(s, REPZ_11_138, s.bl_tree); send_bits(s, count - 11, 7); } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ function build_bl_tree(s) { var max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, s.dyn_ltree, s.l_desc.max_code); scan_tree(s, s.dyn_dtree, s.d_desc.max_code); /* Build the bit length tree: */ build_tree(s, s.bl_desc); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { break; } } /* Update opt_len to include the bit length tree and counts */ s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", // s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ function send_all_trees(s, lcodes, dcodes, blcodes) // deflate_state *s; // int lcodes, dcodes, blcodes; /* number of codes for each tree */ { var rank; /* index in bl_order */ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, // "too many codes"); //Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes - 1, 5); send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); } //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ function detect_data_type(s) { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ var black_mask = 0xf3ffc07f; var n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>>= 1) { if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { return Z_BINARY; } } /* Check for textual ("white-listed") bytes. */ if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { return Z_TEXT; } for (n = 32; n < LITERALS; n++) { if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { return Z_TEXT; } } /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } var static_init_done = false; /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ function _tr_init(s) { if (!static_init_done) { tr_static_init(); static_init_done = true; } s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); s.bi_buf = 0; s.bi_valid = 0; /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Send a stored block */ function _tr_stored_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ copy_block(s, buf, stored_len, true); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. */ function _tr_align(s) { send_bits(s, STATIC_TREES << 1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ function _tr_flush_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block, or NULL if too old */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ var max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s.level > 0) { /* Check if the file is binary or text */ if (s.strm.data_type === Z_UNKNOWN) { s.strm.data_type = detect_data_type(s); } /* Construct the literal and distance trees */ build_tree(s, s.l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); build_tree(s, s.d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s.opt_len + 3 + 7) >>> 3; static_lenb = (s.static_len + 3 + 7) >>> 3; // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, // s->last_lit)); if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } } else { // Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { /* 4: two words for the lengths */ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); compress_block(s, static_ltree, static_dtree); } else { send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); compress_block(s, s.dyn_ltree, s.dyn_dtree); } // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); } // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, // s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ function _tr_tally(s, dist, lc) // deflate_state *s; // unsigned dist; /* distance of matched string */ // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { //var out_length, in_length, dcode; s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; s.last_lit++; if (dist === 0) { /* lc is the unmatched char */ s.dyn_ltree[lc * 2]/*.Freq*/++; } else { s.matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ //Assert((ush)dist < (ush)MAX_DIST(s) && // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef TRUNCATE_BLOCK // /* Try to guess if it is profitable to stop the current block here */ // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { // /* Compute an upper bound for the compressed length */ // out_length = s.last_lit*8; // in_length = s.strstart - s.block_start; // // for (dcode = 0; dcode < D_CODES; dcode++) { // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); // } // out_length >>>= 3; // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", // // s->last_lit, in_length, out_length, // // 100L - out_length*100L/in_length)); // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { // return true; // } // } //#endif return (s.last_lit === s.lit_bufsize - 1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } exports._tr_init = _tr_init; exports._tr_stored_block = _tr_stored_block; exports._tr_flush_block = _tr_flush_block; exports._tr_tally = _tr_tally; exports._tr_align = _tr_align; },{"../utils/common":88}],100:[function(_dereq_,module,exports){ 'use strict'; function ZStream() { /* next input byte */ this.input = null; // JS specific, because we have no pointers this.next_in = 0; /* number of bytes available at input */ this.avail_in = 0; /* total number of input bytes read so far */ this.total_in = 0; /* next output byte should be put there */ this.output = null; // JS specific, because we have no pointers this.next_out = 0; /* remaining free space at output */ this.avail_out = 0; /* total number of bytes output so far */ this.total_out = 0; /* last error message, NULL if no error */ this.msg = ''/*Z_NULL*/; /* not visible by applications */ this.state = null; /* best guess about the data type: binary or text */ this.data_type = 2/*Z_UNKNOWN*/; /* adler32 value of the uncompressed data */ this.adler = 0; } module.exports = ZStream; },{}],101:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],102:[function(_dereq_,module,exports){ 'use strict'; var asap = _dereq_('asap') module.exports = Promise function Promise(fn) { if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new') if (typeof fn !== 'function') throw new TypeError('not a function') var state = null var value = null var deferreds = [] var self = this this.then = function(onFulfilled, onRejected) { return new Promise(function(resolve, reject) { handle(new Handler(onFulfilled, onRejected, resolve, reject)) }) } function handle(deferred) { if (state === null) { deferreds.push(deferred) return } asap(function() { var cb = state ? deferred.onFulfilled : deferred.onRejected if (cb === null) { (state ? deferred.resolve : deferred.reject)(value) return } var ret try { ret = cb(value) } catch (e) { deferred.reject(e) return } deferred.resolve(ret) }) } function resolve(newValue) { try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.') if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) { var then = newValue.then if (typeof then === 'function') { doResolve(then.bind(newValue), resolve, reject) return } } state = true value = newValue finale() } catch (e) { reject(e) } } function reject(newValue) { state = false value = newValue finale() } function finale() { for (var i = 0, len = deferreds.length; i < len; i++) handle(deferreds[i]) deferreds = null } doResolve(fn, resolve, reject) } function Handler(onFulfilled, onRejected, resolve, reject){ this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null this.onRejected = typeof onRejected === 'function' ? onRejected : null this.resolve = resolve this.reject = reject } /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function doResolve(fn, onFulfilled, onRejected) { var done = false; try { fn(function (value) { if (done) return done = true onFulfilled(value) }, function (reason) { if (done) return done = true onRejected(reason) }) } catch (ex) { if (done) return done = true onRejected(ex) } } },{"asap":44}],103:[function(_dereq_,module,exports){ 'use strict'; //This file contains then/promise specific extensions to the core promise API var Promise = _dereq_('./core.js') var asap = _dereq_('asap') module.exports = Promise /* Static Functions */ function ValuePromise(value) { this.then = function (onFulfilled) { if (typeof onFulfilled !== 'function') return this return new Promise(function (resolve, reject) { asap(function () { try { resolve(onFulfilled(value)) } catch (ex) { reject(ex); } }) }) } } ValuePromise.prototype = Object.create(Promise.prototype) var TRUE = new ValuePromise(true) var FALSE = new ValuePromise(false) var NULL = new ValuePromise(null) var UNDEFINED = new ValuePromise(undefined) var ZERO = new ValuePromise(0) var EMPTYSTRING = new ValuePromise('') Promise.resolve = function (value) { if (value instanceof Promise) return value if (value === null) return NULL if (value === undefined) return UNDEFINED if (value === true) return TRUE if (value === false) return FALSE if (value === 0) return ZERO if (value === '') return EMPTYSTRING if (typeof value === 'object' || typeof value === 'function') { try { var then = value.then if (typeof then === 'function') { return new Promise(then.bind(value)) } } catch (ex) { return new Promise(function (resolve, reject) { reject(ex) }) } } return new ValuePromise(value) } Promise.from = Promise.cast = function (value) { var err = new Error('Promise.from and Promise.cast are deprecated, use Promise.resolve instead') err.name = 'Warning' console.warn(err.stack) return Promise.resolve(value) } Promise.denodeify = function (fn, argumentCount) { argumentCount = argumentCount || Infinity return function () { var self = this var args = Array.prototype.slice.call(arguments) return new Promise(function (resolve, reject) { while (args.length && args.length > argumentCount) { args.pop() } args.push(function (err, res) { if (err) reject(err) else resolve(res) }) fn.apply(self, args) }) } } Promise.nodeify = function (fn) { return function () { var args = Array.prototype.slice.call(arguments) var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null try { return fn.apply(this, arguments).nodeify(callback) } catch (ex) { if (callback === null || typeof callback == 'undefined') { return new Promise(function (resolve, reject) { reject(ex) }) } else { asap(function () { callback(ex) }) } } } } Promise.all = function () { var calledWithArray = arguments.length === 1 && Array.isArray(arguments[0]) var args = Array.prototype.slice.call(calledWithArray ? arguments[0] : arguments) if (!calledWithArray) { var err = new Error('Promise.all should be called with a single array, calling it with multiple arguments is deprecated') err.name = 'Warning' console.warn(err.stack) } return new Promise(function (resolve, reject) { if (args.length === 0) return resolve([]) var remaining = args.length function res(i, val) { try { if (val && (typeof val === 'object' || typeof val === 'function')) { var then = val.then if (typeof then === 'function') { then.call(val, function (val) { res(i, val) }, reject) return } } args[i] = val if (--remaining === 0) { resolve(args); } } catch (ex) { reject(ex) } } for (var i = 0; i < args.length; i++) { res(i, args[i]) } }) } Promise.reject = function (value) { return new Promise(function (resolve, reject) { reject(value); }); } Promise.race = function (values) { return new Promise(function (resolve, reject) { values.forEach(function(value){ Promise.resolve(value).then(resolve, reject); }) }); } /* Prototype Methods */ Promise.prototype.done = function (onFulfilled, onRejected) { var self = arguments.length ? this.then.apply(this, arguments) : this self.then(null, function (err) { asap(function () { throw err }) }) } Promise.prototype.nodeify = function (callback) { if (typeof callback != 'function') return this this.then(function (value) { asap(function () { callback(null, value) }) }, function (err) { asap(function () { callback(err) }) }) } Promise.prototype['catch'] = function (onRejected) { return this.then(null, onRejected); } },{"./core.js":102,"asap":44}]},{},[1]);
/*! * isobject <https://github.com/jonschlinkert/isobject> * * Copyright (c) 2014-2015, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; var isArray = require('isarray'); module.exports = function isObject(o) { return o != null && typeof o === 'object' && !isArray(o); };
/** * Tabby v7.4.6 * Simple, mobile-first toggle tabs., by Chris Ferdinandi. * http://github.com/cferdinandi/tabby * * Free to use under the MIT License. * http://gomakethings.com/mit/ */ /* * classList.js: Cross-browser full element.classList implementation. * 2014-01-31 * * By Eli Grey, http://eligrey.com * Public Domain. * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. */ /*global self, document, DOMException */ /*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js*/ if ("document" in self && !("classList" in document.createElement("_"))) { (function (view) { "use strict"; if (!('Element' in view)) return; var classListProp = "classList", protoProp = "prototype", elemCtrProto = view.Element[protoProp], objCtr = Object, strTrim = String[protoProp].trim || function () { return this.replace(/^\s+|\s+$/g, ""); }, arrIndexOf = Array[protoProp].indexOf || function (item) { var i = 0, len = this.length; for (; i < len; i++) { if (i in this && this[i] === item) { return i; } } return -1; }, // Vendors: please allow content code to instantiate DOMExceptions DOMEx = function (type, message) { this.name = type; this.code = DOMException[type]; this.message = message; }, checkTokenAndGetIndex = function (classList, token) { if (token === "") { throw new DOMEx( "SYNTAX_ERR", "An invalid or illegal string was specified" ); } if (/\s/.test(token)) { throw new DOMEx( "INVALID_CHARACTER_ERR", "String contains an invalid character" ); } return arrIndexOf.call(classList, token); }, ClassList = function (elem) { var trimmedClasses = strTrim.call(elem.getAttribute("class") || ""), classes = trimmedClasses ? trimmedClasses.split(/\s+/) : [], i = 0, len = classes.length; for (; i < len; i++) { this.push(classes[i]); } this._updateClassName = function () { elem.setAttribute("class", this.toString()); }; }, classListProto = ClassList[protoProp] = [], classListGetter = function () { return new ClassList(this); }; // Most DOMException implementations don't allow calling DOMException's toString() // on non-DOMExceptions. Error's toString() is sufficient here. DOMEx[protoProp] = Error[protoProp]; classListProto.item = function (i) { return this[i] || null; }; classListProto.contains = function (token) { token += ""; return checkTokenAndGetIndex(this, token) !== -1; }; classListProto.add = function () { var tokens = arguments, i = 0, l = tokens.length, token, updated = false; do { token = tokens[i] + ""; if (checkTokenAndGetIndex(this, token) === -1) { this.push(token); updated = true; } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.remove = function () { var tokens = arguments, i = 0, l = tokens.length, token, updated = false; do { token = tokens[i] + ""; var index = checkTokenAndGetIndex(this, token); if (index !== -1) { this.splice(index, 1); updated = true; } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.toggle = function (token, force) { token += ""; var result = this.contains(token), method = result ? force !== true && "remove" : force !== false && "add"; if (method) { this[method](token); } return !result; }; classListProto.toString = function () { return this.join(" "); }; if (objCtr.defineProperty) { var classListPropDesc = { get: classListGetter, enumerable: true, configurable: true }; try { objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } catch (ex) { // IE 8 doesn't support enumerable:true if (ex.number === -0x7FF5EC54) { classListPropDesc.enumerable = false; objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } } } else if (objCtr[protoProp].__defineGetter__) { elemCtrProto.__defineGetter__(classListProp, classListGetter); } }(self)); }
module.exports={title:"NetApp",slug:"netapp",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>NetApp</title><path d="M0 2v20h9.33V10h5.34v12H24V2Z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"http://www.netapp.com/",hex:"0067C5",guidelines:"https://www.netapp.com/company/legal/trademark-guidelines/",license:void 0};
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v4.0.2 * @link http://www.ag-grid.com/ * @license MIT */ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; var gridOptionsWrapper_1 = require('../gridOptionsWrapper'); var logger_1 = require('../logger'); var columnUtils_1 = require('../columnController/columnUtils'); var columnKeyCreator_1 = require("./columnKeyCreator"); var originalColumnGroup_1 = require("../entities/originalColumnGroup"); var column_1 = require("../entities/column"); var context_1 = require("../context/context"); var context_2 = require("../context/context"); var context_3 = require("../context/context"); var context_4 = require("../context/context"); // takes in a list of columns, as specified by the column definitions, and returns column groups var BalancedColumnTreeBuilder = (function () { function BalancedColumnTreeBuilder() { } BalancedColumnTreeBuilder.prototype.agWire = function (loggerFactory) { this.logger = loggerFactory.create('BalancedColumnTreeBuilder'); }; BalancedColumnTreeBuilder.prototype.createBalancedColumnGroups = function (abstractColDefs) { // column key creator dishes out unique column id's in a deterministic way, // so if we have two grids (that cold be master/slave) with same column definitions, // then this ensures the two grids use identical id's. var columnKeyCreator = new columnKeyCreator_1.ColumnKeyCreator(); // create am unbalanced tree that maps the provided definitions var unbalancedTree = this.recursivelyCreateColumns(abstractColDefs, 0, columnKeyCreator); var treeDept = this.findMaxDept(unbalancedTree, 0); this.logger.log('Number of levels for grouped columns is ' + treeDept); var balancedTree = this.balanceColumnTree(unbalancedTree, 0, treeDept, columnKeyCreator); this.columnUtils.deptFirstOriginalTreeSearch(balancedTree, function (child) { if (child instanceof originalColumnGroup_1.OriginalColumnGroup) { child.calculateExpandable(); } }); return { balancedTree: balancedTree, treeDept: treeDept }; }; BalancedColumnTreeBuilder.prototype.balanceColumnTree = function (unbalancedTree, currentDept, columnDept, columnKeyCreator) { var _this = this; var result = []; // go through each child, for groups, recurse a level deeper, // for columns we need to pad unbalancedTree.forEach(function (child) { if (child instanceof originalColumnGroup_1.OriginalColumnGroup) { var originalGroup = child; var newChildren = _this.balanceColumnTree(originalGroup.getChildren(), currentDept + 1, columnDept, columnKeyCreator); originalGroup.setChildren(newChildren); result.push(originalGroup); } else { var newChild = child; for (var i = columnDept - 1; i >= currentDept; i--) { var newColId = columnKeyCreator.getUniqueKey(null, null); var paddedGroup = new originalColumnGroup_1.OriginalColumnGroup(null, newColId); paddedGroup.setChildren([newChild]); newChild = paddedGroup; } result.push(newChild); } }); return result; }; BalancedColumnTreeBuilder.prototype.findMaxDept = function (treeChildren, dept) { var maxDeptThisLevel = dept; for (var i = 0; i < treeChildren.length; i++) { var abstractColumn = treeChildren[i]; if (abstractColumn instanceof originalColumnGroup_1.OriginalColumnGroup) { var originalGroup = abstractColumn; var newDept = this.findMaxDept(originalGroup.getChildren(), dept + 1); if (maxDeptThisLevel < newDept) { maxDeptThisLevel = newDept; } } } return maxDeptThisLevel; }; BalancedColumnTreeBuilder.prototype.recursivelyCreateColumns = function (abstractColDefs, level, columnKeyCreator) { var _this = this; var result = []; if (!abstractColDefs) { return result; } abstractColDefs.forEach(function (abstractColDef) { _this.checkForDeprecatedItems(abstractColDef); if (_this.isColumnGroup(abstractColDef)) { var groupColDef = abstractColDef; var groupId = columnKeyCreator.getUniqueKey(groupColDef.groupId, null); var originalGroup = new originalColumnGroup_1.OriginalColumnGroup(groupColDef, groupId); var children = _this.recursivelyCreateColumns(groupColDef.children, level + 1, columnKeyCreator); originalGroup.setChildren(children); result.push(originalGroup); } else { var colDef = abstractColDef; var colId = columnKeyCreator.getUniqueKey(colDef.colId, colDef.field); var column = new column_1.Column(colDef, colId); _this.context.wireBean(column); result.push(column); } }); return result; }; BalancedColumnTreeBuilder.prototype.checkForDeprecatedItems = function (colDef) { if (colDef) { var colDefNoType = colDef; // take out the type, so we can access attributes not defined in the type if (colDefNoType.group !== undefined) { console.warn('ag-grid: colDef.group is invalid, please check documentation on how to do grouping as it changed in version 3'); } if (colDefNoType.headerGroup !== undefined) { console.warn('ag-grid: colDef.headerGroup is invalid, please check documentation on how to do grouping as it changed in version 3'); } if (colDefNoType.headerGroupShow !== undefined) { console.warn('ag-grid: colDef.headerGroupShow is invalid, should be columnGroupShow, please check documentation on how to do grouping as it changed in version 3'); } } }; // if object has children, we assume it's a group BalancedColumnTreeBuilder.prototype.isColumnGroup = function (abstractColDef) { return abstractColDef.children !== undefined; }; __decorate([ context_3.Autowired('gridOptionsWrapper'), __metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper) ], BalancedColumnTreeBuilder.prototype, "gridOptionsWrapper", void 0); __decorate([ context_3.Autowired('columnUtils'), __metadata('design:type', columnUtils_1.ColumnUtils) ], BalancedColumnTreeBuilder.prototype, "columnUtils", void 0); __decorate([ context_3.Autowired('context'), __metadata('design:type', context_4.Context) ], BalancedColumnTreeBuilder.prototype, "context", void 0); __decorate([ __param(0, context_2.Qualifier('loggerFactory')), __metadata('design:type', Function), __metadata('design:paramtypes', [logger_1.LoggerFactory]), __metadata('design:returntype', void 0) ], BalancedColumnTreeBuilder.prototype, "agWire", null); BalancedColumnTreeBuilder = __decorate([ context_1.Bean('balancedColumnTreeBuilder'), __metadata('design:paramtypes', []) ], BalancedColumnTreeBuilder); return BalancedColumnTreeBuilder; })(); exports.BalancedColumnTreeBuilder = BalancedColumnTreeBuilder;
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":5,"../lib/Shim.IE8":29}],2:[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":25,"./Shared":28}],3:[function(_dereq_,module,exports){ "use strict"; var crcTable, checksum; crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); /** * Returns a checksum of a string. * @param {String} str The string to checksum. * @return {Number} The checksum generated. */ checksum = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; module.exports = checksum; },{}],4:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Overload, ReactorIO, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this.sharedPathSolver = sharedPathSolver; this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); sharedPathSolver = new Path(); /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. */ Shared.synthesize(Collection.prototype, 'cappedSize'); Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', { keyName: keyName, oldData: oldKey }); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = new Date(); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); if (this.chainWillSend()) { this.chainSend('setData', { dataSet: this.decouple(data), oldData: oldData }); } op.time('Resolve chains'); op.stop(); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a hash string jString = this.hash(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This should use remove so that chain reactor events are properly // TODO: handled, but ensure that chunking is switched off this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.emit('immediateChange', {type: 'truncate'}); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj, callback); break; case 'update': returnData.result = this.update(query, obj, {}, callback); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when the update is * complete. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } else { // Decouple the update data update = this.decouple(update); } // Handle transform update = this.transformIn(update); return this._handleUpdate(query, update, options, callback); }; Collection.prototype._handleUpdate = function (query, update, options, callback) { var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); if (this.chainWillSend()) { this.chainSend('update', { query: query, update: update, dataSet: this.decouple(updated) }, options); } op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); if (callback) { callback(); } this.emit('immediateChange', {type: 'update', data: updated}); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.emit('immediateChange', {type: 'remove', data: returnArr}); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback(false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback(resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback(resultObj); } this._onChange(); this.emit('immediateChange', {type: 'insert', data: inserted}); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); if (self.chainWillSend()) { self.chainSend('insert', { dataSet: self.decouple([doc]) }, { index: index }); } //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, hash = this.hash(doc), pk = this._primaryKey; // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[pk], doc); this._primaryCrc.uniqueSet(doc[pk], hash); this._crcLookup.uniqueSet(hash, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, hash = this.hash(doc), pk = this._primaryKey; // Remove from primary key index this._primaryIndex.unSet(doc[pk]); this._primaryCrc.unSet(doc[pk]); this._crcLookup.unSet(hash); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback('Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinIndex, joinSource = {}, joinQuery, joinPath, joinSourceKey, joinSourceType, joinSourceIdentifier, joinSourceData, resultRemove = [], i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); // Check if the query tries to limit by data that would only exist after // the join operation has been completed if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get references to the join sources op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinSourceData = analysis.joinsOn[joinIndex]; joinSourceKey = joinSourceData.key; joinSourceType = joinSourceData.type; joinSourceIdentifier = joinSourceData.id; joinPath = new Path(analysis.joinQueries[joinSourceKey]); joinQuery = joinPath.value(query)[0]; joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinSourceKey]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource)); op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); this.spliceArrayByIndexList(resultArr, resultRemove); op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } };*/ /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ /*Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } };*/ /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ /*Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; };*/ /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinSourceIndex, joinSourceKey, joinSourceType, joinSourceIdentifier, joinMatch, joinSources = [], joinSourceReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) { // Loop the join sources and keep a reference to them for (joinSourceKey in options.$join[joinSourceIndex]) { if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) { joinMatch = options.$join[joinSourceIndex][joinSourceKey]; joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; joinSources.push({ id: joinSourceIdentifier, type: joinSourceType, key: joinSourceKey }); // Check if the join uses an $as operator if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) { joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as); } else { joinSourceReferences.push(joinSourceKey); } } } } // Loop the join source references and determine if the query references // any of the sources that are used in the join. If there no queries against // joined sources the find method can use a code path optimised for this. // Queries against joined sources requires the joined sources to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinSourceReferences.length; index++) { // Check if the query references any source data that the join will create queryPath = this._queryReferencesSource(query, joinSourceReferences[index], ''); if (queryPath) { analysis.joinQueries[joinSources[index].key] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinSources; analysis.queriesOn = analysis.queriesOn.concat(joinSources); } return analysis; }; /** * Checks if the passed query references a source object (such * as a collection) by name. * @param {Object} query The query object to scan. * @param {String} sourceName The source name to scan for in the query. * @param {String=} path The path to scan from. * @returns {*} * @private */ Collection.prototype._queryReferencesSource = function (query, sourceName, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === sourceName) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesSource(query[i], sourceName, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents that matches * the subDocQuery parameter. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; case '2d': index = new Index2d(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data.dataSet); self.update({}, obj1); } else { self.insert(packet.data.dataSet); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data.dataSet); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Index2d":8,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":24,"./Path":25,"./ReactorIO":26,"./Shared":28}],5:[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":6,"./Metrics.js":12,"./Overload":24,"./Shared":28}],6:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Checksum, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Checksum = _dereq_('./Checksum.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.Checksum = Checksum; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Checksum.js":3,"./Collection.js":4,"./Metrics.js":12,"./Overload":24,"./Shared":28}],7:[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; },{}],8:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.lookup = function (query, options) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options) { var self = this, geoHash, neighbours, visited, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } // Get the lngLat geohash from the query geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision); // Calculate 9 box geohashes neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'}); // Lookup all matching co-ordinates from the btree results = []; visited = 0; for (i = 0; i < 9; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visited += search._visited; results = results.concat(search); } // Work with original data results = this._collection._primaryIndex.lookup(results); if (results.length) { distance = {}; // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { // Add item inside radius distance finalResults.push(results[i]); } } // Sort by distance from center finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; Index2d.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; Index2d.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":2,"./GeoHash":7,"./Path":25,"./Shared":28}],9:[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":2,"./Path":25,"./Shared":28}],10:[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":25,"./Shared":28}],11:[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":28}],12:[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":23,"./Shared":28}],13:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],14:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * Creates a chain link between the current reactor node and the passed * reactor node. Chain packets that are send by this reactor node will * then be propagated to the passed node for subsequent packets. * @param {*} obj The chain reactor node to link to. */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, /** * Removes a chain link between the current reactor node and the passed * reactor node. Chain packets sent from this reactor node will no longer * be received by the passed node. * @param {*} obj The chain reactor node to unlink from. */ unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, /** * Determines if this chain reactor node has any listeners downstream. * @returns {Boolean} True if there are nodes downstream of this node. */ chainWillSend: function () { return Boolean(this._chain); }, /** * Sends a chain reactor packet downstream from this node to any of its * chained targets that were linked to this node via a call to chain(). * @param {String} type The type of chain reactor packet to send. This * can be any string but the receiving reactor nodes will not react to * it unless they recognise the string. Built-in strings include: "insert", * "update", "remove", "setData" and "debug". * @param {Object} data A data object that usually contains a key called * "dataSet" which is an array of items to work on, and can contain other * custom keys that help describe the operation. * @param {Object=} options An options object. Can also contain custom * key/value pairs that your custom chain reactor code can operate on. */ chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index; 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!'); } } } }, /** * Handles receiving a chain reactor message that was sent via the chainSend() * method. Creates the chain packet object and then allows it to be processed. * @param {Object} sender The node that is sending the packet. * @param {String} type The type of packet. * @param {Object} data The data related to the packet. * @param {Object=} options An options object. */ chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }, cancelPropagate = false; if (this.debug && this.debug()) { console.log(this.logIdentifier() + ' Received data from parent reactor node'); } // Check if we have a chain handler method if (this._chainHandler) { // Fire our internal handler cancelPropagate = this._chainHandler(chainPacket); } // Check if we were told to cancel further propagation if (!cancelPropagate) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],15:[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, /** * The ForerunnerDB Date object that allows data serialisation in an * automated fashion. Using this object provides ForerunnerDB with over * 5 times the performance serialising and 2 times the performance * de-serialising over walking an object tree as jStringify and jParse * used to have to do. * @param year * @param month * @param day * @param hour * @param minutes * @param seconds * @param milliseconds * @returns {*} * @constructor */ FDBDate: function (year, month, day, hour, minutes, seconds, milliseconds) { var newDate, argLength = arguments.length; if (argLength === 0) { newDate = new Date(); } if (argLength === 1) { newDate = new Date(year); } if (argLength === 2) { newDate = new Date(year, month); } if (argLength === 3) { newDate = new Date(year, month, day); } if (argLength === 4) { newDate = new Date(year, month, day, hour); } if (argLength === 5) { newDate = new Date(year, month, day, hour, minutes); } if (argLength === 6) { newDate = new Date(year, month, day, hour, minutes, seconds); } if (argLength === 7) { newDate = new Date(year, month, day, hour, minutes, seconds, milliseconds); } newDate.toJSON = function () { return {"$date": this.toISOString()}; }; return newDate; }, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined && data !== "") { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return serialiser.parse(data); //return JSON.parse(data); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { return serialiser.stringify(data); //return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Generates a unique hash for the passed object. * @param {Object} obj The object to generate a hash for. * @returns {String} */ hash: function (obj) { return JSON.stringify(obj); }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return 'ForerunnerDB ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; }, /** * Registers a timed callback that will overwrite itself if * the same id is used within the timeout period. Useful * for de-bouncing fast-calls. * @param {String} id An ID for the call (use the same one * to debounce the same calls). * @param {Function} callback The callback method to call on * timeout. * @param {Number} timeout The timeout in milliseconds before * the callback is called. */ debounce: function (id, callback, timeout) { var self = this, newData; self._debounce = self._debounce || {}; if (self._debounce[id]) { // Clear timeout for this item clearTimeout(self._debounce[id].timeout); } newData = { callback: callback, timeout: setTimeout(function () { // Delete existing reference delete self._debounce[id]; // Call the callback callback(); }, timeout) }; // Save current data self._debounce[id] = newData; } }; module.exports = Common; },{"./Overload":24,"./Serialiser":27}],16:[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; },{}],17:[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":24}],18:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; }, /** * * @param {Array | Object} docArr An array of objects to run the join * operation against or a single object. * @param {Array} joinClause The join clause object array (the array in * the $join key of a normal join options object). * @param {Object} joinSource An object containing join source reference * data or a blank object if you are doing a bespoke join operation. * @param {Object} options An options object or blank object if no options. * @returns {Array} * @private */ applyJoin: function (docArr, joinClause, joinSource, options) { var self = this, joinSourceIndex, joinSourceKey, joinMatch, joinSourceType, joinSourceIdentifier, resultKeyName, joinSourceInstance, resultIndex, joinSearchQuery, joinMulti, joinRequire, joinPrefix, joinMatchIndex, joinMatchData, joinSearchOptions, joinFindResults, joinFindResult, joinItem, resultRemove = [], l; if (!(docArr instanceof Array)) { // Turn the document into an array docArr = [docArr]; } for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) { for (joinSourceKey in joinClause[joinSourceIndex]) { if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) { // Get the match data for the join joinMatch = joinClause[joinSourceIndex][joinSourceKey]; // Check if the join is to a collection (default) or a specified source type // e.g 'view' or 'collection' joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; // Set the key to store the join result in to the collection name by default // can be overridden by the '$as' clause in the join object resultKeyName = joinSourceKey; // Get the join collection instance from the DB if (joinSource[joinSourceIdentifier]) { // We have a joinSource for this identifier already (given to us by // an index when we analysed the query earlier on) and we can use // that source instead. joinSourceInstance = joinSource[joinSourceIdentifier]; } else { // We do not already have a joinSource so grab the instance from the db if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') { joinSourceInstance = this._db[joinSourceType](joinSourceKey); } } // Loop our result data array for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultKeyName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultKeyName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = docArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultIndex); } } } } } return resultRemove; }, /** * Takes a query object with dynamic references and converts the references * into actual values from the references source. * @param {Object} query The query object with dynamic references. * @param {Object} item The document to apply the references to. * @returns {*} * @private */ resolveDynamicQuery: function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; // Check for early exit conditions if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3)); } else { pathResult = this.sharedPathSolver.value(item, query); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self.resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }, spliceArrayByIndexList: function (arr, list) { var i; for (i = list.length - 1; i >= 0; i--) { arr.splice(list[i], 1); } } }; module.exports = Matching; },{}],19:[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; },{}],20:[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; },{}],21:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * When called in a before phase the newDoc object can be directly altered * to modify the data in it before the operation is carried out. * @callback addTriggerCallback * @param {Object} operation The details about the operation. * @param {Object} oldDoc The document before the operation. * @param {Object} newDoc The document after the operation. */ /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Constants} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Constants} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {addTriggerCallback} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":24}],22:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],23:[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":25,"./Shared":28}],24:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, name; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } name = typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload: ', def); throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],25:[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":28}],26:[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":28}],27:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { this._encoder = []; this._decoder = {}; // Handler for Date() objects this.registerEncoder('$date', function (data) { if (data instanceof Date) { return data.toISOString(); } }); this.registerDecoder('$date', function (data) { return new Date(data); }); // Handler for RegExp() objects this.registerEncoder('$regexp', function (data) { if (data instanceof RegExp) { return { source: data.source, params: '' + (data.global ? 'g' : '') + (data.ignoreCase ? 'i' : '') }; } }); this.registerDecoder('$regexp', function (data) { var type = typeof data; if (type === 'object') { return new RegExp(data.source, data.params); } else if (type === 'string') { return new RegExp(data); } }); }; /** * Register an encoder that can handle encoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. * @param {Function} method The encoder method. */ Serialiser.prototype.registerEncoder = function (handles, method) { this._encoder.push(function (data) { var methodVal = method(data), returnObj; if (methodVal !== undefined) { returnObj = {}; returnObj[handles] = methodVal; } return returnObj; }); }; /** * Register a decoder that can handle decoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. When an object * has a field matching this handler name then this decode will be invoked * to provide a decoded version of the data that was previously encoded by * it's counterpart encoder method. * @param {Function} method The decoder method. */ Serialiser.prototype.registerDecoder = function (handles, method) { this._decoder[handles] = method; }; /** * Loops the encoders and asks each one if it wants to handle encoding for * the passed data object. If no value is returned (undefined) then the data * will be passed to the next encoder and so on. If a value is returned the * loop will break and the encoded data will be used. * @param {Object} data The data object to handle. * @returns {*} The encoded data. * @private */ Serialiser.prototype._encode = function (data) { // Loop the encoders and if a return value is given by an encoder // the loop will exit and return that value. var count = this._encoder.length, retVal; while (count-- && !retVal) { retVal = this._encoder[count](data); } return retVal; }; /** * Converts a previously encoded string back into an object. * @param {String} data The string to convert to an object. * @returns {Object} The reconstituted object. */ Serialiser.prototype.parse = function (data) { if (data) { var jsonObject = JSON.parse(data), handler; // Check the string for special parse indicators for (handler in this._decoder) { if (this._decoder.hasOwnProperty(handler)) { if (data.indexOf(handler) > -1) { // Found special indicator, do full parse return this._parse(jsonObject); } } } return jsonObject; } }; /** * 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; },{}],28:[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.662', modules: {}, plugins: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Tags":20,"./Mixin.Triggers":21,"./Mixin.Updating":22,"./Overload":24}],29:[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 = {}; },{}]},{},[1]);
var sliced = require('../') var assert = require('assert') describe('sliced', function(){ it('exports a function', function(){ assert.equal('function', typeof sliced); }) describe('with 1 arg', function(){ it('returns an array of the arg', function(){ var o = [3, "4", {}]; var r = sliced(o); assert.equal(3, r.length); assert.equal(o[0], r[0]); assert.equal(o[1], r[1]); assert.equal(o[1], r[1]); }) }) describe('with 2 args', function(){ it('returns an array of the arg starting at the 2nd arg', function(){ var o = [3, "4", 5, null]; var r = sliced(o, 2); assert.equal(2, r.length); assert.equal(o[2], r[0]); assert.equal(o[3], r[1]); }) }) describe('with 3 args', function(){ it('returns an array of the arg from the 2nd to the 3rd arg', function(){ var o = [3, "4", 5, null]; var r = sliced(o, 1, 2); assert.equal(1, r.length); assert.equal(o[1], r[0]); }) }) describe('with negative start and no end', function(){ it('begins at an offset from the end and includes all following elements', function(){ var o = [3, "4", 5, null]; var r = sliced(o, -2); assert.equal(2, r.length); assert.equal(o[2], r[0]); assert.equal(o[3], r[1]); var r = sliced(o, -12); assert.equal(4, r.length); assert.equal(o[0], r[0]); assert.equal(o[1], r[1]); }) }) describe('with negative start and positive end', function(){ it('begins at an offset from the end and includes `end` elements', function(){ var o = [3, "4", {x:1}, null]; var r = sliced(o, -2, 1); assert.equal(0, r.length); var r = sliced(o, -2, 2); assert.equal(0, r.length); var r = sliced(o, -2, 3); assert.equal(1, r.length); assert.equal(o[2], r[0]); }) }) describe('with negative start and negative end', function(){ it('begins at `start` offset from the end and includes all elements up to `end` offset from the end', function(){ var o = [3, "4", {x:1}, null]; var r = sliced(o, -3, -1); assert.equal(2, r.length); assert.equal(o[1], r[0]); assert.equal(o[2], r[1]); var r = sliced(o, -3, -3); assert.equal(0, r.length); var r = sliced(o, -3, -4); assert.equal(0, r.length); }) }) })
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ /* eslint no-bitwise: 0 */ 'use strict'; exports.__esModule = true; exports.default = void 0; var _AnimatedNode = _interopRequireDefault(require("./AnimatedNode")); var _AnimatedWithChildren2 = _interopRequireDefault(require("./AnimatedWithChildren")); var _NativeAnimatedHelper = _interopRequireDefault(require("../NativeAnimatedHelper")); var _invariant = _interopRequireDefault(require("fbjs/lib/invariant")); var _normalizeCssColor = _interopRequireDefault(require("normalize-css-color")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } 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; } var linear = function linear(t) { return t; }; /** * Very handy helper to map input ranges to output ranges with an easing * function and custom behavior outside of the ranges. */ function createInterpolation(config) { if (config.outputRange && typeof config.outputRange[0] === 'string') { return createInterpolationFromStringOutputRange(config); } var outputRange = config.outputRange; checkInfiniteRange('outputRange', outputRange); var inputRange = config.inputRange; checkInfiniteRange('inputRange', inputRange); checkValidInputRange(inputRange); (0, _invariant.default)(inputRange.length === outputRange.length, 'inputRange (' + inputRange.length + ') and outputRange (' + outputRange.length + ') must have the same length'); var easing = config.easing || linear; var extrapolateLeft = 'extend'; if (config.extrapolateLeft !== undefined) { extrapolateLeft = config.extrapolateLeft; } else if (config.extrapolate !== undefined) { extrapolateLeft = config.extrapolate; } var extrapolateRight = 'extend'; if (config.extrapolateRight !== undefined) { extrapolateRight = config.extrapolateRight; } else if (config.extrapolate !== undefined) { extrapolateRight = config.extrapolate; } return function (input) { (0, _invariant.default)(typeof input === 'number', 'Cannot interpolation an input which is not a number'); var range = findRange(input, inputRange); return interpolate(input, inputRange[range], inputRange[range + 1], outputRange[range], outputRange[range + 1], easing, extrapolateLeft, extrapolateRight); }; } function interpolate(input, inputMin, inputMax, outputMin, outputMax, easing, extrapolateLeft, extrapolateRight) { var result = input; // Extrapolate if (result < inputMin) { if (extrapolateLeft === 'identity') { return result; } else if (extrapolateLeft === 'clamp') { result = inputMin; } else if (extrapolateLeft === 'extend') {// noop } } if (result > inputMax) { if (extrapolateRight === 'identity') { return result; } else if (extrapolateRight === 'clamp') { result = inputMax; } else if (extrapolateRight === 'extend') {// noop } } if (outputMin === outputMax) { return outputMin; } if (inputMin === inputMax) { if (input <= inputMin) { return outputMin; } return outputMax; } // Input Range if (inputMin === -Infinity) { result = -result; } else if (inputMax === Infinity) { result = result - inputMin; } else { result = (result - inputMin) / (inputMax - inputMin); } // Easing result = easing(result); // Output Range if (outputMin === -Infinity) { result = -result; } else if (outputMax === Infinity) { result = result + outputMin; } else { result = result * (outputMax - outputMin) + outputMin; } return result; } function colorToRgba(input) { var int32Color = (0, _normalizeCssColor.default)(input); if (int32Color === null) { return input; } int32Color = int32Color || 0; var r = (int32Color & 0xff000000) >>> 24; var g = (int32Color & 0x00ff0000) >>> 16; var b = (int32Color & 0x0000ff00) >>> 8; var a = (int32Color & 0x000000ff) / 255; return "rgba(" + r + ", " + g + ", " + b + ", " + a + ")"; } var stringShapeRegex = /[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/g; /** * Supports string shapes by extracting numbers so new values can be computed, * and recombines those values into new strings of the same shape. Supports * things like: * * rgba(123, 42, 99, 0.36) // colors * -45deg // values with units */ function createInterpolationFromStringOutputRange(config) { var outputRange = config.outputRange; (0, _invariant.default)(outputRange.length >= 2, 'Bad output range'); outputRange = outputRange.map(colorToRgba); checkPattern(outputRange); // ['rgba(0, 100, 200, 0)', 'rgba(50, 150, 250, 0.5)'] // -> // [ // [0, 50], // [100, 150], // [200, 250], // [0, 0.5], // ] /* $FlowFixMe(>=0.18.0): `outputRange[0].match()` can return `null`. Need to * guard against this possibility. */ var outputRanges = outputRange[0].match(stringShapeRegex).map(function () { return []; }); outputRange.forEach(function (value) { /* $FlowFixMe(>=0.18.0): `value.match()` can return `null`. Need to guard * against this possibility. */ value.match(stringShapeRegex).forEach(function (number, i) { outputRanges[i].push(+number); }); }); /* $FlowFixMe(>=0.18.0): `outputRange[0].match()` can return `null`. Need to * guard against this possibility. */ var interpolations = outputRange[0].match(stringShapeRegex).map(function (value, i) { return createInterpolation(_objectSpread({}, config, { outputRange: outputRanges[i] })); }); // rgba requires that the r,g,b are integers.... so we want to round them, but we *dont* want to // round the opacity (4th column). var shouldRound = isRgbOrRgba(outputRange[0]); return function (input) { var i = 0; // 'rgba(0, 100, 200, 0)' // -> // 'rgba(${interpolations[0](input)}, ${interpolations[1](input)}, ...' return outputRange[0].replace(stringShapeRegex, function () { var val = +interpolations[i++](input); if (shouldRound) { val = i < 4 ? Math.round(val) : Math.round(val * 1000) / 1000; } return String(val); }); }; } function isRgbOrRgba(range) { return typeof range === 'string' && range.startsWith('rgb'); } function checkPattern(arr) { var pattern = arr[0].replace(stringShapeRegex, ''); for (var i = 1; i < arr.length; ++i) { (0, _invariant.default)(pattern === arr[i].replace(stringShapeRegex, ''), 'invalid pattern ' + arr[0] + ' and ' + arr[i]); } } function findRange(input, inputRange) { var i; for (i = 1; i < inputRange.length - 1; ++i) { if (inputRange[i] >= input) { break; } } return i - 1; } function checkValidInputRange(arr) { (0, _invariant.default)(arr.length >= 2, 'inputRange must have at least 2 elements'); for (var i = 1; i < arr.length; ++i) { (0, _invariant.default)(arr[i] >= arr[i - 1], /* $FlowFixMe(>=0.13.0) - In the addition expression below this comment, * one or both of the operands may be something that doesn't cleanly * convert to a string, like undefined, null, and object, etc. If you really * mean this implicit string conversion, you can do something like * String(myThing) */ 'inputRange must be monotonically non-decreasing ' + arr); } } function checkInfiniteRange(name, arr) { (0, _invariant.default)(arr.length >= 2, name + ' must have at least 2 elements'); (0, _invariant.default)(arr.length !== 2 || arr[0] !== -Infinity || arr[1] !== Infinity, /* $FlowFixMe(>=0.13.0) - In the addition expression below this comment, * one or both of the operands may be something that doesn't cleanly convert * to a string, like undefined, null, and object, etc. If you really mean * this implicit string conversion, you can do something like * String(myThing) */ name + 'cannot be ]-infinity;+infinity[ ' + arr); } var AnimatedInterpolation = /*#__PURE__*/ function (_AnimatedWithChildren) { _inheritsLoose(AnimatedInterpolation, _AnimatedWithChildren); // Export for testing. function AnimatedInterpolation(parent, config) { var _this; _this = _AnimatedWithChildren.call(this) || this; _this._parent = parent; _this._config = config; _this._interpolation = createInterpolation(config); return _this; } var _proto = AnimatedInterpolation.prototype; _proto.__makeNative = function __makeNative() { this._parent.__makeNative(); _AnimatedWithChildren.prototype.__makeNative.call(this); }; _proto.__getValue = function __getValue() { var parentValue = this._parent.__getValue(); (0, _invariant.default)(typeof parentValue === 'number', 'Cannot interpolate an input which is not a number.'); return this._interpolation(parentValue); }; _proto.interpolate = function interpolate(config) { return new AnimatedInterpolation(this, config); }; _proto.__attach = function __attach() { this._parent.__addChild(this); }; _proto.__detach = function __detach() { this._parent.__removeChild(this); _AnimatedWithChildren.prototype.__detach.call(this); }; _proto.__transformDataType = function __transformDataType(range) { // $FlowFixMe return range.map(_NativeAnimatedHelper.default.transformDataType); }; _proto.__getNativeConfig = function __getNativeConfig() { if (process.env.NODE_ENV !== 'production') { _NativeAnimatedHelper.default.validateInterpolation(this._config); } return { inputRange: this._config.inputRange, // Only the `outputRange` can contain strings so we don't need to transform `inputRange` here outputRange: this.__transformDataType(this._config.outputRange), extrapolateLeft: this._config.extrapolateLeft || this._config.extrapolate || 'extend', extrapolateRight: this._config.extrapolateRight || this._config.extrapolate || 'extend', type: 'interpolation' }; }; return AnimatedInterpolation; }(_AnimatedWithChildren2.default); AnimatedInterpolation.__createInterpolation = createInterpolation; var _default = AnimatedInterpolation; exports.default = _default; module.exports = exports.default;
function Gdn_Queue() { this.Queue = []; this.ActiveItem = false; Gdn_Queue.prototype.Add = function(QueueObject) { this.Queue.push(QueueObject); } Gdn_Queue.prototype.Length = function() { return this.Queue.length; } Gdn_Queue.prototype.Get = function() { if (!this.Length()) return false; return this.Queue.shift(); } } gdn.loaded('queue');
process.env.NODE_ENV = process.env.NODE_ENV || 'development' const { environment } = require('@rails/webpacker') module.exports = environment.toWebpackConfig()
'use strict'; var util = require('util'); function AbortError (obj) { Error.captureStackTrace(this, this.constructor); Object.defineProperty(this, 'message', { value: obj.message || '', configurable: true, writable: true }); for (var keys = Object.keys(obj), key = keys.pop(); key; key = keys.pop()) { this[key] = obj[key]; } } function AggregateError (obj) { Error.captureStackTrace(this, this.constructor); Object.defineProperty(this, 'message', { value: obj.message || '', configurable: true, writable: true }); for (var keys = Object.keys(obj), key = keys.pop(); key; key = keys.pop()) { this[key] = obj[key]; } } util.inherits(AbortError, Error); util.inherits(AggregateError, AbortError); Object.defineProperty(AbortError.prototype, 'name', { value: 'AbortError', // configurable: true, writable: true }); Object.defineProperty(AggregateError.prototype, 'name', { value: 'AggregateError', // configurable: true, writable: true }); module.exports = { AbortError: AbortError, AggregateError: AggregateError };
/* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the 2-clause BSD license. * See license.txt in the OpenLayers distribution or repository for the * full text of the license. */ /** * @requires OpenLayers/Geometry.js */ /** * Class: OpenLayers.Geometry.Collection * A Collection is exactly what it sounds like: A collection of different * Geometries. These are stored in the local parameter <components> (which * can be passed as a parameter to the constructor). * * As new geometries are added to the collection, they are NOT cloned. * When removing geometries, they need to be specified by reference (ie you * have to pass in the *exact* geometry to be removed). * * The <getArea> and <getLength> functions here merely iterate through * the components, summing their respective areas and lengths. * * Create a new instance with the <OpenLayers.Geometry.Collection> constructor. * * Inherits from: * - <OpenLayers.Geometry> */ OpenLayers.Geometry.Collection = OpenLayers.Class(OpenLayers.Geometry, { /** * APIProperty: components * {Array(<OpenLayers.Geometry>)} The component parts of this geometry */ components: null, /** * Property: componentTypes * {Array(String)} An array of class names representing the types of * components that the collection can include. A null value means the * component types are not restricted. */ componentTypes: null, /** * Constructor: OpenLayers.Geometry.Collection * Creates a Geometry Collection -- a list of geoms. * * Parameters: * components - {Array(<OpenLayers.Geometry>)} Optional array of geometries * */ initialize: function (components) { OpenLayers.Geometry.prototype.initialize.apply(this, arguments); this.components = []; if (components != null) { this.addComponents(components); } }, /** * APIMethod: destroy * Destroy this geometry. */ destroy: function () { this.components.length = 0; this.components = null; OpenLayers.Geometry.prototype.destroy.apply(this, arguments); }, /** * APIMethod: clone * Clone this geometry. * * Returns: * {<OpenLayers.Geometry.Collection>} An exact clone of this collection */ clone: function() { var Constructor = OpenLayers.Util.getConstructor(this.CLASS_NAME); var geometry = new Constructor(); for(var i=0, len=this.components.length; i<len; i++) { geometry.addComponent(this.components[i].clone()); } // catch any randomly tagged-on properties OpenLayers.Util.applyDefaults(geometry, this); return geometry; }, /** * Method: getComponentsString * Get a string representing the components for this collection * * Returns: * {String} A string representation of the components of this geometry */ getComponentsString: function(){ var strings = []; for(var i=0, len=this.components.length; i<len; i++) { strings.push(this.components[i].toShortString()); } return strings.join(","); }, /** * APIMethod: calculateBounds * Recalculate the bounds by iterating through the components and * calling calling extendBounds() on each item. */ calculateBounds: function() { this.bounds = null; var bounds = new OpenLayers.Bounds(); var components = this.components; if (components) { for (var i=0, len=components.length; i<len; i++) { bounds.extend(components[i].getBounds()); } } // to preserve old behavior, we only set bounds if non-null // in the future, we could add bounds.isEmpty() if (bounds.left != null && bounds.bottom != null && bounds.right != null && bounds.top != null) { this.setBounds(bounds); } }, /** * APIMethod: addComponents * Add components to this geometry. * * Parameters: * components - {Array(<OpenLayers.Geometry>)} An array of geometries to add */ addComponents: function(components){ if(!(OpenLayers.Util.isArray(components))) { components = [components]; } for(var i=0, len=components.length; i<len; i++) { this.addComponent(components[i]); } }, /** * Method: addComponent * Add a new component (geometry) to the collection. If this.componentTypes * is set, then the component class name must be in the componentTypes array. * * The bounds cache is reset. * * Parameters: * component - {<OpenLayers.Geometry>} A geometry to add * index - {int} Optional index into the array to insert the component * * Returns: * {Boolean} The component geometry was successfully added */ addComponent: function(component, index) { var added = false; if(component) { if(this.componentTypes == null || (OpenLayers.Util.indexOf(this.componentTypes, component.CLASS_NAME) > -1)) { if(index != null && (index < this.components.length)) { var components1 = this.components.slice(0, index); var components2 = this.components.slice(index, this.components.length); components1.push(component); this.components = components1.concat(components2); } else { this.components.push(component); } component.parent = this; this.clearBounds(); added = true; } } return added; }, /** * APIMethod: removeComponents * Remove components from this geometry. * * Parameters: * components - {Array(<OpenLayers.Geometry>)} The components to be removed * * Returns: * {Boolean} A component was removed. */ removeComponents: function(components) { var removed = false; if(!(OpenLayers.Util.isArray(components))) { components = [components]; } for(var i=components.length-1; i>=0; --i) { removed = this.removeComponent(components[i]) || removed; } return removed; }, /** * Method: removeComponent * Remove a component from this geometry. * * Parameters: * component - {<OpenLayers.Geometry>} * * Returns: * {Boolean} The component was removed. */ removeComponent: function(component) { OpenLayers.Util.removeItem(this.components, component); // clearBounds() so that it gets recalculated on the next call // to this.getBounds(); this.clearBounds(); return true; }, /** * APIMethod: getLength * Calculate the length of this geometry * * Returns: * {Float} The length of the geometry */ getLength: function() { var length = 0.0; for (var i=0, len=this.components.length; i<len; i++) { length += this.components[i].getLength(); } return length; }, /** * APIMethod: getArea * Calculate the area of this geometry. Note how this function is overridden * in <OpenLayers.Geometry.Polygon>. * * Returns: * {Float} The area of the collection by summing its parts */ getArea: function() { var area = 0.0; for (var i=0, len=this.components.length; i<len; i++) { area += this.components[i].getArea(); } return area; }, /** * APIMethod: getGeodesicArea * Calculate the approximate area of the polygon were it projected onto * the earth. * * Parameters: * projection - {<OpenLayers.Projection>} The spatial reference system * for the geometry coordinates. If not provided, Geographic/WGS84 is * assumed. * * Reference: * Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for * Polygons on a Sphere", JPL Publication 07-03, Jet Propulsion * Laboratory, Pasadena, CA, June 2007 http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409 * * Returns: * {float} The approximate geodesic area of the geometry in square meters. */ getGeodesicArea: function(projection) { var area = 0.0; for(var i=0, len=this.components.length; i<len; i++) { area += this.components[i].getGeodesicArea(projection); } return area; }, /** * APIMethod: getCentroid * * Compute the centroid for this geometry collection. * * Parameters: * weighted - {Boolean} Perform the getCentroid computation recursively, * returning an area weighted average of all geometries in this collection. * * Returns: * {<OpenLayers.Geometry.Point>} The centroid of the collection */ getCentroid: function(weighted) { if (!weighted) { return this.components.length && this.components[0].getCentroid(); } var len = this.components.length; if (!len) { return false; } var areas = []; var centroids = []; var areaSum = 0; var minArea = Number.MAX_VALUE; var component; for (var i=0; i<len; ++i) { component = this.components[i]; var area = component.getArea(); var centroid = component.getCentroid(true); if (isNaN(area) || isNaN(centroid.x) || isNaN(centroid.y)) { continue; } areas.push(area); areaSum += area; minArea = (area < minArea && area > 0) ? area : minArea; centroids.push(centroid); } len = areas.length; if (areaSum === 0) { // all the components in this collection have 0 area // probably a collection of points -- weight all the points the same for (var i=0; i<len; ++i) { areas[i] = 1; } areaSum = areas.length; } else { // normalize all the areas where the smallest area will get // a value of 1 for (var i=0; i<len; ++i) { areas[i] /= minArea; } areaSum /= minArea; } var xSum = 0, ySum = 0, centroid, area; for (var i=0; i<len; ++i) { centroid = centroids[i]; area = areas[i]; xSum += centroid.x * area; ySum += centroid.y * area; } return new OpenLayers.Geometry.Point(xSum/areaSum, ySum/areaSum); }, /** * APIMethod: getGeodesicLength * Calculate the approximate length of the geometry were it projected onto * the earth. * * projection - {<OpenLayers.Projection>} The spatial reference system * for the geometry coordinates. If not provided, Geographic/WGS84 is * assumed. * * Returns: * {Float} The appoximate geodesic length of the geometry in meters. */ getGeodesicLength: function(projection) { var length = 0.0; for(var i=0, len=this.components.length; i<len; i++) { length += this.components[i].getGeodesicLength(projection); } return length; }, /** * APIMethod: move * Moves a geometry by the given displacement along positive x and y axes. * This modifies the position of the geometry and clears the cached * bounds. * * Parameters: * x - {Float} Distance to move geometry in positive x direction. * y - {Float} Distance to move geometry in positive y direction. */ move: function(x, y) { for(var i=0, len=this.components.length; i<len; i++) { this.components[i].move(x, y); } }, /** * APIMethod: rotate * Rotate a geometry around some origin * * Parameters: * angle - {Float} Rotation angle in degrees (measured counterclockwise * from the positive x-axis) * origin - {<OpenLayers.Geometry.Point>} Center point for the rotation */ rotate: function(angle, origin) { for(var i=0, len=this.components.length; i<len; ++i) { this.components[i].rotate(angle, origin); } }, /** * APIMethod: resize * Resize a geometry relative to some origin. Use this method to apply * a uniform scaling to a geometry. * * Parameters: * scale - {Float} Factor by which to scale the geometry. A scale of 2 * doubles the size of the geometry in each dimension * (lines, for example, will be twice as long, and polygons * will have four times the area). * origin - {<OpenLayers.Geometry.Point>} Point of origin for resizing * ratio - {Float} Optional x:y ratio for resizing. Default ratio is 1. * * Returns: * {<OpenLayers.Geometry>} - The current geometry. */ resize: function(scale, origin, ratio) { for(var i=0; i<this.components.length; ++i) { this.components[i].resize(scale, origin, ratio); } return this; }, /** * APIMethod: distanceTo * Calculate the closest distance between two geometries (on the x-y plane). * * Parameters: * geometry - {<OpenLayers.Geometry>} The target geometry. * options - {Object} Optional properties for configuring the distance * calculation. * * Valid options: * details - {Boolean} Return details from the distance calculation. * Default is false. * edge - {Boolean} Calculate the distance from this geometry to the * nearest edge of the target geometry. Default is true. If true, * calling distanceTo from a geometry that is wholly contained within * the target will result in a non-zero distance. If false, whenever * geometries intersect, calling distanceTo will return 0. If false, * details cannot be returned. * * Returns: * {Number | Object} The distance between this geometry and the target. * If details is true, the return will be an object with distance, * x0, y0, x1, and y1 properties. The x0 and y0 properties represent * the coordinates of the closest point on this geometry. The x1 and y1 * properties represent the coordinates of the closest point on the * target geometry. */ distanceTo: function(geometry, options) { var edge = !(options && options.edge === false); var details = edge && options && options.details; var result, best, distance; var min = Number.POSITIVE_INFINITY; for(var i=0, len=this.components.length; i<len; ++i) { result = this.components[i].distanceTo(geometry, options); distance = details ? result.distance : result; if(distance < min) { min = distance; best = result; if(min == 0) { break; } } } return best; }, /** * APIMethod: equals * Determine whether another geometry is equivalent to this one. Geometries * are considered equivalent if all components have the same coordinates. * * Parameters: * geometry - {<OpenLayers.Geometry>} The geometry to test. * * Returns: * {Boolean} The supplied geometry is equivalent to this geometry. */ equals: function(geometry) { var equivalent = true; if(!geometry || !geometry.CLASS_NAME || (this.CLASS_NAME != geometry.CLASS_NAME)) { equivalent = false; } else if(!(OpenLayers.Util.isArray(geometry.components)) || (geometry.components.length != this.components.length)) { equivalent = false; } else { for(var i=0, len=this.components.length; i<len; ++i) { if(!this.components[i].equals(geometry.components[i])) { equivalent = false; break; } } } return equivalent; }, /** * APIMethod: transform * Reproject the components geometry from source to dest. * * Parameters: * source - {<OpenLayers.Projection>} * dest - {<OpenLayers.Projection>} * * Returns: * {<OpenLayers.Geometry>} */ transform: function(source, dest) { if (source && dest) { for (var i=0, len=this.components.length; i<len; i++) { var component = this.components[i]; component.transform(source, dest); } this.bounds = null; } return this; }, /** * APIMethod: intersects * Determine if the input geometry intersects this one. * * Parameters: * geometry - {<OpenLayers.Geometry>} Any type of geometry. * * Returns: * {Boolean} The input geometry intersects this one. */ intersects: function(geometry) { var intersect = false; for(var i=0, len=this.components.length; i<len; ++ i) { intersect = geometry.intersects(this.components[i]); if(intersect) { break; } } return intersect; }, /** * APIMethod: getVertices * Return a list of all points in this geometry. * * Parameters: * nodes - {Boolean} For lines, only return vertices that are * endpoints. If false, for lines, only vertices that are not * endpoints will be returned. If not provided, all vertices will * be returned. * * Returns: * {Array} A list of all vertices in the geometry. */ getVertices: function(nodes) { var vertices = []; for(var i=0, len=this.components.length; i<len; ++i) { Array.prototype.push.apply( vertices, this.components[i].getVertices(nodes) ); } return vertices; }, CLASS_NAME: "OpenLayers.Geometry.Collection" });
/** * API Bound Models for AngularJS * @version v0.18.0 - 2014-08-26 * @link https://github.com/angular-platanus/restmod * @author Ignacio Baixas <ignacio@platan.us> * @license MIT License, http://www.opensource.org/licenses/MIT */ !function(a,b){"use strict";a.module("restmod").factory("PagedModel",["restmod",function(a){return a.mixin({"@$pageHeader":"X-Page","@$pageCountHeader":"X-Page-Total","~afterFetchMany":function(a){var c=a.headers(this.$pageHeader),d=a.headers(this.$pageCountHeader);this.$page=c!==b?parseInt(c,10):1,this.$pageCount=d!==b?parseInt(d,10):1}})}])}(angular);
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": "a.m.", "1": "p.m." }, "DAY": { "0": "domingo", "1": "lunes", "2": "martes", "3": "mi\u00e9rcoles", "4": "jueves", "5": "viernes", "6": "s\u00e1bado" }, "MONTH": { "0": "enero", "1": "febrero", "2": "marzo", "3": "abril", "4": "mayo", "5": "junio", "6": "julio", "7": "agosto", "8": "septiembre", "9": "octubre", "10": "noviembre", "11": "diciembre" }, "SHORTDAY": { "0": "dom", "1": "lun", "2": "mar", "3": "mi\u00e9", "4": "jue", "5": "vie", "6": "s\u00e1b" }, "SHORTMONTH": { "0": "ene", "1": "feb", "2": "mar", "3": "abr", "4": "may", "5": "jun", "6": "jul", "7": "ago", "8": "sep", "9": "oct", "10": "nov", "11": "dic" }, "fullDate": "EEEE, d 'de' MMMM 'de' y", "longDate": "d 'de' MMMM 'de' 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": "es-sv", "pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.shave = factory()); }(this, (function () { 'use strict'; function shave(target, maxHeight, opts) { if (!maxHeight) throw Error('maxHeight is required'); var els = typeof target === 'string' ? document.querySelectorAll(target) : target; if (!('length' in els)) els = [els]; var defaults = { character: '…', classname: 'js-shave', spaces: true }; var character = opts && opts.character || defaults.character; var classname = opts && opts.classname || defaults.classname; var spaces = opts && opts.spaces === false ? false : defaults.spaces; var charHtml = '<span class="js-shave-char">' + character + '</span>'; for (var i = 0; i < els.length; i++) { var el = els[i]; var span = el.querySelector('.' + classname); // If element text has already been shaved if (span) { // Remove the ellipsis to recapture the original text el.removeChild(el.querySelector('.js-shave-char')); el.textContent = el.textContent; // nuke span, recombine text } // If already short enough, we're done if (el.offsetHeight < maxHeight) continue; var fullText = el.textContent; var words = spaces ? fullText.split(' ') : fullText; // If 0 or 1 words, we're done if (words.length < 2) continue; // Binary search for number of words which can fit in allotted height var max = words.length - 1; var min = 0; var pivot = void 0; while (min < max) { pivot = min + max + 1 >> 1; el.textContent = spaces ? words.slice(0, pivot).join(' ') : words.slice(0, pivot); el.insertAdjacentHTML('beforeend', charHtml); if (el.offsetHeight > maxHeight) max = spaces ? pivot - 1 : pivot - 2;else min = pivot; } el.textContent = spaces ? words.slice(0, max).join(' ') : words.slice(0, max); el.insertAdjacentHTML('beforeend', charHtml); var diff = spaces ? words.slice(max + 1).join(' ') : words.slice(max); el.insertAdjacentHTML('beforeend', '<span class="' + classname + '" style="display:none;">' + diff + '</span>'); } } var plugin = window.$ || window.jQuery || window.Zepto; if (plugin) { plugin.fn.extend({ shave: function shaveFunc(maxHeight, opts) { return shave(this, maxHeight, opts); } }); } return shave; })));
export default function() { var callback = arguments[0]; arguments[0] = this; callback.apply(null, arguments); return this; }
'use strict'; 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": [ "AM", "PM" ], "DAY": [ "\u0627\u062a\u0648\u0627\u0631", "\u067e\u06cc\u0631", "\u0645\u0646\u06af\u0644", "\u0628\u064f\u062f\u06be", "\u062c\u0645\u0639\u0631\u0627\u062a", "\u062c\u0645\u0639\u06c1", "\u06c1\u0641\u062a\u06c1" ], "MONTH": [ "\u062c\u0646\u0648\u0631\u06cc", "\u0641\u0631\u0648\u0631\u06cc", "\u0645\u0627\u0631\u0686", "\u0627\u067e\u0631\u06cc\u0644", "\u0645\u0626", "\u062c\u0648\u0646", "\u062c\u0648\u0644\u0627\u0626\u06cc", "\u0627\u06af\u0633\u062a", "\u0633\u062a\u0645\u0628\u0631", "\u0627\u06a9\u062a\u0648\u0628\u0631", "\u0646\u0648\u0645\u0628\u0631", "\u062f\u0633\u0645\u0628\u0631" ], "SHORTDAY": [ "\u0a10\u0a24.", "\u0a38\u0a4b\u0a2e.", "\u0a2e\u0a70\u0a17\u0a32.", "\u0a2c\u0a41\u0a27.", "\u0a35\u0a40\u0a30.", "\u0a38\u0a3c\u0a41\u0a71\u0a15\u0a30.", "\u0a38\u0a3c\u0a28\u0a40." ], "SHORTMONTH": [ "\u0a1c\u0a28\u0a35\u0a30\u0a40", "\u0a2b\u0a3c\u0a30\u0a35\u0a30\u0a40", "\u0a2e\u0a3e\u0a30\u0a1a", "\u0a05\u0a2a\u0a4d\u0a30\u0a48\u0a32", "\u0a2e\u0a08", "\u0a1c\u0a42\u0a28", "\u0a1c\u0a41\u0a32\u0a3e\u0a08", "\u0a05\u0a17\u0a38\u0a24", "\u0a38\u0a24\u0a70\u0a2c\u0a30", "\u0a05\u0a15\u0a24\u0a42\u0a2c\u0a30", "\u0a28\u0a35\u0a70\u0a2c\u0a30", "\u0a26\u0a38\u0a70\u0a2c\u0a30" ], "fullDate": "EEEE, dd MMMM y", "longDate": "d MMMM y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "dd/MM/y h:mm a", "shortDate": "dd/MM/y", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u20b9", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 2, "lgSize": 3, "macFrac": 0, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 2, "lgSize": 3, "macFrac": 0, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4-", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "pa-arab", "pluralCat": function (n, opt_precision) { if (n >= 0 && n <= 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
var _filter = require('./_filter'); /** * @private * @param {Function} fn The strategy for extracting function names from an object * @return {Function} A function that takes an object and returns an array of function names. */ module.exports = function _functionsWith(fn) { return function(obj) { return _filter(function(key) { return typeof obj[key] === 'function'; }, fn(obj)); }; };
// SpryUtils.js - version 0.2 - Spry Pre-Release 1.6 // // Copyright (c) 2007. Adobe Systems Incorporated. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Adobe Systems Incorporated nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. var Spry; if (!Spry) Spry = {}; if (!Spry.Utils) Spry.Utils = {}; Spry.Utils.submitForm = function(form, callback, opts) { if (!form) return true; if ( typeof form == 'string' ) form = document.getElementById(form) || document.forms[form]; var frmOpts = {}; frmOpts.method = form.method; frmOpts.url = form.action || document.location.href; frmOpts.enctype = form.enctype; Spry.Utils.setOptions(frmOpts, opts); var submitData = Spry.Utils.extractParamsFromForm(form, frmOpts.elements); if (frmOpts.additionalData) submitData += "&" + frmOpts.additionalData; if (frmOpts.enctype.toLowerCase() != 'multipart/form-data') { // Ajax submission of a form doesn't work for multipart/form-data! frmOpts.method = (frmOpts.method.toLowerCase() == "post") ? 'POST' : 'GET'; if (frmOpts.method == "GET") { // Data will be submitted in the url. if (frmOpts.url.indexOf('?') == -1) frmOpts.url += '?'; else frmOpts.url += '&'; frmOpts.url += submitData; } else { // Send Content-Type header. if (!frmOpts.headers) frmOpts.headers = {}; if (!frmOpts.headers['Content-Type'] || frmOpts.headers['Content-Type'].indexOf("application/x-www-form-urlencoded") ==-1 ) frmOpts.headers['Content-Type'] = 'application/x-www-form-urlencoded'; // Set the postData frmOpts.postData = submitData; } Spry.Utils.loadURL(frmOpts.method, frmOpts.url, true, callback, frmOpts); return false; } // Native submission when 'multipart/form-data' is used. return true; }; Spry.Utils.extractParamsFromForm = function (form, elements) { if (!form) return ''; if ( typeof form == 'string' ) form = document.getElementById(form) || document.forms[form]; var formElements; if (elements) formElements = ',' + elements.join(',') + ','; var compStack = new Array(); // key=value pairs var el; for (var i = 0; i < form.elements.length; i++ ) { el = form.elements[i]; if (el.disabled || !el.name) { // Don't submit disabled elements. // Don't submit elements without name. continue; } if (!el.type) { // It seems that this element doesn't have a type set, // so skip it. continue; } if (formElements && formElements.indexOf(',' + el.name + ',')==-1) continue; switch(el.type.toLowerCase()) { case 'text': case 'password': case 'textarea': case 'hidden': case 'submit': compStack.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value)); break; case 'select-one': var value = ''; var opt; if (el.selectedIndex >= 0) { opt = el.options[el.selectedIndex]; value = opt.value || opt.text; } compStack.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(value)); break; case 'select-multiple': for (var j = 0; j < el.length; j++) { if (el.options[j].selected) { value = el.options[j].value || el.options[j].text; compStack.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(value)); } } break; case 'checkbox': case 'radio': if (el.checked) compStack.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value)); break; default: // file, button, reset break; } } return compStack.join('&'); };
export{default}from"./FormHelperText";
"use strict"; exports.__esModule = true; // istanbul ignore next function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } } // istanbul ignore next function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _helpersBuildComprehension = require("../../helpers/build-comprehension"); var _helpersBuildComprehension2 = _interopRequireDefault(_helpersBuildComprehension); var _traversal = require("../../../traversal"); var _traversal2 = _interopRequireDefault(_traversal); var _util = require("../../../util"); var util = _interopRequireWildcard(_util); var _types = require("../../../types"); var t = _interopRequireWildcard(_types); var metadata = { stage: 0 }; exports.metadata = metadata; /** * [Please add a description.] */ var visitor = { /** * [Please add a description.] */ ComprehensionExpression: function ComprehensionExpression(node, parent, scope) { var callback = array; if (node.generator) callback = generator; return callback(node, parent, scope); } }; exports.visitor = visitor; /** * [Please add a description.] */ function generator(node) { var body = []; var container = t.functionExpression(null, [], t.blockStatement(body), true); container.shadow = true; body.push(_helpersBuildComprehension2["default"](node, function () { return t.expressionStatement(t.yieldExpression(node.body)); })); return t.callExpression(container, []); } /** * [Please add a description.] */ function array(node, parent, scope) { var uid = scope.generateUidIdentifierBasedOnNode(parent); var container = util.template("array-comprehension-container", { KEY: uid }); container.callee.shadow = true; var block = container.callee.body; var body = block.body; if (_traversal2["default"].hasType(node, scope, "YieldExpression", t.FUNCTION_TYPES)) { container.callee.generator = true; container = t.yieldExpression(container, true); } var returnStatement = body.pop(); body.push(_helpersBuildComprehension2["default"](node, function () { return util.template("array-push", { STATEMENT: node.body, KEY: uid }, true); })); body.push(returnStatement); return container; }
export{default}from"./Snackbar";
/*! * inferno-server vundefined * (c) 2016 Dominic Gannaway * Released under the MPL-2.0 License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.InfernoServer = factory()); }(this, function () { 'use strict'; var babelHelpers_typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; function createStaticNode(html) { return { create: function create() { return html; } }; } var isArray = (function (x) { return x.constructor === Array; }) var isStringOrNumber = (function (x) { return typeof x === 'string' || typeof x === 'number'; }) var noop = (function () {}) var canUseDOM = !!(typeof window !== 'undefined' && // Nwjs doesn't add document as a global in their node context, but does have it on window.document, // As a workaround, check if document is undefined typeof document !== 'undefined' && window.document.createElement); var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!window.addEventListener, canUseViewport: canUseDOM && !!window.screen, canUseSymbol: typeof Symbol === 'function' && typeof Symbol['for'] === 'function' }; var HOOK = {}; var reDash = /\-./g; /* eslint-disable quote-props */ var unitlessProperties = { 'animation-iteration-count': true, 'box-flex': true, 'box-flex-group': true, 'column-count': true, 'counter-increment': true, 'fill-opacity': true, 'flex': true, 'flex-grow': true, 'flex-order': true, 'flex-positive': true, 'flex-shrink': true, 'float': true, 'font-weight': true, 'grid-column': true, 'line-height': true, 'line-clamp': true, 'opacity': true, 'order': true, 'orphans': true, 'stop-opacity': true, 'stroke-dashoffset': true, 'stroke-opacity': true, 'stroke-width': true, 'tab-size': true, 'transform': true, 'transform-origin': true, 'widows': true, 'z-index': true, 'zoom': true }; /* eslint-enable quote-props */ var directions = ['Top', 'Right', 'Bottom', 'Left']; var dirMap = function dirMap(prefix, postfix) { return directions.map(function (dir) { return (prefix || '') + dir + (postfix || ''); }); }; var shortCuts = { // rely on cssText font: [/* font-style font-variant font-weight font-size/line-height font-family|caption|icon|menu|message-box|small-caption|status-bar|initial|inherit; */], padding: dirMap('padding'), margin: dirMap('margin'), 'border-width': dirMap('border', 'Width'), 'border-style': dirMap('border', 'Style') }; var cssToJSName = function cssToJSName(cssName) { return cssName.replace(reDash, function (str) { return str[1].toUpperCase(); }); }; // Don't execute this in nodejS if (ExecutionEnvironment.canUseDOM) { (function () { // get browser supported CSS properties var documentElement = document.documentElement; var computed = window.getComputedStyle(documentElement); var props = Array.prototype.slice.call(computed, 0); for (var key in documentElement.style) { if (!computed[key]) { props.push(key); } } props.forEach(function (propName) { var prefix = propName[0] === '-' ? propName.substr(1, propName.indexOf('-', 1) - 1) : null; var stylePropName = cssToJSName(propName); HOOK[stylePropName] = { unPrefixed: prefix ? propName.substr(prefix.length + 2) : propName, unitless: unitlessProperties[propName] ? true : false, shorthand: null }; }); var lenMap = { 1: function _(values, props, style) { return props.forEach(function (prop) { return style[prop] = values[0]; }); }, 2: function _(values, props, style) { return values.forEach(function (value, index) { style[props[index]] = style[props[index + 2]] = value; }); }, 4: function _(values, props, style) { return props.forEach(function (prop, index) { style[prop] = values[index]; }); } }; // normalize property shortcuts Object.keys(shortCuts).forEach(function (propName) { var stylePropName = cssToJSName(propName); HOOK[stylePropName] = { unPrefixed: propName, unitless: false, shorthand: function shorthand(value, style) { var type = typeof value === 'undefined' ? 'undefined' : babelHelpers_typeof(value); if (type === 'number') { value += 'px'; } if (!value) { return; } if ('cssText' in style) { // normalize setting complex property across browsers style.cssText += ';' + propName + ':' + value; } else { var values = value.split(' '); (lenMap[values.length] || noop)(values, shortCuts[propName], style); } } }; }); })(); } /** * DOM registry * */ var PROPERTY = 0x1; var BOOLEAN = 0x2; var NUMERIC_VALUE = 0x4; var POSITIVE_NUMERIC_VALUE = 0x6 | 0x4; var xlink = 'http://www.w3.org/1999/xlink'; var xml = 'http://www.w3.org/XML/1998/namespace'; var DOMAttributeNamespaces = { // None-JSX compat 'xlink:actuate': xlink, 'xlink:arcrole': xlink, 'xlink:href': xlink, 'xlink:role': xlink, 'xlink:show': xlink, 'xlink:title': xlink, 'xlink:type': xlink, 'xml:base': xml, 'xml:lang': xml, 'xml:space': xml, // JSX compat xlinkActuate: xlink, xlinkArcrole: xlink, xlinkHref: xlink, xlinkRole: xlink, xlinkShow: xlink, xlinkTitle: xlink, xlinkType: xlink }; var DOMAttributeNames = { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv', // SVG clipPath: 'clip-path', fillOpacity: 'fill-opacity', fontFamily: 'font-family', fontSize: 'font-size', markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strokeDasharray: 'stroke-dasharray', strokeLinecap: 'stroke-linecap', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', textAnchor: 'text-anchor', viewBox: 'viewBox', // Edge case. The letter 'b' need to be uppercase // JSX compat xlinkActuate: 'xlink:actuate', xlinkArcrole: 'xlink:arcrole', xlinkHref: 'xlink:href', xlinkRole: 'xlink:role', xlinkShow: 'xlink:show', xlinkTitle: 'xlink:title', xlinkType: 'xlink:type', xmlBase: 'xml:base', xmlLang: 'xml:lang', xmlSpace: 'xml:space' }; var DOMPropertyNames = { autoComplete: 'autocomplete', autoFocus: 'autofocus', autoSave: 'autosave' }; // This 'whitelist' contains edge cases such as attributes // that should be seen as a property or boolean property. // ONLY EDIT THIS IF YOU KNOW WHAT YOU ARE DOING!! var Whitelist = { allowFullScreen: BOOLEAN, async: BOOLEAN, autoFocus: BOOLEAN, autoPlay: BOOLEAN, capture: BOOLEAN, checked: PROPERTY | BOOLEAN, controls: BOOLEAN, currentTime: PROPERTY | POSITIVE_NUMERIC_VALUE, default: BOOLEAN, defaultChecked: BOOLEAN, defaultMuted: BOOLEAN, defaultSelected: BOOLEAN, defer: BOOLEAN, disabled: PROPERTY | BOOLEAN, download: BOOLEAN, enabled: BOOLEAN, formNoValidate: BOOLEAN, hidden: PROPERTY | BOOLEAN, // 3.2.5 - Global attributes loop: BOOLEAN, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: PROPERTY | BOOLEAN, muted: PROPERTY | BOOLEAN, mediaGroup: PROPERTY, noValidate: BOOLEAN, noShade: PROPERTY | BOOLEAN, noResize: BOOLEAN, noWrap: BOOLEAN, typeMustMatch: BOOLEAN, open: BOOLEAN, paused: PROPERTY, playbackRate: PROPERTY | NUMERIC_VALUE, readOnly: BOOLEAN, required: PROPERTY | BOOLEAN, reversed: BOOLEAN, radioGroup: PROPERTY, icon: PROPERTY, draggable: BOOLEAN, // 3.2.5 - Global attributes dropzone: null, // 3.2.5 - Global attributes scoped: PROPERTY | BOOLEAN, visible: BOOLEAN, trueSpeed: BOOLEAN, sandbox: null, sortable: BOOLEAN, inert: BOOLEAN, indeterminate: BOOLEAN, nohref: BOOLEAN, compact: BOOLEAN, declare: BOOLEAN, ismap: PROPERTY | BOOLEAN, pauseOnExit: PROPERTY | BOOLEAN, seamless: BOOLEAN, translate: BOOLEAN, // 3.2.5 - Global attributes selected: PROPERTY | BOOLEAN, srcLang: PROPERTY, srcObject: PROPERTY, value: PROPERTY, volume: PROPERTY | POSITIVE_NUMERIC_VALUE, itemScope: BOOLEAN, // 3.2.5 - Global attributes className: null, tabindex: PROPERTY | NUMERIC_VALUE, /** * React compat for non-working JSX namespace support */ xlinkActuate: null, xlinkArcrole: null, xlinkHref: null, xlinkRole: null, xlinkShow: null, xlinkTitle: null, xlinkType: null, xmlBase: null, xmlLang: null, xmlSpace: null, /** * SVG */ clipPath: null, fillOpacity: null, fontFamily: null, fontSize: null, markerEnd: null, markerMid: null, markerStart: null, stopColor: null, stopOpacity: null, strokeDasharray: null, strokeLinecap: null, strokeOpacity: null, strokeWidth: null, textAnchor: null, /** * Numeric attributes */ cols: POSITIVE_NUMERIC_VALUE, rows: NUMERIC_VALUE, rowspan: NUMERIC_VALUE, size: POSITIVE_NUMERIC_VALUE, sizes: NUMERIC_VALUE, start: NUMERIC_VALUE, /** * Namespace attributes */ 'xlink:actuate': null, 'xlink:arcrole': null, 'xlink:href': null, 'xlink:role': null, 'xlink:show': null, 'xlink:title': null, 'xlink:type': null, 'xml:base': null, 'xml:lang': null, 'xml:space': null, /** * 3.2.5 - Global attributes */ id: null, dir: null, title: null, /** * Properties that MUST be set as attributes, due to: * * - browser bug * - strange spec outlier * * Nothing bad with this. This properties get a performance boost * compared to custom attributes because they are skipping the * validation check. */ // Force 'autocorrect' and 'autoCapitalize' to be set as an attribute // to fix issues with Mobile Safari on iOS devices autocorrect: null, // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: null, // Some version of IE ( like IE9 ) actually throw an exception // if you set input.type = 'something-unknown' type: null, /** * Form */ form: null, formAction: null, formEncType: null, formMethod: null, formTarget: null, frameBorder: null, /** * Internet Explorer / Edge */ // IE-only attribute that controls focus behavior unselectable: null, /** * Firefox */ continuous: BOOLEAN, /** * Others */ srcSet: null, inlist: null, minLength: null, marginWidth: null, marginHeight: null, list: null, keyType: null, is: null, inputMode: null, height: null, width: null, dateTime: null, contenteditable: null, // 3.2.5 - Global attributes contextMenu: null, classID: null, cellPadding: null, cellSpacing: null, charSet: null, allowTransparency: null, spellcheck: null, // 3.2.5 - Global attributes srcDoc: PROPERTY }; var HTMLPropsContainer = {}; function checkBitmask(value, bitmask) { return bitmask !== null && (value & bitmask) === bitmask; } for (var propName in Whitelist) { var propConfig = Whitelist[propName]; HTMLPropsContainer[propName] = { attributeName: DOMAttributeNames[propName] || propName.toLowerCase(), attributeNamespace: DOMAttributeNamespaces[propName] ? DOMAttributeNamespaces[propName] : null, propertyName: DOMPropertyNames[propName] || propName, mustUseProperty: checkBitmask(propConfig, PROPERTY), hasBooleanValue: checkBitmask(propConfig, BOOLEAN), hasNumericValue: checkBitmask(propConfig, NUMERIC_VALUE), hasPositiveNumericValue: checkBitmask(propConfig, POSITIVE_NUMERIC_VALUE) }; } var isVoid = (function (x) { return x === null || x === undefined; }) /* eslint eqeqeq:0 */ function isValidAttribute(strings) { var i = 0; var character = undefined; while (i <= strings.length) { character = strings[i]; if (!isNaN(character * 1)) { return false; } else { if (character == character.toUpperCase()) { return false; } if (character === character.toLowerCase()) { return true; } } i++; } return false; } var ESCAPE_LOOKUP = { '&': '&amp;', '>': '&gt;', '<': '&lt;', '"': '&quot;', '`': '&#x60;', "'": '&#x27;' }; var ESCAPE_REGEX = /[&><"'`]/g; /** * Escapes attribute value to prevent scripting attacks. * * @param {*} value Attribute value to escape. * @return {string} An escaped string. */ var quoteAttributeValueForBrowser = (function (value) { return '"' + ('' + value).replace(ESCAPE_REGEX, function (match) { return ESCAPE_LOOKUP[match]; }) + '"'; }) var selfClosingTags = { area: true, base: true, basefont: true, br: true, col: true, command: true, embed: true, frame: true, hr: true, img: true, input: true, isindex: true, keygen: true, link: true, meta: true, param: true, source: true, track: true, wbr: true, //common self closing svg elements path: true, circle: true, ellipse: true, line: true, rect: true, use: true, stop: true, polyline: true, polygon: true }; function renderMarkupForSelect(node) { var value = node.attrs && node.attrs.value; if (!isVoid(value)) { var values = {}; if (isArray(value)) { for (var i = 0, len = value.length; i < len; i++) { values[value[i]] = value[i]; } } else { values[value] = value; } populateOptions(node, values); if (node.attrs && node.attrs.value) { delete node.attrs.value; } } } /** * Populates values to options node. * * @param Object node A starting node (generaly a select node). * @param Object values The selected values to populate. */ function populateOptions(node, values) { if (node.tag !== 'option') { for (var i = 0, len = node.children.length; i < len; i++) { populateOptions(node.children[i], values); } return; } var value = node.attrs && node.attrs.value; if (!values[value]) { return; } node.attrs = node.attrs || {}; node.attrs.selected = "selected"; } /** * WORK IN PROGRESS * * Need to run tests for this one!! * * */ function renderMarkupForStyles(styles, component) { var serialized = ''; for (var styleName in styles) { if (isValidAttribute(styleName)) { var styleValue = styles[styleName]; if (!isVoid(styleValue)) { if (!unitlessProperties[styleName]) { if (typeof styleValue !== 'string') { styleValue = styleValue + 'px'; } } serialized += styleName + ':'; serialized += styleValue + ';'; } } } return serialized || null; } function renderMarkupForAttributes(name, value) { if (name === 'data-inferno') { return '' + name; } var propertyInfo = HTMLPropsContainer[name] || null; if (propertyInfo) { if (isVoid(value) || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && value !== value || propertyInfo.hasPositiveNumericValue && value < 1 || value === 'false' || value.length === 0) { return ''; } var attributeName = propertyInfo.attributeName; return attributeName + '=' + quoteAttributeValueForBrowser(value); } else { if (isVoid(value) || !isValidAttribute(name)) { return ''; } // custom attributes return (DOMAttributeNames[name] || name.toLowerCase()) + '=' + quoteAttributeValueForBrowser(value); } } function createStaticAttributes(props, excludeAttrs) { var HTML = ''; for (var propKey in props) { var propValue = props[propKey]; if (!isVoid(propValue)) { if (propKey === 'style') { propValue = renderMarkupForStyles(propValue); } var markup = null; markup = renderMarkupForAttributes(propKey, propValue); if (markup) { HTML += ' ' + markup; } } } return HTML; } function createStaticTreeChildren(children) { var isLastChildNode = false; if (isArray(children)) { return children.map(function (child, i) { if (isStringOrNumber(child)) { if (isLastChildNode) { isLastChildNode = true; return '<!---->' + child; } else { isLastChildNode = true; return child; } } isLastChildNode = false; return createStaticTreeNode(false, child); }).join(''); } else { if (isStringOrNumber(children)) { return children; } else { return createStaticTreeNode(false, children); } } } function createStaticTreeNode(isRoot, node) { var staticNode = undefined; if (isVoid(node)) { return ''; } if (node.tag) { var tag = node.tag.toLowerCase(); var attrs = node.attrs; var attributes = {}; for (var key in node.attrs) { if (key === 'value') { if (tag === 'select') { renderMarkupForSelect(node); continue; } else if (tag === 'textarea' || attrs.contenteditable) { node.text = attrs[key]; continue; } } attributes[key] = attrs[key]; } if (isRoot) { attributes['data-inferno'] = true; } staticNode = '<' + tag; // In React they can add innerHTML like this, just workaround it if (attributes.innerHTML) { node.text = attributes.innerHTML; } else { staticNode += createStaticAttributes(attributes, null); } if (selfClosingTags[tag]) { staticNode += ' />'; } else { staticNode += '>'; if (!isVoid(node.children)) { staticNode += createStaticTreeChildren(node.children); } else if (!isVoid(node.text)) { staticNode += node.text; } staticNode += '</' + tag + '>'; } } return staticNode; } function createHTMLTree(schema, isRoot, dynamicNodeMap) { var dynamicFlags = dynamicNodeMap.get(schema); var node = undefined; // static html if (!dynamicFlags) { return createStaticNode(createStaticTreeNode(isRoot, schema)); } return node; } function renderToString(item) { return item.tree.html.create(item); } var global = global || (typeof window !== 'undefined' ? window : null); // browser if (global && global.Inferno) { global.Inferno.addTreeConstructor('html', createHTMLTree); // nodeJS // TODO! Find a better way to detect if we are running in Node, and test if this actually works!!! } else if (global && !global.Inferno) { var Inferno = undefined; // TODO! Avoid try / catch try { Inferno = require('inferno'); } catch (e) { Inferno = null; // TODO Should we throw a warning and inform that the Inferno package is not installed? } if (Inferno != null) { if (typeof Inferno.addTreeConstructor !== 'function') { throw 'Your package is out-of-date! Upgrade to latest Inferno in order to use the InfernoServer package.'; } else { Inferno.addTreeConstructor('html', createHTMLTree); } } } var index = { renderToString: renderToString }; return index; })); //# sourceMappingURL=inferno-server.js.map
jQuery.keyboard.language.he={language:"עברית (Hebrew)",display:{a:"✔:אישור (Shift+Enter)",accept:"אישור:אישור (Shift+Enter)",alt:"Alt:תווים נוספים",b:"←:Backspace",bksp:"Bksp:Backspace",c:"✖:ביטול (Esc)",cancel:"ביטול:ביטול (Esc)",clear:"C:ניקוי",combo:"ö:Toggle Combo Keys",dec:".:נקודה עשרונית",e:"↵:Enter",enter:"Enter:Enter",lock:"⇪ Lock:Caps Lock",s:"⇧:Shift",shift:"Shift:Shift",sign:"±:שינוי סימן",space:"&nbsp;:רווח",t:"⇥:Tab",tab:"⇥ Tab:Tab"},wheelMessage:"ניתן להשתמש בגלגלת העכבר כדי לראות מקשים נוספים",rtl:!0};
// Copyright 2009-2012 by contributors, MIT License // vim: ts=4 sts=4 sw=4 expandtab (function () { setTimeout(function(){ webshims.isReady('es5', true); }); /** * Brings an environment as close to ECMAScript 5 compliance * as is possible with the facilities of erstwhile engines. * * Annotated ES5: http://es5.github.com/ (specific links below) * ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf * Required reading: http://javascriptweblog.wordpress.com/2011/12/05/extending-javascript-natives/ */ // Shortcut to an often accessed properties, in order to avoid multiple // dereference that costs universally. var call = Function.prototype.call; var prototypeOfArray = Array.prototype; var prototypeOfObject = Object.prototype; var _Array_slice_ = prototypeOfArray.slice; var array_splice = Array.prototype.splice; var array_push = Array.prototype.push; var array_unshift = Array.prototype.unshift; // Having a toString local variable name breaks in Opera so use _toString. var _toString = prototypeOfObject.toString; var isFunction = function (val) { return prototypeOfObject.toString.call(val) === '[object Function]'; }; var isRegex = function (val) { return prototypeOfObject.toString.call(val) === '[object RegExp]'; }; var isArray = function isArray(obj) { return _toString.call(obj) === "[object Array]"; }; var isArguments = function isArguments(value) { var str = _toString.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = !isArray(str) && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && isFunction(value.callee); } return isArgs; }; // // Function // ======== // // ES-5 15.3.4.5 // http://es5.github.com/#x15.3.4.5 function Empty() {} if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 // 1. Let Target be the this value. var target = this; // 2. If IsCallable(Target) is false, throw a TypeError exception. if (!isFunction(target)) { throw new TypeError("Function.prototype.bind called on incompatible " + target); } // 3. Let A be a new (possibly empty) internal list of all of the // argument values provided after thisArg (arg1, arg2 etc), in order. // XXX slicedArgs will stand in for "A" if used var args = _Array_slice_.call(arguments, 1); // for normal call // 4. Let F be a new native ECMAScript object. // 11. Set the [[Prototype]] internal property of F to the standard // built-in Function prototype object as specified in 15.3.3.1. // 12. Set the [[Call]] internal property of F as described in // 15.3.4.5.1. // 13. Set the [[Construct]] internal property of F as described in // 15.3.4.5.2. // 14. Set the [[HasInstance]] internal property of F as described in // 15.3.4.5.3. var binder = function () { if (this instanceof bound) { // 15.3.4.5.2 [[Construct]] // When the [[Construct]] internal method of a function object, // F that was created using the bind function is called with a // list of arguments ExtraArgs, the following steps are taken: // 1. Let target be the value of F's [[TargetFunction]] // internal property. // 2. If target has no [[Construct]] internal method, a // TypeError exception is thrown. // 3. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Construct]] internal // method of target providing args as the arguments. var result = target.apply( this, args.concat(_Array_slice_.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { // 15.3.4.5.1 [[Call]] // When the [[Call]] internal method of a function object, F, // which was created using the bind function is called with a // this value and a list of arguments ExtraArgs, the following // steps are taken: // 1. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 2. Let boundThis be the value of F's [[BoundThis]] internal // property. // 3. Let target be the value of F's [[TargetFunction]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Call]] internal method // of target providing boundThis as the this value and // providing args as the arguments. // equiv: target.call(this, ...boundArgs, ...args) return target.apply( that, args.concat(_Array_slice_.call(arguments)) ); } }; // 15. If the [[Class]] internal property of Target is "Function", then // a. Let L be the length property of Target minus the length of A. // b. Set the length own property of F to either 0 or L, whichever is // larger. // 16. Else set the length own property of F to 0. var boundLength = Math.max(0, target.length - args.length); // 17. Set the attributes of the length own property of F to the values // specified in 15.3.5.1. var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push("$" + i); } // XXX Build a dynamic function with desired amount of arguments is the only // way to set the length property of a function. // In environments where Content Security Policies enabled (Chrome extensions, // for ex.) all use of eval or Function costructor throws an exception. // However in all of these environments Function.prototype.bind exists // and so this code will never be executed. var bound = Function("binder", "return function (" + boundArgs.join(",") + "){return binder.apply(this,arguments)}")(binder); if (target.prototype) { Empty.prototype = target.prototype; bound.prototype = new Empty(); // Clean up dangling references. Empty.prototype = null; } // TODO // 18. Set the [[Extensible]] internal property of F to true. // TODO // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3). // 20. Call the [[DefineOwnProperty]] internal method of F with // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]: // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and // false. // 21. Call the [[DefineOwnProperty]] internal method of F with // arguments "arguments", PropertyDescriptor {[[Get]]: thrower, // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false}, // and false. // TODO // NOTE Function objects created using Function.prototype.bind do not // have a prototype property or the [[Code]], [[FormalParameters]], and // [[Scope]] internal properties. // XXX can't delete prototype in pure-js. // 22. Return F. return bound; }; } // _Please note: Shortcuts are defined after `Function.prototype.bind` as we // us it in defining shortcuts. var owns = call.bind(prototypeOfObject.hasOwnProperty); // If JS engine supports accessors creating shortcuts. var defineGetter; var defineSetter; var lookupGetter; var lookupSetter; var supportsAccessors; if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) { defineGetter = call.bind(prototypeOfObject.__defineGetter__); defineSetter = call.bind(prototypeOfObject.__defineSetter__); lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); } // // Array // ===== // // ES5 15.4.4.12 // http://es5.github.com/#x15.4.4.12 var spliceWorksWithEmptyObject = (function () { var obj = {}; Array.prototype.splice.call(obj, 0, 0, 1); return obj.length === 1; }()); var omittingSecondSpliceArgIsNoop = [1].splice(0).length === 0; var spliceNoopReturnsEmptyArray = (function () { var a = [1, 2]; var result = a.splice(); return a.length === 2 && isArray(result) && result.length === 0; }()); if (spliceNoopReturnsEmptyArray) { // Safari 5.0 bug where .split() returns undefined Array.prototype.splice = function splice(start, deleteCount) { if (arguments.length === 0) { return []; } else { return array_splice.apply(this, arguments); } }; } if (!omittingSecondSpliceArgIsNoop || !spliceWorksWithEmptyObject) { Array.prototype.splice = function splice(start, deleteCount) { if (arguments.length === 0) { return []; } var args = arguments; this.length = Math.max(toInteger(this.length), 0); if (arguments.length > 0 && typeof deleteCount !== 'number') { args = _Array_slice_.call(arguments); if (args.length < 2) { args.push(toInteger(deleteCount)); } else { args[1] = toInteger(deleteCount); } } return array_splice.apply(this, args); }; } // ES5 15.4.4.12 // http://es5.github.com/#x15.4.4.13 // Return len+argCount. // [bugfix, ielt8] // IE < 8 bug: [].unshift(0) === undefined but should be "1" if ([].unshift(0) !== 1) { Array.prototype.unshift = function () { array_unshift.apply(this, arguments); return this.length; }; } // ES5 15.4.3.2 // http://es5.github.com/#x15.4.3.2 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray if (!Array.isArray) { Array.isArray = isArray; } // The IsCallable() check in the Array functions // has been replaced with a strict check on the // internal class of the object to trap cases where // the provided function was actually a regular // expression literal, which in V8 and // JavaScriptCore is a typeof "function". Only in // V8 are regular expression literals permitted as // reduce parameters, so it is desirable in the // general case for the shim to match the more // strict and common behavior of rejecting regular // expressions. // ES5 15.4.4.18 // http://es5.github.com/#x15.4.4.18 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach // Check failure of by-index access of string characters (IE < 9) // and failure of `0 in boxedString` (Rhino) var boxedString = Object("a"); var splitString = boxedString[0] !== "a" || !(0 in boxedString); var properlyBoxesContext = function properlyBoxed(method) { // Check node 0.6.21 bug where third parameter is not boxed var properlyBoxesNonStrict = true; var properlyBoxesStrict = true; if (method) { method.call('foo', function (_, __, context) { if (typeof context !== 'object') { properlyBoxesNonStrict = false; } }); method.call([1], function () { 'use strict'; properlyBoxesStrict = typeof this === 'string'; }, 'x'); } return !!method && properlyBoxesNonStrict && properlyBoxesStrict; }; if (!Array.prototype.forEach || !properlyBoxesContext(Array.prototype.forEach)) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString.call(this) === "[object String]" ? this.split("") : object, thisp = arguments[1], i = -1, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (!isFunction(fun)) { throw new TypeError(); // TODO message } while (++i < length) { if (i in self) { // Invoke the callback function with call, passing arguments: // context, property value, property key, thisArg object // context fun.call(thisp, self[i], i, object); } } }; } // ES5 15.4.4.19 // http://es5.github.com/#x15.4.4.19 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map if (!Array.prototype.map || !properlyBoxesContext(Array.prototype.map)) { Array.prototype.map = function map(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString.call(this) === "[object String]" ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; // If no callback function or if callback is not a callable function if (!isFunction(fun)) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { result[i] = fun.call(thisp, self[i], i, object); } } return result; }; } // ES5 15.4.4.20 // http://es5.github.com/#x15.4.4.20 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter if (!Array.prototype.filter || !properlyBoxesContext(Array.prototype.filter)) { Array.prototype.filter = function filter(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString.call(this) === "[object String]" ? this.split("") : object, length = self.length >>> 0, result = [], value, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (!isFunction(fun)) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { value = self[i]; if (fun.call(thisp, value, i, object)) { result.push(value); } } } return result; }; } // ES5 15.4.4.16 // http://es5.github.com/#x15.4.4.16 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every if (!Array.prototype.every || !properlyBoxesContext(Array.prototype.every)) { Array.prototype.every = function every(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString.call(this) === "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (!isFunction(fun)) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } // ES5 15.4.4.17 // http://es5.github.com/#x15.4.4.17 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some if (!Array.prototype.some || !properlyBoxesContext(Array.prototype.some)) { Array.prototype.some = function some(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString.call(this) === "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (!isFunction(fun)) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, object)) { return true; } } return false; }; } // ES5 15.4.4.21 // http://es5.github.com/#x15.4.4.21 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce var reduceCoercesToObject = false; if (Array.prototype.reduce) { reduceCoercesToObject = typeof Array.prototype.reduce.call('es5', function (_, __, ___, list) { return list; }) === 'object'; } if (!Array.prototype.reduce || !reduceCoercesToObject) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString.call(this) === "[object String]" ? this.split("") : object, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (!isFunction(fun)) { throw new TypeError(fun + " is not a function"); } // no value to return if no initial value and an empty array if (!length && arguments.length === 1) { throw new TypeError("reduce of empty array with no initial value"); } var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } // if array contains no values, no initial value to return if (++i >= length) { throw new TypeError("reduce of empty array with no initial value"); } } while (true); } for (; i < length; i++) { if (i in self) { result = fun.call(void 0, result, self[i], i, object); } } return result; }; } // ES5 15.4.4.22 // http://es5.github.com/#x15.4.4.22 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight var reduceRightCoercesToObject = false; if (Array.prototype.reduceRight) { reduceRightCoercesToObject = typeof Array.prototype.reduceRight.call('es5', function (_, __, ___, list) { return list; }) === 'object'; } if (!Array.prototype.reduceRight || !reduceRightCoercesToObject) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString.call(this) === "[object String]" ? this.split("") : object, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (!isFunction(fun)) { throw new TypeError(fun + " is not a function"); } // no value to return if no initial value, empty array if (!length && arguments.length === 1) { throw new TypeError("reduceRight of empty array with no initial value"); } var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } // if array contains no values, no initial value to return if (--i < 0) { throw new TypeError("reduceRight of empty array with no initial value"); } } while (true); } if (i < 0) { return result; } do { if (i in self) { result = fun.call(void 0, result, self[i], i, object); } } while (i--); return result; }; } // ES5 15.4.4.14 // http://es5.github.com/#x15.4.4.14 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) !== -1)) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = splitString && _toString.call(this) === "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = 0; if (arguments.length > 1) { i = toInteger(arguments[1]); } // handle negative indices i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } // ES5 15.4.4.15 // http://es5.github.com/#x15.4.4.15 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) !== -1)) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = splitString && _toString.call(this) === "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = length - 1; if (arguments.length > 1) { i = Math.min(i, toInteger(arguments[1])); } // handle negative indices i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) { return i; } } return -1; }; } // // Object // ====== // // ES5 15.2.3.14 // http://es5.github.com/#x15.2.3.14 var keysWorksWithArguments = Object.keys && (function () { return Object.keys(arguments).length === 2; }(1, 2)); if (!Object.keys) { // http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation var hasDontEnumBug = !({'toString': null}).propertyIsEnumerable('toString'), hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'), dontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ], dontEnumsLength = dontEnums.length; Object.keys = function keys(object) { var isFn = isFunction(object), isArgs = isArguments(object), isObject = object !== null && typeof object === 'object', isString = isObject && _toString.call(object) === '[object String]'; if (!isObject && !isFn && !isArgs) { throw new TypeError("Object.keys called on a non-object"); } var theKeys = []; var skipProto = hasProtoEnumBug && isFn; if (isString || isArgs) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && owns(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var ctor = object.constructor, skipConstructor = ctor && ctor.prototype === object; for (var j = 0; j < dontEnumsLength; j++) { var dontEnum = dontEnums[j]; if (!(skipConstructor && dontEnum === 'constructor') && owns(object, dontEnum)) { theKeys.push(dontEnum); } } } return theKeys; }; } else if (!keysWorksWithArguments) { // Safari 5.0 bug var originalKeys = Object.keys; Object.keys = function keys(object) { if (isArguments(object)) { return originalKeys(Array.prototype.slice.call(object)); } else { return originalKeys(object); } }; } // // Date // ==== // // ES5 15.9.5.43 // http://es5.github.com/#x15.9.5.43 // This function returns a String value represent the instance in time // represented by this Date object. The format of the String is the Date Time // string format defined in 15.9.1.15. All fields are present in the String. // The time zone is always UTC, denoted by the suffix Z. If the time value of // this object is not a finite Number a RangeError exception is thrown. var negativeDate = -62198755200000, negativeYearString = "-000001"; if ( !Date.prototype.toISOString || (new Date(negativeDate).toISOString().indexOf(negativeYearString) === -1) ) { Date.prototype.toISOString = function toISOString() { var result, length, value, year, month; if (!isFinite(this)) { throw new RangeError("Date.prototype.toISOString called on non-finite value."); } year = this.getUTCFullYear(); month = this.getUTCMonth(); // see https://github.com/es-shims/es5-shim/issues/111 year += Math.floor(month / 12); month = (month % 12 + 12) % 12; // the date time string format is specified in 15.9.1.15. result = [month + 1, this.getUTCDate(), this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()]; year = ( (year < 0 ? "-" : (year > 9999 ? "+" : "")) + ("00000" + Math.abs(year)).slice(0 <= year && year <= 9999 ? -4 : -6) ); length = result.length; while (length--) { value = result[length]; // pad months, days, hours, minutes, and seconds to have two // digits. if (value < 10) { result[length] = "0" + value; } } // pad milliseconds to have three digits. return ( year + "-" + result.slice(0, 2).join("-") + "T" + result.slice(2).join(":") + "." + ("000" + this.getUTCMilliseconds()).slice(-3) + "Z" ); }; } // ES5 15.9.5.44 // http://es5.github.com/#x15.9.5.44 // This function provides a String representation of a Date object for use by // JSON.stringify (15.12.3). var dateToJSONIsSupported = false; try { dateToJSONIsSupported = ( Date.prototype.toJSON && new Date(NaN).toJSON() === null && new Date(negativeDate).toJSON().indexOf(negativeYearString) !== -1 && Date.prototype.toJSON.call({ // generic toISOString: function () { return true; } }) ); } catch (e) { } if (!dateToJSONIsSupported) { Date.prototype.toJSON = function toJSON(key) { // When the toJSON method is called with argument key, the following // steps are taken: // 1. Let O be the result of calling ToObject, giving it the this // value as its argument. // 2. Let tv be toPrimitive(O, hint Number). var o = Object(this), tv = toPrimitive(o), toISO; // 3. If tv is a Number and is not finite, return null. if (typeof tv === "number" && !isFinite(tv)) { return null; } // 4. Let toISO be the result of calling the [[Get]] internal method of // O with argument "toISOString". toISO = o.toISOString; // 5. If IsCallable(toISO) is false, throw a TypeError exception. if (typeof toISO !== "function") { throw new TypeError("toISOString property is not callable"); } // 6. Return the result of calling the [[Call]] internal method of // toISO with O as the this value and an empty argument list. return toISO.call(o); // NOTE 1 The argument is ignored. // NOTE 2 The toJSON function is intentionally generic; it does not // require that its this value be a Date object. Therefore, it can be // transferred to other kinds of objects for use as a method. However, // it does require that any such object have a toISOString method. An // object is free to use the argument key to filter its // stringification. }; } // ES5 15.9.4.2 // http://es5.github.com/#x15.9.4.2 // based on work shared by Daniel Friesen (dantman) // http://gist.github.com/303249 var supportsExtendedYears = Date.parse('+033658-09-27T01:46:40.000Z') === 1e15; var acceptsInvalidDates = !isNaN(Date.parse('2012-04-04T24:00:00.500Z')) || !isNaN(Date.parse('2012-11-31T23:59:59.000Z')); var doesNotParseY2KNewYear = isNaN(Date.parse("2000-01-01T00:00:00.000Z")); if (!Date.parse || doesNotParseY2KNewYear || acceptsInvalidDates || !supportsExtendedYears) { // XXX global assignment won't work in embeddings that use // an alternate object for the context. Date = (function (NativeDate) { // Date.length === 7 function Date(Y, M, D, h, m, s, ms) { var length = arguments.length; if (this instanceof NativeDate) { var date = length === 1 && String(Y) === Y ? // isString(Y) // We explicitly pass it through parse: new NativeDate(Date.parse(Y)) : // We have to manually make calls depending on argument // length here length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) : length >= 6 ? new NativeDate(Y, M, D, h, m, s) : length >= 5 ? new NativeDate(Y, M, D, h, m) : length >= 4 ? new NativeDate(Y, M, D, h) : length >= 3 ? new NativeDate(Y, M, D) : length >= 2 ? new NativeDate(Y, M) : length >= 1 ? new NativeDate(Y) : new NativeDate(); // Prevent mixups with unfixed Date object date.constructor = Date; return date; } return NativeDate.apply(this, arguments); } // 15.9.1.15 Date Time String Format. var isoDateExpression = new RegExp("^" + "(\\d{4}|[\+\-]\\d{6})" + // four-digit year capture or sign + // 6-digit extended year "(?:-(\\d{2})" + // optional month capture "(?:-(\\d{2})" + // optional day capture "(?:" + // capture hours:minutes:seconds.milliseconds "T(\\d{2})" + // hours capture ":(\\d{2})" + // minutes capture "(?:" + // optional :seconds.milliseconds ":(\\d{2})" + // seconds capture "(?:(\\.\\d{1,}))?" + // milliseconds capture ")?" + "(" + // capture UTC offset component "Z|" + // UTC capture "(?:" + // offset specifier +/-hours:minutes "([-+])" + // sign capture "(\\d{2})" + // hours offset capture ":(\\d{2})" + // minutes offset capture ")" + ")?)?)?)?" + "$"); var months = [ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 ]; function dayFromMonth(year, month) { var t = month > 1 ? 1 : 0; return ( months[month] + Math.floor((year - 1969 + t) / 4) - Math.floor((year - 1901 + t) / 100) + Math.floor((year - 1601 + t) / 400) + 365 * (year - 1970) ); } function toUTC(t) { return Number(new NativeDate(1970, 0, 1, 0, 0, 0, t)); } // Copy any custom methods a 3rd party library may have added for (var key in NativeDate) { Date[key] = NativeDate[key]; } // Copy "native" methods explicitly; they may be non-enumerable Date.now = NativeDate.now; Date.UTC = NativeDate.UTC; Date.prototype = NativeDate.prototype; Date.prototype.constructor = Date; // Upgrade Date.parse to handle simplified ISO 8601 strings Date.parse = function parse(string) { var match = isoDateExpression.exec(string); if (match) { // parse months, days, hours, minutes, seconds, and milliseconds // provide default values if necessary // parse the UTC offset component var year = Number(match[1]), month = Number(match[2] || 1) - 1, day = Number(match[3] || 1) - 1, hour = Number(match[4] || 0), minute = Number(match[5] || 0), second = Number(match[6] || 0), millisecond = Math.floor(Number(match[7] || 0) * 1000), // When time zone is missed, local offset should be used // (ES 5.1 bug) // see https://bugs.ecmascript.org/show_bug.cgi?id=112 isLocalTime = Boolean(match[4] && !match[8]), signOffset = match[9] === "-" ? 1 : -1, hourOffset = Number(match[10] || 0), minuteOffset = Number(match[11] || 0), result; if ( hour < ( minute > 0 || second > 0 || millisecond > 0 ? 24 : 25 ) && minute < 60 && second < 60 && millisecond < 1000 && month > -1 && month < 12 && hourOffset < 24 && minuteOffset < 60 && // detect invalid offsets day > -1 && day < ( dayFromMonth(year, month + 1) - dayFromMonth(year, month) ) ) { result = ( (dayFromMonth(year, month) + day) * 24 + hour + hourOffset * signOffset ) * 60; result = ( (result + minute + minuteOffset * signOffset) * 60 + second ) * 1000 + millisecond; if (isLocalTime) { result = toUTC(result); } if (-8.64e15 <= result && result <= 8.64e15) { return result; } } return NaN; } return NativeDate.parse.apply(this, arguments); }; return Date; })(Date); } // ES5 15.9.4.4 // http://es5.github.com/#x15.9.4.4 if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } // // Number // ====== // // ES5.1 15.7.4.5 // http://es5.github.com/#x15.7.4.5 if (!Number.prototype.toFixed || (0.00008).toFixed(3) !== '0.000' || (0.9).toFixed(0) === '0' || (1.255).toFixed(2) !== '1.25' || (1000000000000000128).toFixed(0) !== "1000000000000000128") { // Hide these variables and functions (function () { var base, size, data, i; base = 1e7; size = 6; data = [0, 0, 0, 0, 0, 0]; function multiply(n, c) { var i = -1; while (++i < size) { c += n * data[i]; data[i] = c % base; c = Math.floor(c / base); } } function divide(n) { var i = size, c = 0; while (--i >= 0) { c += data[i]; data[i] = Math.floor(c / n); c = (c % n) * base; } } function numToString() { var i = size; var s = ''; while (--i >= 0) { if (s !== '' || i === 0 || data[i] !== 0) { var t = String(data[i]); if (s === '') { s = t; } else { s += '0000000'.slice(0, 7 - t.length) + t; } } } return s; } function pow(x, n, acc) { return (n === 0 ? acc : (n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc))); } function log(x) { var n = 0; while (x >= 4096) { n += 12; x /= 4096; } while (x >= 2) { n += 1; x /= 2; } return n; } Number.prototype.toFixed = function toFixed(fractionDigits) { var f, x, s, m, e, z, j, k; // Test for NaN and round fractionDigits down f = Number(fractionDigits); f = f !== f ? 0 : Math.floor(f); if (f < 0 || f > 20) { throw new RangeError("Number.toFixed called with invalid number of decimals"); } x = Number(this); // Test for NaN if (x !== x) { return "NaN"; } // If it is too big or small, return the string value of the number if (x <= -1e21 || x >= 1e21) { return String(x); } s = ""; if (x < 0) { s = "-"; x = -x; } m = "0"; if (x > 1e-21) { // 1e-21 < x < 1e21 // -70 < log2(x) < 70 e = log(x * pow(2, 69, 1)) - 69; z = (e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1)); z *= 0x10000000000000; // Math.pow(2, 52); e = 52 - e; // -18 < e < 122 // x = z / 2 ^ e if (e > 0) { multiply(0, z); j = f; while (j >= 7) { multiply(1e7, 0); j -= 7; } multiply(pow(10, j, 1), 0); j = e - 1; while (j >= 23) { divide(1 << 23); j -= 23; } divide(1 << j); multiply(1, 1); divide(2); m = numToString(); } else { multiply(0, z); multiply(1 << (-e), 0); m = numToString() + '0.00000000000000000000'.slice(2, 2 + f); } } if (f > 0) { k = m.length; if (k <= f) { m = s + '0.0000000000000000000'.slice(0, f - k + 2) + m; } else { m = s + m.slice(0, k - f) + '.' + m.slice(k - f); } } else { m = s + m; } return m; }; }()); } // // String // ====== // // ES5 15.5.4.14 // http://es5.github.com/#x15.5.4.14 // [bugfix, IE lt 9, firefox 4, Konqueror, Opera, obscure browsers] // Many browsers do not split properly with regular expressions or they // do not perform the split correctly under obscure conditions. // See http://blog.stevenlevithan.com/archives/cross-browser-split // I've tested in many browsers and this seems to cover the deviant ones: // 'ab'.split(/(?:ab)*/) should be ["", ""], not [""] // '.'.split(/(.?)(.?)/) should be ["", ".", "", ""], not ["", ""] // 'tesst'.split(/(s)*/) should be ["t", undefined, "e", "s", "t"], not // [undefined, "t", undefined, "e", ...] // ''.split(/.?/) should be [], not [""] // '.'.split(/()()/) should be ["."], not ["", "", "."] var string_split = String.prototype.split; if ( 'ab'.split(/(?:ab)*/).length !== 2 || '.'.split(/(.?)(.?)/).length !== 4 || 'tesst'.split(/(s)*/)[1] === "t" || 'test'.split(/(?:)/, -1).length !== 4 || ''.split(/.?/).length || '.'.split(/()()/).length > 1 ) { (function () { var compliantExecNpcg = /()??/.exec("")[1] === void 0; // NPCG: nonparticipating capturing group String.prototype.split = function (separator, limit) { var string = this; if (separator === void 0 && limit === 0) { return []; } // If `separator` is not a regex, use native split if (_toString.call(separator) !== "[object RegExp]") { return string_split.call(this, separator, limit); } var output = [], flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + // Proposed for ES6 (separator.sticky ? "y" : ""), // Firefox 3+ lastLastIndex = 0, // Make `global` and avoid `lastIndex` issues by working with a copy separator2, match, lastIndex, lastLength; separator = new RegExp(separator.source, flags + "g"); string += ""; // Type-convert if (!compliantExecNpcg) { // Doesn't need flags gy, but they don't hurt separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags); } /* Values for `limit`, per the spec: * If undefined: 4294967295 // Math.pow(2, 32) - 1 * If 0, Infinity, or NaN: 0 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296; * If negative number: 4294967296 - Math.floor(Math.abs(limit)) * If other: Type-convert, then use the above rules */ limit = limit === void 0 ? -1 >>> 0 : // Math.pow(2, 32) - 1 ToUint32(limit); while (match = separator.exec(string)) { // `separator.lastIndex` is not reliable cross-browser lastIndex = match.index + match[0].length; if (lastIndex > lastLastIndex) { output.push(string.slice(lastLastIndex, match.index)); // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1) { match[0].replace(separator2, function () { for (var i = 1; i < arguments.length - 2; i++) { if (arguments[i] === void 0) { match[i] = void 0; } } }); } if (match.length > 1 && match.index < string.length) { Array.prototype.push.apply(output, match.slice(1)); } lastLength = match[0].length; lastLastIndex = lastIndex; if (output.length >= limit) { break; } } if (separator.lastIndex === match.index) { separator.lastIndex++; // Avoid an infinite loop } } if (lastLastIndex === string.length) { if (lastLength || !separator.test("")) { output.push(""); } } else { output.push(string.slice(lastLastIndex)); } return output.length > limit ? output.slice(0, limit) : output; }; }()); // [bugfix, chrome] // If separator is undefined, then the result array contains just one String, // which is the this value (converted to a String). If limit is not undefined, // then the output array is truncated so that it contains no more than limit // elements. // "0".split(undefined, 0) -> [] } else if ("0".split(void 0, 0).length) { String.prototype.split = function split(separator, limit) { if (separator === void 0 && limit === 0) { return []; } return string_split.call(this, separator, limit); }; } var str_replace = String.prototype.replace; var replaceReportsGroupsCorrectly = (function () { var groups = []; 'x'.replace(/x(.)?/g, function (match, group) { groups.push(group); }); return groups.length === 1 && typeof groups[0] === 'undefined'; }()); if (!replaceReportsGroupsCorrectly) { String.prototype.replace = function replace(searchValue, replaceValue) { var isFn = isFunction(replaceValue); var hasCapturingGroups = isRegex(searchValue) && (/\)[*?]/).test(searchValue.source); if (!isFn || !hasCapturingGroups) { return str_replace.call(this, searchValue, replaceValue); } else { var wrappedReplaceValue = function (match) { var length = arguments.length; var originalLastIndex = searchValue.lastIndex; searchValue.lastIndex = 0; var args = searchValue.exec(match); searchValue.lastIndex = originalLastIndex; args.push(arguments[length - 2], arguments[length - 1]); return replaceValue.apply(this, args); }; return str_replace.call(this, searchValue, wrappedReplaceValue); } }; } // ECMA-262, 3rd B.2.3 // Not an ECMAScript standard, although ECMAScript 3rd Edition has a // non-normative section suggesting uniform semantics and it should be // normalized across all browsers // [bugfix, IE lt 9] IE < 9 substr() with negative value not working in IE if ("".substr && "0b".substr(-1) !== "b") { var string_substr = String.prototype.substr; /** * Get the substring of a string * @param {integer} start where to start the substring * @param {integer} length how many characters to return * @return {string} */ String.prototype.substr = function substr(start, length) { return string_substr.call( this, start < 0 ? ((start = this.length + start) < 0 ? 0 : start) : start, length ); }; } // ES5 15.5.4.20 // whitespace from: http://es5.github.io/#x15.5.4.20 var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; var zeroWidth = '\u200b'; if (!String.prototype.trim || ws.trim() || !zeroWidth.trim()) { // http://blog.stevenlevithan.com/archives/faster-trim-javascript // http://perfectionkills.com/whitespace-deviations/ ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { if (this === void 0 || this === null) { throw new TypeError("can't convert " + this + " to object"); } return String(this) .replace(trimBeginRegexp, "") .replace(trimEndRegexp, ""); }; } // ES-5 15.1.2.2 if (parseInt(ws + '08') !== 8 || parseInt(ws + '0x16') !== 22) { parseInt = (function (origParseInt) { var hexRegex = /^0[xX]/; return function parseIntES5(str, radix) { str = String(str).trim(); if (!Number(radix)) { radix = hexRegex.test(str) ? 16 : 10; } return origParseInt(str, radix); }; }(parseInt)); } // // Util // ====== // // ES5 9.4 // http://es5.github.com/#x9.4 // http://jsperf.com/to-integer function toInteger(n) { n = +n; if (n !== n) { // isNaN n = 0; } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } return n; } function isPrimitive(input) { var type = typeof input; return ( input === null || type === "undefined" || type === "boolean" || type === "number" || type === "string" ); } function toPrimitive(input) { var val, valueOf, toStr; if (isPrimitive(input)) { return input; } valueOf = input.valueOf; if (isFunction(valueOf)) { val = valueOf.call(input); if (isPrimitive(val)) { return val; } } toStr = input.toString; if (isFunction(toStr)) { val = toStr.call(input); if (isPrimitive(val)) { return val; } } throw new TypeError(); } // ES5 9.9 // http://es5.github.com/#x9.9 var toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError("can't convert " + o + " to object"); } return Object(o); }; var ToUint32 = function ToUint32(x) { return x >>> 0; }; })(); (function($, shims){ var defineProperty = 'defineProperty'; var advancedObjectProperties = !!(Object.create && Object.defineProperties && Object.getOwnPropertyDescriptor); //safari5 has defineProperty-interface, but it can't be used on dom-object //only do this test in non-IE browsers, because this hurts dhtml-behavior in some IE8 versions if (advancedObjectProperties && Object[defineProperty] && Object.prototype.__defineGetter__) { (function(){ try { var foo = document.createElement('foo'); Object[defineProperty](foo, 'bar', { get: function(){ return true; } }); advancedObjectProperties = !!foo.bar; } catch (e) { advancedObjectProperties = false; } foo = null; })(); } Modernizr.objectAccessor = !!((advancedObjectProperties || (Object.prototype.__defineGetter__ && Object.prototype.__lookupSetter__))); Modernizr.advancedObjectProperties = advancedObjectProperties; if((!advancedObjectProperties || !Object.create || !Object.defineProperties || !Object.getOwnPropertyDescriptor || !Object.defineProperty)){ var call = Function.prototype.call; var prototypeOfObject = Object.prototype; var owns = call.bind(prototypeOfObject.hasOwnProperty); shims.objectCreate = function(proto, props, opts, no__proto__){ var o; var f = function(){}; f.prototype = proto; o = new f(); if(!no__proto__ && !('__proto__' in o) && !Modernizr.objectAccessor){ o.__proto__ = proto; } if(props){ shims.defineProperties(o, props); } if(opts){ o.options = $.extend(true, {}, o.options || {}, opts); opts = o.options; } if(o._create && $.isFunction(o._create)){ o._create(opts); } return o; }; shims.defineProperties = function(object, props){ for (var name in props) { if (owns(props, name)) { shims.defineProperty(object, name, props[name]); } } return object; }; var descProps = ['configurable', 'enumerable', 'writable']; shims.defineProperty = function(proto, property, descriptor){ if(typeof descriptor != "object" || descriptor === null){return proto;} if(owns(descriptor, "value")){ proto[property] = descriptor.value; return proto; } if(proto.__defineGetter__){ if (typeof descriptor.get == "function") { proto.__defineGetter__(property, descriptor.get); } if (typeof descriptor.set == "function"){ proto.__defineSetter__(property, descriptor.set); } } return proto; }; shims.getPrototypeOf = function (object) { return Object.getPrototypeOf && Object.getPrototypeOf(object) || object.__proto__ || object.constructor && object.constructor.prototype; }; //based on http://www.refactory.org/s/object_getownpropertydescriptor/view/latest shims.getOwnPropertyDescriptor = function(obj, prop){ if (typeof obj !== "object" && typeof obj !== "function" || obj === null){ throw new TypeError("Object.getOwnPropertyDescriptor called on a non-object"); } var descriptor; if(Object.defineProperty && Object.getOwnPropertyDescriptor){ try{ descriptor = Object.getOwnPropertyDescriptor(obj, prop); return descriptor; } catch(e){} } descriptor = { configurable: true, enumerable: true, writable: true, value: undefined }; var getter = obj.__lookupGetter__ && obj.__lookupGetter__(prop), setter = obj.__lookupSetter__ && obj.__lookupSetter__(prop) ; if (!getter && !setter) { // not an accessor so return prop if(!owns(obj, prop)){ return; } descriptor.value = obj[prop]; return descriptor; } // there is an accessor, remove descriptor.writable; populate descriptor.get and descriptor.set delete descriptor.writable; delete descriptor.value; descriptor.get = descriptor.set = undefined; if(getter){ descriptor.get = getter; } if(setter){ descriptor.set = setter; } return descriptor; }; } webshims.isReady('es5', true); })(webshims.$, webshims); ; //this might was already extended by ES5 shim feature (function($){ "use strict"; var webshims = window.webshims; if(webshims.defineProperties){return;} var defineProperty = 'defineProperty'; var has = Object.prototype.hasOwnProperty; var descProps = ['configurable', 'enumerable', 'writable']; var extendUndefined = function(prop){ for(var i = 0; i < 3; i++){ if(prop[descProps[i]] === undefined && (descProps[i] !== 'writable' || prop.value !== undefined)){ prop[descProps[i]] = true; } } }; var extendProps = function(props){ if(props){ for(var i in props){ if(has.call(props, i)){ extendUndefined(props[i]); } } } }; if(Object.create){ webshims.objectCreate = function(proto, props, opts){ extendProps(props); var o = Object.create(proto, props); if(opts){ o.options = $.extend(true, {}, o.options || {}, opts); opts = o.options; } if(o._create && $.isFunction(o._create)){ o._create(opts); } return o; }; } if(Object[defineProperty]){ webshims[defineProperty] = function(obj, prop, desc){ extendUndefined(desc); return Object[defineProperty](obj, prop, desc); }; } if(Object.defineProperties){ webshims.defineProperties = function(obj, props){ extendProps(props); return Object.defineProperties(obj, props); }; } webshims.getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; webshims.getPrototypeOf = Object.getPrototypeOf; })(window.webshims.$); //DOM-Extension helper webshims.register('dom-extend', function($, webshims, window, document, undefined){ "use strict"; var supportHrefNormalized = !('hrefNormalized' in $.support) || $.support.hrefNormalized; var supportGetSetAttribute = !('getSetAttribute' in $.support) || $.support.getSetAttribute; var has = Object.prototype.hasOwnProperty; webshims.assumeARIA = supportGetSetAttribute || Modernizr.canvas || Modernizr.video || Modernizr.boxsizing; if($('<input type="email" />').attr('type') == 'text' || $('<form />').attr('novalidate') === "" || ('required' in $('<input />')[0].attributes)){ webshims.error("IE browser modes are busted in IE10+. Please test your HTML/CSS/JS with a real IE version or at least IETester or similiar tools"); } if('debug' in webshims){ webshims.error('Use webshims.setOptions("debug", true||false||"noCombo"); to debug flag'); } if (!webshims.cfg.no$Switch) { var switch$ = function(){ if (window.jQuery && (!window.$ || window.jQuery == window.$) && !window.jQuery.webshims) { webshims.error("jQuery was included more than once. Make sure to include it only once or try the $.noConflict(extreme) feature! Webshims and other Plugins might not work properly. Or set webshims.cfg.no$Switch to 'true'."); if (window.$) { window.$ = webshims.$; } window.jQuery = webshims.$; } if(webshims.M != Modernizr){ webshims.error("Modernizr was included more than once. Make sure to include it only once! Webshims and other scripts might not work properly."); for(var i in Modernizr){ if(!(i in webshims.M)){ webshims.M[i] = Modernizr[i]; } } Modernizr = webshims.M; } }; switch$(); setTimeout(switch$, 90); webshims.ready('DOM', switch$); $(switch$); webshims.ready('WINDOWLOAD', switch$); } //shortcus var modules = webshims.modules; var listReg = /\s*,\s*/; //proxying attribute var olds = {}; var havePolyfill = {}; var hasPolyfillMethod = {}; var extendedProps = {}; var extendQ = {}; var modifyProps = {}; var oldVal = $.fn.val; var singleVal = function(elem, name, val, pass, _argless){ return (_argless) ? oldVal.call($(elem)) : oldVal.call($(elem), val); }; //jquery mobile and jquery ui if(!$.widget){ (function(){ var _cleanData = $.cleanData; $.cleanData = function( elems ) { if(!$.widget){ for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } } _cleanData( elems ); }; })(); } $.fn.val = function(val){ var elem = this[0]; if(arguments.length && val == null){ val = ''; } if(!arguments.length){ if(!elem || elem.nodeType !== 1){return oldVal.call(this);} return $.prop(elem, 'value', val, 'val', true); } if($.isArray(val)){ return oldVal.apply(this, arguments); } var isFunction = $.isFunction(val); return this.each(function(i){ elem = this; if(elem.nodeType === 1){ if(isFunction){ var genVal = val.call( elem, i, $.prop(elem, 'value', undefined, 'val', true)); if(genVal == null){ genVal = ''; } $.prop(elem, 'value', genVal, 'val') ; } else { $.prop(elem, 'value', val, 'val'); } } }); }; $.fn.onTrigger = function(evt, fn){ return this.on(evt, fn).each(fn); }; $.fn.onWSOff = function(evt, fn, trigger, evtDel){ if(!evtDel){ evtDel = document; } $(evtDel)[trigger ? 'onTrigger' : 'on'](evt, fn); this.on('remove', function(e){ if(!e.originalEvent){ $(evtDel).off(evt, fn); } }); return this; }; var idCount = 0; var dataID = '_webshims'+ (Math.round(Math.random() * 1000)); var elementData = function(elem, key, val){ elem = elem.jquery ? elem[0] : elem; if(!elem){return val || {};} var data = $.data(elem, dataID); if(val !== undefined){ if(!data){ data = $.data(elem, dataID, {}); } if(key){ data[key] = val; } } return key ? data && data[key] : data; }; [{name: 'getNativeElement', prop: 'nativeElement'}, {name: 'getShadowElement', prop: 'shadowElement'}, {name: 'getShadowFocusElement', prop: 'shadowFocusElement'}].forEach(function(data){ $.fn[data.name] = function(){ var elems = []; this.each(function(){ var shadowData = elementData(this, 'shadowData'); var elem = shadowData && shadowData[data.prop] || this; if($.inArray(elem, elems) == -1){ elems.push(elem); } }); return this.pushStack(elems); }; }); function clone(elem, dataAndEvents, uniqueIds){ var cloned = $.clone( elem, dataAndEvents, false ); $(cloned.querySelectorAll('.'+webshims.shadowClass)).detach(); if(uniqueIds){ idCount++; $(cloned.querySelectorAll('[id]')).prop('id', function(i, id){ return id +idCount; }); } else { $(cloned.querySelectorAll('audio[id^="ID-"], video[id^="ID-"], label[id^="ID-"]')).removeAttr('id'); } return cloned; } $.fn.clonePolyfill = function(dataAndEvents, uniqueIds){ dataAndEvents = dataAndEvents || false; return this .map(function() { var cloned = clone( this, dataAndEvents, uniqueIds ); setTimeout(function(){ if($.contains(document.body, cloned)){ $(cloned).updatePolyfill(); } }); return cloned; }) ; }; //add support for $('video').trigger('play') in case extendNative is set to false if(!webshims.cfg.extendNative && !webshims.cfg.noTriggerOverride){ (function(oldTrigger){ $.event.trigger = function(event, data, elem, onlyHandlers){ if(!hasPolyfillMethod[event] || onlyHandlers || !elem || elem.nodeType !== 1){ return oldTrigger.apply(this, arguments); } var ret, isOrig, origName; var origFn = elem[event]; var polyfilledFn = $.prop(elem, event); var changeFn = polyfilledFn && origFn != polyfilledFn; if(changeFn){ origName = '__ws'+event; isOrig = (event in elem) && has.call(elem, event); elem[event] = polyfilledFn; elem[origName] = origFn; } ret = oldTrigger.apply(this, arguments); if (changeFn) { if(isOrig){ elem[event] = origFn; } else { delete elem[event]; } delete elem[origName]; } return ret; }; })($.event.trigger); } ['removeAttr', 'prop', 'attr'].forEach(function(type){ olds[type] = $[type]; $[type] = function(elem, name, value, pass, _argless){ var isVal = (pass == 'val'); var oldMethod = !isVal ? olds[type] : singleVal; if( !elem || !havePolyfill[name] || elem.nodeType !== 1 || (!isVal && pass && type == 'attr' && $.attrFn[name]) ){ return oldMethod(elem, name, value, pass, _argless); } var nodeName = (elem.nodeName || '').toLowerCase(); var desc = extendedProps[nodeName]; var curType = (type == 'attr' && (value === false || value === null)) ? 'removeAttr' : type; var propMethod; var oldValMethod; var ret; if(!desc){ desc = extendedProps['*']; } if(desc){ desc = desc[name]; } if(desc){ propMethod = desc[curType]; } if(propMethod){ if(name == 'value'){ oldValMethod = propMethod.isVal; propMethod.isVal = isVal; } if(curType === 'removeAttr'){ return propMethod.value.call(elem); } else if(value === undefined){ return (propMethod.get) ? propMethod.get.call(elem) : propMethod.value ; } else if(propMethod.set) { if(type == 'attr' && value === true){ value = name; } ret = propMethod.set.call(elem, value); } if(name == 'value'){ propMethod.isVal = oldValMethod; } } else { ret = oldMethod(elem, name, value, pass, _argless); } if((value !== undefined || curType === 'removeAttr') && modifyProps[nodeName] && modifyProps[nodeName][name]){ var boolValue; if(curType == 'removeAttr'){ boolValue = false; } else if(curType == 'prop'){ boolValue = !!(value); } else { boolValue = true; } modifyProps[nodeName][name].forEach(function(fn){ if(!fn.only || (fn.only = 'prop' && type == 'prop') || (fn.only == 'attr' && type != 'prop')){ fn.call(elem, value, boolValue, (isVal) ? 'val' : curType, type); } }); } return ret; }; extendQ[type] = function(nodeName, prop, desc){ if(!extendedProps[nodeName]){ extendedProps[nodeName] = {}; } if(!extendedProps[nodeName][prop]){ extendedProps[nodeName][prop] = {}; } var oldDesc = extendedProps[nodeName][prop][type]; var getSup = function(propType, descriptor, oDesc){ var origProp; if(descriptor && descriptor[propType]){ return descriptor[propType]; } if(oDesc && oDesc[propType]){ return oDesc[propType]; } if(type == 'prop' && prop == 'value'){ return function(value){ var elem = this; return (desc.isVal) ? singleVal(elem, prop, value, false, (arguments.length === 0)) : olds[type](elem, prop, value) ; }; } if(type == 'prop' && propType == 'value' && desc.value.apply){ origProp = '__ws'+prop; hasPolyfillMethod[prop] = true; return function(value){ var sup = this[origProp] || olds[type](this, prop); if(sup && sup.apply){ sup = sup.apply(this, arguments); } return sup; }; } return function(value){ return olds[type](this, prop, value); }; }; extendedProps[nodeName][prop][type] = desc; if(desc.value === undefined){ if(!desc.set){ desc.set = desc.writeable ? getSup('set', desc, oldDesc) : (webshims.cfg.useStrict && prop == 'prop') ? function(){throw(prop +' is readonly on '+ nodeName);} : function(){webshims.info(prop +' is readonly on '+ nodeName);} ; } if(!desc.get){ desc.get = getSup('get', desc, oldDesc); } } ['value', 'get', 'set'].forEach(function(descProp){ if(desc[descProp]){ desc['_sup'+descProp] = getSup(descProp, oldDesc); } }); }; }); var extendNativeValue = (function(){ var UNKNOWN = webshims.getPrototypeOf(document.createElement('foobar')); //see also: https://github.com/lojjic/PIE/issues/40 | https://prototype.lighthouseapp.com/projects/8886/tickets/1107-ie8-fatal-crash-when-prototypejs-is-loaded-with-rounded-cornershtc var isExtendNativeSave = Modernizr.advancedObjectProperties && Modernizr.objectAccessor; return function(nodeName, prop, desc){ var elem , elemProto; if( isExtendNativeSave && (elem = document.createElement(nodeName)) && (elemProto = webshims.getPrototypeOf(elem)) && UNKNOWN !== elemProto && ( !elem[prop] || !has.call(elem, prop) ) ){ var sup = elem[prop]; desc._supvalue = function(){ if(sup && sup.apply){ return sup.apply(this, arguments); } return sup; }; elemProto[prop] = desc.value; } else { desc._supvalue = function(){ var data = elementData(this, 'propValue'); if(data && data[prop] && data[prop].apply){ return data[prop].apply(this, arguments); } return data && data[prop]; }; initProp.extendValue(nodeName, prop, desc.value); } desc.value._supvalue = desc._supvalue; }; })(); var initProp = (function(){ var initProps = {}; webshims.addReady(function(context, contextElem){ var nodeNameCache = {}; var getElementsByName = function(name){ if(!nodeNameCache[name]){ nodeNameCache[name] = $(context.getElementsByTagName(name)); if(contextElem[0] && $.nodeName(contextElem[0], name)){ nodeNameCache[name] = nodeNameCache[name].add(contextElem); } } }; $.each(initProps, function(name, fns){ getElementsByName(name); if(!fns || !fns.forEach){ webshims.warn('Error: with '+ name +'-property. methods: '+ fns); return; } fns.forEach(function(fn){ nodeNameCache[name].each(fn); }); }); nodeNameCache = null; }); var tempCache; var emptyQ = $([]); var createNodeNameInit = function(nodeName, fn){ if(!initProps[nodeName]){ initProps[nodeName] = [fn]; } else { initProps[nodeName].push(fn); } if($.isDOMReady){ (tempCache || $( document.getElementsByTagName(nodeName) )).each(fn); } }; var elementExtends = {}; return { createTmpCache: function(nodeName){ if($.isDOMReady){ tempCache = tempCache || $( document.getElementsByTagName(nodeName) ); } return tempCache || emptyQ; }, flushTmpCache: function(){ tempCache = null; }, content: function(nodeName, prop){ createNodeNameInit(nodeName, function(){ var val = $.attr(this, prop); if(val != null){ $.attr(this, prop, val); } }); }, createElement: function(nodeName, fn){ createNodeNameInit(nodeName, fn); }, extendValue: function(nodeName, prop, value){ createNodeNameInit(nodeName, function(){ $(this).each(function(){ var data = elementData(this, 'propValue', {}); data[prop] = this[prop]; this[prop] = value; }); }); } }; })(); var createPropDefault = function(descs, removeType){ if(descs.defaultValue === undefined){ descs.defaultValue = ''; } if(!descs.removeAttr){ descs.removeAttr = { value: function(){ descs[removeType || 'prop'].set.call(this, descs.defaultValue); descs.removeAttr._supvalue.call(this); } }; } if(!descs.attr){ descs.attr = {}; } }; $.extend(webshims, { getID: (function(){ var ID = new Date().getTime(); return function(elem){ elem = $(elem); var id = elem.prop('id'); if(!id){ ID++; id = 'ID-'+ ID; elem.eq(0).prop('id', id); } return id; }; })(), shadowClass: 'wsshadow-'+(Date.now()), implement: function(elem, type){ var data = elementData(elem, 'implemented') || elementData(elem, 'implemented', {}); if(data[type]){ webshims.warn(type +' already implemented for element #'+elem.id); return false; } data[type] = true; return true; }, extendUNDEFProp: function(obj, props){ $.each(props, function(name, prop){ if( !(name in obj) ){ obj[name] = prop; } }); }, getOptions: (function(){ var normalName = /\-([a-z])/g; var regs = {}; var nameRegs = {}; var regFn = function(f, upper){ return upper.toLowerCase(); }; var nameFn = function(f, dashed){ return dashed.toUpperCase(); }; return function(elem, name, bases, stringAllowed){ if(nameRegs[name]){ name = nameRegs[name]; } else { nameRegs[name] = name.replace(normalName, nameFn); name = nameRegs[name]; } var data = elementData(elem, 'cfg'+name); var dataName; var cfg = {}; if(data){ return data; } data = $(elem).data(); if(data && typeof data[name] == 'string'){ if(stringAllowed){ return elementData(elem, 'cfg'+name, data[name]); } webshims.error('data-'+ name +' attribute has to be a valid JSON, was: '+ data[name]); } if(!bases){ bases = [true, {}]; } else if(!Array.isArray(bases)){ bases = [true, {}, bases]; } else { bases.unshift(true, {}); } if(data && typeof data[name] == 'object'){ bases.push(data[name]); } if(!regs[name]){ regs[name] = new RegExp('^'+ name +'([A-Z])'); } for(dataName in data){ if(regs[name].test(dataName)){ cfg[dataName.replace(regs[name], regFn)] = data[dataName]; } } bases.push(cfg); return elementData(elem, 'cfg'+name, $.extend.apply($, bases)); }; })(), //http://www.w3.org/TR/html5/common-dom-interfaces.html#reflect createPropDefault: createPropDefault, data: elementData, moveToFirstEvent: function(elem, eventType, bindType){ var events = ($._data(elem, 'events') || {})[eventType]; var fn; if(events && events.length > 1){ fn = events.pop(); if(!bindType){ bindType = 'bind'; } if(bindType == 'bind' && events.delegateCount){ events.splice( events.delegateCount, 0, fn); } else { events.unshift( fn ); } } elem = null; }, addShadowDom: (function(){ var resizeTimer; var lastHeight; var lastWidth; var $window = $(window); var docObserve = { init: false, runs: 0, test: function(){ var height = docObserve.getHeight(); var width = docObserve.getWidth(); if(height != docObserve.height || width != docObserve.width){ docObserve.height = height; docObserve.width = width; docObserve.handler({type: 'docresize'}); docObserve.runs++; if(docObserve.runs < 9){ setTimeout(docObserve.test, 90); } } else { docObserve.runs = 0; } }, handler: (function(){ var trigger = function(){ $(document).triggerHandler('updateshadowdom'); }; return function(e){ clearTimeout(resizeTimer); resizeTimer = setTimeout(function(){ if(e.type == 'resize'){ var width = $window.width(); var height = $window.width(); if(height == lastHeight && width == lastWidth){ return; } lastHeight = height; lastWidth = width; docObserve.height = docObserve.getHeight(); docObserve.width = docObserve.getWidth(); } if(window.requestAnimationFrame){ requestAnimationFrame(trigger); } else { setTimeout(trigger, 0); } }, (e.type == 'resize' && !window.requestAnimationFrame) ? 50 : 9); }; })(), _create: function(){ $.each({ Height: "getHeight", Width: "getWidth" }, function(name, type){ var body = document.body; var doc = document.documentElement; docObserve[type] = function (){ return Math.max( body[ "scroll" + name ], doc[ "scroll" + name ], body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); }; }); }, start: function(){ if(!this.init && document.body){ this.init = true; this._create(); this.height = docObserve.getHeight(); this.width = docObserve.getWidth(); setInterval(this.test, 999); $(this.test); if($.support.boxSizing == null){ $(function(){ if($.support.boxSizing){ docObserve.handler({type: 'boxsizing'}); } }); } webshims.ready('WINDOWLOAD', this.test); $(document).on('updatelayout.webshim pageinit popupafteropen panelbeforeopen tabsactivate collapsibleexpand shown.bs.modal shown.bs.collapse slid.bs.carousel', this.handler); $(window).on('resize', this.handler); } } }; webshims.docObserve = function(){ webshims.ready('DOM', function(){ docObserve.start(); }); }; return function(nativeElem, shadowElem, opts){ if(nativeElem && shadowElem){ opts = opts || {}; if(nativeElem.jquery){ nativeElem = nativeElem[0]; } if(shadowElem.jquery){ shadowElem = shadowElem[0]; } var nativeData = $.data(nativeElem, dataID) || $.data(nativeElem, dataID, {}); var shadowData = $.data(shadowElem, dataID) || $.data(shadowElem, dataID, {}); var shadowFocusElementData = {}; if(!opts.shadowFocusElement){ opts.shadowFocusElement = shadowElem; } else if(opts.shadowFocusElement){ if(opts.shadowFocusElement.jquery){ opts.shadowFocusElement = opts.shadowFocusElement[0]; } shadowFocusElementData = $.data(opts.shadowFocusElement, dataID) || $.data(opts.shadowFocusElement, dataID, shadowFocusElementData); } $(nativeElem).on('remove', function(e){ if (!e.originalEvent) { setTimeout(function(){ $(shadowElem).remove(); }, 4); } }); nativeData.hasShadow = shadowElem; shadowFocusElementData.nativeElement = shadowData.nativeElement = nativeElem; shadowFocusElementData.shadowData = shadowData.shadowData = nativeData.shadowData = { nativeElement: nativeElem, shadowElement: shadowElem, shadowFocusElement: opts.shadowFocusElement }; if(opts.shadowChilds){ opts.shadowChilds.each(function(){ elementData(this, 'shadowData', shadowData.shadowData); }); } if(opts.data){ shadowFocusElementData.shadowData.data = shadowData.shadowData.data = nativeData.shadowData.data = opts.data; } opts = null; } webshims.docObserve(); }; })(), propTypes: { standard: function(descs, name){ createPropDefault(descs); if(descs.prop){return;} descs.prop = { set: function(val){ descs.attr.set.call(this, ''+val); }, get: function(){ return descs.attr.get.call(this) || descs.defaultValue; } }; }, "boolean": function(descs, name){ createPropDefault(descs); if(descs.prop){return;} descs.prop = { set: function(val){ if(val){ descs.attr.set.call(this, ""); } else { descs.removeAttr.value.call(this); } }, get: function(){ return descs.attr.get.call(this) != null; } }; }, "src": (function(){ var anchor = document.createElement('a'); anchor.style.display = "none"; return function(descs, name){ createPropDefault(descs); if(descs.prop){return;} descs.prop = { set: function(val){ descs.attr.set.call(this, val); }, get: function(){ var href = this.getAttribute(name); var ret; if(href == null){return '';} anchor.setAttribute('href', href+'' ); if(!supportHrefNormalized){ try { $(anchor).insertAfter(this); ret = anchor.getAttribute('href', 4); } catch(er){ ret = anchor.getAttribute('href', 4); } $(anchor).detach(); } return ret || anchor.href; } }; }; })(), enumarated: function(descs, name){ createPropDefault(descs); if(descs.prop){return;} descs.prop = { set: function(val){ descs.attr.set.call(this, val); }, get: function(){ var val = (descs.attr.get.call(this) || '').toLowerCase(); if(!val || descs.limitedTo.indexOf(val) == -1){ val = descs.defaultValue; } return val; } }; } // ,unsignedLong: $.noop // ,"doubble": $.noop // ,"long": $.noop // ,tokenlist: $.noop // ,settableTokenlist: $.noop }, reflectProperties: function(nodeNames, props){ if(typeof props == 'string'){ props = props.split(listReg); } props.forEach(function(prop){ webshims.defineNodeNamesProperty(nodeNames, prop, { prop: { set: function(val){ $.attr(this, prop, val); }, get: function(){ return $.attr(this, prop) || ''; } } }); }); }, defineNodeNameProperty: function(nodeName, prop, descs){ havePolyfill[prop] = true; if(descs.reflect){ if(descs.propType && !webshims.propTypes[descs.propType]){ webshims.error('could not finde propType '+ descs.propType); } else { webshims.propTypes[descs.propType || 'standard'](descs, prop); } } ['prop', 'attr', 'removeAttr'].forEach(function(type){ var desc = descs[type]; if(desc){ if(type === 'prop'){ desc = $.extend({writeable: true}, desc); } else { desc = $.extend({}, desc, {writeable: true}); } extendQ[type](nodeName, prop, desc); if(nodeName != '*' && webshims.cfg.extendNative && type == 'prop' && desc.value && $.isFunction(desc.value)){ extendNativeValue(nodeName, prop, desc); } descs[type] = desc; } }); if(descs.initAttr){ initProp.content(nodeName, prop); } return descs; }, defineNodeNameProperties: function(name, descs, propType, _noTmpCache){ var olddesc; for(var prop in descs){ if(!_noTmpCache && descs[prop].initAttr){ initProp.createTmpCache(name); } if(propType){ if(descs[prop][propType]){ //webshims.log('override: '+ name +'['+prop +'] for '+ propType); } else { descs[prop][propType] = {}; ['value', 'set', 'get'].forEach(function(copyProp){ if(copyProp in descs[prop]){ descs[prop][propType][copyProp] = descs[prop][copyProp]; delete descs[prop][copyProp]; } }); } } descs[prop] = webshims.defineNodeNameProperty(name, prop, descs[prop]); } if(!_noTmpCache){ initProp.flushTmpCache(); } return descs; }, createElement: function(nodeName, create, descs){ var ret; if($.isFunction(create)){ create = { after: create }; } initProp.createTmpCache(nodeName); if(create.before){ initProp.createElement(nodeName, create.before); } if(descs){ ret = webshims.defineNodeNameProperties(nodeName, descs, false, true); } if(create.after){ initProp.createElement(nodeName, create.after); } initProp.flushTmpCache(); return ret; }, onNodeNamesPropertyModify: function(nodeNames, props, desc, only){ if(typeof nodeNames == 'string'){ nodeNames = nodeNames.split(listReg); } if($.isFunction(desc)){ desc = {set: desc}; } nodeNames.forEach(function(name){ if(!modifyProps[name]){ modifyProps[name] = {}; } if(typeof props == 'string'){ props = props.split(listReg); } if(desc.initAttr){ initProp.createTmpCache(name); } props.forEach(function(prop){ if(!modifyProps[name][prop]){ modifyProps[name][prop] = []; havePolyfill[prop] = true; } if(desc.set){ if(only){ desc.set.only = only; } modifyProps[name][prop].push(desc.set); } if(desc.initAttr){ initProp.content(name, prop); } }); initProp.flushTmpCache(); }); }, defineNodeNamesBooleanProperty: function(elementNames, prop, descs){ if(!descs){ descs = {}; } if($.isFunction(descs)){ descs.set = descs; } webshims.defineNodeNamesProperty(elementNames, prop, { attr: { set: function(val){ if(descs.useContentAttribute){ webshims.contentAttr(this, prop, val); } else { this.setAttribute(prop, val); } if(descs.set){ descs.set.call(this, true); } }, get: function(){ var ret = (descs.useContentAttribute) ? webshims.contentAttr(this, prop) : this.getAttribute(prop); return (ret == null) ? undefined : prop; } }, removeAttr: { value: function(){ this.removeAttribute(prop); if(descs.set){ descs.set.call(this, false); } } }, reflect: true, propType: 'boolean', initAttr: descs.initAttr || false }); }, contentAttr: function(elem, name, val){ if(!elem.nodeName){return;} var attr; if(val === undefined){ attr = (elem.attributes[name] || {}); val = attr.specified ? attr.value : null; return (val == null) ? undefined : val; } if(typeof val == 'boolean'){ if(!val){ elem.removeAttribute(name); } else { elem.setAttribute(name, name); } } else { elem.setAttribute(name, val); } }, activeLang: (function(){ var curLang = []; var langDatas = []; var loading = {}; var load = function(src, obj, loadingLang){ obj._isLoading = true; if(loading[src]){ loading[src].push(obj); } else { loading[src] = [obj]; webshims.loader.loadScript(src, function(){ if(loadingLang == curLang.join()){ $.each(loading[src], function(i, obj){ select(obj); }); } delete loading[src]; }); } }; var select = function(obj){ var oldLang = obj.__active; var selectLang = function(i, lang){ obj._isLoading = false; if(obj[lang] || obj.availableLangs.indexOf(lang) != -1){ if(obj[lang]){ obj.__active = obj[lang]; obj.__activeName = lang; } else { load(obj.langSrc+lang, obj, curLang.join()); } return false; } }; $.each(curLang, selectLang); if(!obj.__active){ obj.__active = obj['']; obj.__activeName = ''; } if(oldLang != obj.__active){ $(obj).trigger('change'); } }; return function(lang){ var shortLang; if(typeof lang == 'string'){ if(curLang[0] != lang){ curLang = [lang]; shortLang = curLang[0].split('-')[0]; if(shortLang && shortLang != lang){ curLang.push(shortLang); } langDatas.forEach(select); } } else if(typeof lang == 'object'){ if(!lang.__active){ langDatas.push(lang); select(lang); } return lang.__active; } return curLang[0]; }; })() }); $.each({ defineNodeNamesProperty: 'defineNodeNameProperty', defineNodeNamesProperties: 'defineNodeNameProperties', createElements: 'createElement' }, function(name, baseMethod){ webshims[name] = function(names, a, b, c){ if(typeof names == 'string'){ names = names.split(listReg); } var retDesc = {}; names.forEach(function(nodeName){ retDesc[nodeName] = webshims[baseMethod](nodeName, a, b, c); }); return retDesc; }; }); webshims.isReady('webshimLocalization', true); //html5a11y + hidden attribute (function(){ if(('content' in document.createElement('template'))){return;} $(function(){ var main = $('main').attr({role: 'main'}); if(main.length > 1){ webshims.error('only one main element allowed in document'); } else if(main.is('article *, section *')) { webshims.error('main not allowed inside of article/section elements'); } }); if(('hidden' in document.createElement('a'))){ return; } webshims.defineNodeNamesBooleanProperty(['*'], 'hidden'); var elemMappings = { article: "article", aside: "complementary", section: "region", nav: "navigation", address: "contentinfo" }; var addRole = function(elem, role){ var hasRole = elem.getAttribute('role'); if (!hasRole) { elem.setAttribute('role', role); } }; $.webshims.addReady(function(context, contextElem){ $.each(elemMappings, function(name, role){ var elems = $(name, context).add(contextElem.filter(name)); for (var i = 0, len = elems.length; i < len; i++) { addRole(elems[i], role); } }); if (context === document) { var header = document.getElementsByTagName('header')[0]; var footers = document.getElementsByTagName('footer'); var footerLen = footers.length; if (header && !$(header).closest('section, article')[0]) { addRole(header, 'banner'); } if (!footerLen) { return; } var footer = footers[footerLen - 1]; if (!$(footer).closest('section, article')[0]) { addRole(footer, 'contentinfo'); } } }); })(); }); ;(function(Modernizr, webshims){ "use strict"; var hasNative = Modernizr.audio && Modernizr.video; var supportsLoop = false; var bugs = webshims.bugs; var swfType = 'mediaelement-jaris'; var loadSwf = function(){ webshims.ready(swfType, function(){ if(!webshims.mediaelement.createSWF){ webshims.mediaelement.loadSwf = true; webshims.reTest([swfType], hasNative); } }); }; var wsCfg = webshims.cfg; var options = wsCfg.mediaelement; var isIE = navigator.userAgent.indexOf('MSIE') != -1; if(!options){ webshims.error("mediaelement wasn't implemented but loaded"); return; } if(hasNative){ var videoElem = document.createElement('video'); Modernizr.videoBuffered = ('buffered' in videoElem); Modernizr.mediaDefaultMuted = ('defaultMuted' in videoElem); supportsLoop = ('loop' in videoElem); Modernizr.mediaLoop = supportsLoop; webshims.capturingEvents(['play', 'playing', 'waiting', 'paused', 'ended', 'durationchange', 'loadedmetadata', 'canplay', 'volumechange']); if( !Modernizr.videoBuffered || !supportsLoop || (!Modernizr.mediaDefaultMuted && isIE && 'ActiveXObject' in window) ){ webshims.addPolyfill('mediaelement-native-fix', { d: ['dom-support'] }); webshims.loader.loadList(['mediaelement-native-fix']); } } if(Modernizr.track && !bugs.track){ (function(){ if(!bugs.track){ if(window.VTTCue && !window.TextTrackCue){ window.TextTrackCue = window.VTTCue; } else if(!window.VTTCue){ window.VTTCue = window.TextTrackCue; } try { new VTTCue(2, 3, ''); } catch(e){ bugs.track = true; } } })(); } webshims.register('mediaelement-core', function($, webshims, window, document, undefined, options){ var hasSwf = swfmini.hasFlashPlayerVersion('10.0.3'); var mediaelement = webshims.mediaelement; mediaelement.parseRtmp = function(data){ var src = data.src.split('://'); var paths = src[1].split('/'); var i, len, found; data.server = src[0]+'://'+paths[0]+'/'; data.streamId = []; for(i = 1, len = paths.length; i < len; i++){ if(!found && paths[i].indexOf(':') !== -1){ paths[i] = paths[i].split(':')[1]; found = true; } if(!found){ data.server += paths[i]+'/'; } else { data.streamId.push(paths[i]); } } if(!data.streamId.length){ webshims.error('Could not parse rtmp url'); } data.streamId = data.streamId.join('/'); }; var getSrcObj = function(elem, nodeName){ elem = $(elem); var src = {src: elem.attr('src') || '', elem: elem, srcProp: elem.prop('src')}; var tmp; if(!src.src){return src;} tmp = elem.attr('data-server'); if(tmp != null){ src.server = tmp; } tmp = elem.attr('type') || elem.attr('data-type'); if(tmp){ src.type = tmp; src.container = $.trim(tmp.split(';')[0]); } else { if(!nodeName){ nodeName = elem[0].nodeName.toLowerCase(); if(nodeName == 'source'){ nodeName = (elem.closest('video, audio')[0] || {nodeName: 'video'}).nodeName.toLowerCase(); } } if(src.server){ src.type = nodeName+'/rtmp'; src.container = nodeName+'/rtmp'; } else { tmp = mediaelement.getTypeForSrc( src.src, nodeName, src ); if(tmp){ src.type = tmp; src.container = tmp; } } } tmp = elem.attr('media'); if(tmp){ src.media = tmp; } if(src.type == 'audio/rtmp' || src.type == 'video/rtmp'){ if(src.server){ src.streamId = src.src; } else { mediaelement.parseRtmp(src); } } return src; }; var hasYt = !hasSwf && ('postMessage' in window) && hasNative; var loadTrackUi = function(){ if(loadTrackUi.loaded){return;} loadTrackUi.loaded = true; if(!options.noAutoTrack){ webshims.ready('WINDOWLOAD', function(){ loadThird(); webshims.loader.loadList(['track-ui']); }); } }; var loadYt = (function(){ var loaded; return function(){ if(loaded || !hasYt){return;} loaded = true; webshims.loader.loadScript("https://www.youtube.com/player_api"); $(function(){ webshims._polyfill(["mediaelement-yt"]); }); }; })(); var loadThird = function(){ if(hasSwf){ loadSwf(); } else { loadYt(); } }; webshims.addPolyfill('mediaelement-yt', { test: !hasYt, d: ['dom-support'] }); mediaelement.mimeTypes = { audio: { //ogm shouldn´t be used! 'audio/ogg': ['ogg','oga', 'ogm'], 'audio/ogg;codecs="opus"': 'opus', 'audio/mpeg': ['mp2','mp3','mpga','mpega'], 'audio/mp4': ['mp4','mpg4', 'm4r', 'm4a', 'm4p', 'm4b', 'aac'], 'audio/wav': ['wav'], 'audio/3gpp': ['3gp','3gpp'], 'audio/webm': ['webm'], 'audio/fla': ['flv', 'f4a', 'fla'], 'application/x-mpegURL': ['m3u8', 'm3u'] }, video: { //ogm shouldn´t be used! 'video/ogg': ['ogg','ogv', 'ogm'], 'video/mpeg': ['mpg','mpeg','mpe'], 'video/mp4': ['mp4','mpg4', 'm4v'], 'video/quicktime': ['mov','qt'], 'video/x-msvideo': ['avi'], 'video/x-ms-asf': ['asf', 'asx'], 'video/flv': ['flv', 'f4v'], 'video/3gpp': ['3gp','3gpp'], 'video/webm': ['webm'], 'application/x-mpegURL': ['m3u8', 'm3u'], 'video/MP2T': ['ts'] } } ; mediaelement.mimeTypes.source = $.extend({}, mediaelement.mimeTypes.audio, mediaelement.mimeTypes.video); mediaelement.getTypeForSrc = function(src, nodeName){ if(src.indexOf('youtube.com/watch?') != -1 || src.indexOf('youtube.com/v/') != -1){ return 'video/youtube'; } if(src.indexOf('rtmp') === 0){ return nodeName+'/rtmp'; } src = src.split('?')[0].split('#')[0].split('.'); src = src[src.length - 1]; var mt; $.each(mediaelement.mimeTypes[nodeName], function(mimeType, exts){ if(exts.indexOf(src) !== -1){ mt = mimeType; return false; } }); return mt; }; mediaelement.srces = function(mediaElem, srces){ mediaElem = $(mediaElem); if(!srces){ srces = []; var nodeName = mediaElem[0].nodeName.toLowerCase(); var src = getSrcObj(mediaElem, nodeName); if(!src.src){ $('source', mediaElem).each(function(){ src = getSrcObj(this, nodeName); if(src.src){srces.push(src);} }); } else { srces.push(src); } return srces; } else { webshims.error('setting sources was removed.'); } }; mediaelement.swfMimeTypes = ['video/3gpp', 'video/x-msvideo', 'video/quicktime', 'video/x-m4v', 'video/mp4', 'video/m4p', 'video/x-flv', 'video/flv', 'audio/mpeg', 'audio/aac', 'audio/mp4', 'audio/x-m4a', 'audio/m4a', 'audio/mp3', 'audio/x-fla', 'audio/fla', 'youtube/flv', 'video/jarisplayer', 'jarisplayer/jarisplayer', 'video/youtube', 'video/rtmp', 'audio/rtmp']; mediaelement.canThirdPlaySrces = function(mediaElem, srces){ var ret = ''; if(hasSwf || hasYt){ mediaElem = $(mediaElem); srces = srces || mediaelement.srces(mediaElem); $.each(srces, function(i, src){ if(src.container && src.src && ((hasSwf && mediaelement.swfMimeTypes.indexOf(src.container) != -1) || (hasYt && src.container == 'video/youtube'))){ ret = src; return false; } }); } return ret; }; var nativeCanPlayType = {}; mediaelement.canNativePlaySrces = function(mediaElem, srces){ var ret = ''; if(hasNative){ mediaElem = $(mediaElem); var nodeName = (mediaElem[0].nodeName || '').toLowerCase(); var nativeCanPlay = (nativeCanPlayType[nodeName] || {prop: {_supvalue: false}}).prop._supvalue || mediaElem[0].canPlayType; if(!nativeCanPlay){return ret;} srces = srces || mediaelement.srces(mediaElem); $.each(srces, function(i, src){ if(src.type && nativeCanPlay.call(mediaElem[0], src.type) ){ ret = src; return false; } }); } return ret; }; var emptyType = (/^\s*application\/octet\-stream\s*$/i); var getRemoveEmptyType = function(){ var ret = emptyType.test($.attr(this, 'type') || ''); if(ret){ $(this).removeAttr('type'); } return ret; }; mediaelement.setError = function(elem, message){ if($('source', elem).filter(getRemoveEmptyType).length){ webshims.error('"application/octet-stream" is a useless mimetype for audio/video. Please change this attribute.'); try { $(elem).mediaLoad(); } catch(er){} } else { if(!message){ message = "can't play sources"; } $(elem).pause().data('mediaerror', message); webshims.error('mediaelementError: '+ message +'. Run the following line in your console to get more info: webshim.mediaelement.loadDebugger();'); setTimeout(function(){ if($(elem).data('mediaerror')){ $(elem).addClass('media-error').trigger('mediaerror'); } }, 1); } }; var handleThird = (function(){ var requested; var readyType = hasSwf ? swfType : 'mediaelement-yt'; return function( mediaElem, ret, data ){ //readd to ready webshims.ready(readyType, function(){ if(mediaelement.createSWF && $(mediaElem).parent()[0]){ mediaelement.createSWF( mediaElem, ret, data ); } else if(!requested) { requested = true; loadThird(); handleThird( mediaElem, ret, data ); } }); if(!requested && hasYt && !mediaelement.createSWF){ loadYt(); } }; })(); var activate = { native: function(elem, src, data){ if(data && data.isActive == 'third') { mediaelement.setActive(elem, 'html5', data); } }, third: handleThird }; var stepSources = function(elem, data, srces){ var i, src; var testOrder = [{test: 'canNativePlaySrces', activate: 'native'}, {test: 'canThirdPlaySrces', activate: 'third'}]; if(options.preferFlash || (data && data.isActive == 'third') ){ testOrder.reverse(); } for(i = 0; i < 2; i++){ src = mediaelement[testOrder[i].test](elem, srces); if(src){ activate[testOrder[i].activate](elem, src, data); break; } } if(!src){ mediaelement.setError(elem, false); if(data && data.isActive == 'third') { mediaelement.setActive(elem, 'html5', data); } } }; var allowedPreload = {'metadata': 1, 'auto': 1, '': 1}; var fixPreload = function(elem){ var preload, img; if(elem.getAttribute('preload') == 'none'){ if(allowedPreload[(preload = $.attr(elem, 'data-preload'))]){ $.attr(elem, 'preload', preload); } else if(hasNative && (preload = elem.getAttribute('poster'))){ img = document.createElement('img'); img.src = preload; } } }; var stopParent = /^(?:embed|object|datalist)$/i; var selectSource = function(elem, data){ var baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {}); var _srces = mediaelement.srces(elem); var parent = elem.parentNode; clearTimeout(baseData.loadTimer); $(elem).removeClass('media-error'); $.data(elem, 'mediaerror', false); if(!_srces.length || !parent || parent.nodeType != 1 || stopParent.test(parent.nodeName || '')){return;} data = data || webshims.data(elem, 'mediaelement'); if(mediaelement.sortMedia){ _srces.sort(mediaelement.sortMedia); } fixPreload(elem); stepSources(elem, data, _srces); }; mediaelement.selectSource = selectSource; $(document).on('ended', function(e){ var data = webshims.data(e.target, 'mediaelement'); if( supportsLoop && (!data || data.isActive == 'html5') && !$.prop(e.target, 'loop')){return;} setTimeout(function(){ if( $.prop(e.target, 'paused') || !$.prop(e.target, 'loop') ){return;} $(e.target).prop('currentTime', 0).play(); }); }); var handleMedia = false; var initMediaElements = function(){ var testFixMedia = function(){ if(webshims.implement(this, 'mediaelement')){ selectSource(this); if(!Modernizr.mediaDefaultMuted && $.attr(this, 'muted') != null){ $.prop(this, 'muted', true); } } }; webshims.ready('dom-support', function(){ handleMedia = true; if(!supportsLoop){ webshims.defineNodeNamesBooleanProperty(['audio', 'video'], 'loop'); } ['audio', 'video'].forEach(function(nodeName){ var supLoad; supLoad = webshims.defineNodeNameProperty(nodeName, 'load', { prop: { value: function(){ var data = webshims.data(this, 'mediaelement'); selectSource(this, data); if(hasNative && (!data || data.isActive == 'html5') && supLoad.prop._supvalue){ supLoad.prop._supvalue.apply(this, arguments); } if(!loadTrackUi.loaded && $('track', this).length){ loadTrackUi(); } $(this).triggerHandler('wsmediareload'); } } }); nativeCanPlayType[nodeName] = webshims.defineNodeNameProperty(nodeName, 'canPlayType', { prop: { value: function(type){ var ret = ''; if(hasNative && nativeCanPlayType[nodeName].prop._supvalue){ ret = nativeCanPlayType[nodeName].prop._supvalue.call(this, type); if(ret == 'no'){ ret = ''; } } if(!ret && hasSwf){ type = $.trim((type || '').split(';')[0]); if(mediaelement.swfMimeTypes.indexOf(type) != -1){ ret = 'maybe'; } } if(!ret && hasYt && type == 'video/youtube'){ ret = 'maybe'; } return ret; } } }); }); webshims.onNodeNamesPropertyModify(['audio', 'video'], ['src', 'poster'], { set: function(){ var elem = this; var baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {}); clearTimeout(baseData.loadTimer); baseData.loadTimer = setTimeout(function(){ selectSource(elem); elem = null; }, 9); } }); webshims.addReady(function(context, insertedElement){ var media = $('video, audio', context) .add(insertedElement.filter('video, audio')) .each(testFixMedia) ; if(!loadTrackUi.loaded && $('track', media).length){ loadTrackUi(); } media = null; }); }); if(hasNative && !handleMedia){ webshims.addReady(function(context, insertedElement){ if(!handleMedia){ $('video, audio', context) .add(insertedElement.filter('video, audio')) .each(function(){ if(!mediaelement.canNativePlaySrces(this)){ loadThird(); handleMedia = true; return false; } }) ; } }); } }; mediaelement.loadDebugger = function(){ webshims.ready('dom-support', function(){ webshims.loader.loadScript('mediaelement-debug'); }); }; if(webshims.cfg.debug){ $(document).on('mediaerror', function(e){ mediaelement.loadDebugger(); }); } //set native implementation ready, before swf api is retested if(hasNative){ webshims.isReady('mediaelement-core', true); initMediaElements(); webshims.ready('WINDOWLOAD mediaelement', loadThird); } else { webshims.ready(swfType, initMediaElements); } webshims.ready('track', loadTrackUi); }); })(Modernizr, webshims); ;webshims.register('mediaelement-jaris', function($, webshims, window, document, undefined, options){ "use strict"; var mediaelement = webshims.mediaelement; var swfmini = window.swfmini; var hasNative = Modernizr.audio && Modernizr.video; var hasFlash = swfmini.hasFlashPlayerVersion('9.0.115'); var loadedSwf = 0; var needsLoadPreload = 'ActiveXObject' in window && hasNative; var getProps = { paused: true, ended: false, currentSrc: '', duration: window.NaN, readyState: 0, networkState: 0, videoHeight: 0, videoWidth: 0, seeking: false, error: null, buffered: { start: function(index){ if(index){ webshims.error('buffered index size error'); return; } return 0; }, end: function(index){ if(index){ webshims.error('buffered index size error'); return; } return 0; }, length: 0 } }; var getPropKeys = Object.keys(getProps); var getSetProps = { currentTime: 0, volume: 1, muted: false }; var getSetPropKeys = Object.keys(getSetProps); var playerStateObj = $.extend({ isActive: 'html5', activating: 'html5', wasSwfReady: false, _bufferedEnd: 0, _bufferedStart: 0, currentTime: 0, _ppFlag: undefined, _calledMeta: false, lastDuration: 0 }, getProps, getSetProps); var getSwfDataFromElem = function(elem){ try { (elem.nodeName); } catch(er){ return null; } var data = webshims.data(elem, 'mediaelement'); return (data && data.isActive== 'third') ? data : null; }; var trigger = function(elem, evt){ evt = $.Event(evt); evt.preventDefault(); $.event.trigger(evt, undefined, elem); }; var playerSwfPath = options.playerPath || webshims.cfg.basePath + "swf/" + (options.playerName || 'JarisFLVPlayer.swf'); webshims.extendUNDEFProp(options.params, { allowscriptaccess: 'always', allowfullscreen: 'true', wmode: 'transparent', allowNetworking: 'all' }); webshims.extendUNDEFProp(options.vars, { controltype: '1', jsapi: '1' }); webshims.extendUNDEFProp(options.attrs, { bgcolor: '#000000' }); var setReadyState = function(readyState, data){ if(readyState < 3){ clearTimeout(data._canplaythroughTimer); } if(readyState >= 3 && data.readyState < 3){ data.readyState = readyState; trigger(data._elem, 'canplay'); if(!data.paused){ trigger(data._elem, 'playing'); } clearTimeout(data._canplaythroughTimer); data._canplaythroughTimer = setTimeout(function(){ setReadyState(4, data); }, 4000); } if(readyState >= 4 && data.readyState < 4){ data.readyState = readyState; trigger(data._elem, 'canplaythrough'); } data.readyState = readyState; }; var callSeeked = function(data){ if(data.seeking && Math.abs(data.currentTime - data._lastSeektime) < 2){ data.seeking = false; $(data._elem).triggerHandler('seeked'); } }; mediaelement.jarisEvent = {}; var localConnectionTimer; var onEvent = { onPlayPause: function(jaris, data, override){ var playing, type; if(override == null){ try { playing = data.api.api_get("isPlaying"); } catch(e){} } else { playing = override; } if(playing == data.paused){ data.paused = !playing; type = data.paused ? 'pause' : 'play'; data._ppFlag = true; trigger(data._elem, type); if(data.readyState < 3){ setReadyState(3, data); } if(!data.paused){ trigger(data._elem, 'playing'); } } }, onSeek: function(jaris, data){ data._lastSeektime = jaris.seekTime; data.seeking = true; $(data._elem).triggerHandler('seeking'); clearTimeout(data._seekedTimer); data._seekedTimer = setTimeout(function(){ callSeeked(data); data.seeking = false; }, 300); }, onConnectionFailed: function(jaris, data){ mediaelement.setError(data._elem, 'flash connection error'); }, onNotBuffering: function(jaris, data){ setReadyState(3, data); }, onDataInitialized: function(jaris, data){ var oldDur = data.duration; var durDelta; data.duration = jaris.duration; if(oldDur == data.duration || isNaN(data.duration)){return;} if(data._calledMeta && ((durDelta = Math.abs(data.lastDuration - data.duration)) < 2)){return;} data.videoHeight = jaris.height; data.videoWidth = jaris.width; if(!data.networkState){ data.networkState = 2; } if(data.readyState < 1){ setReadyState(1, data); } clearTimeout(data._durationChangeTimer); if(data._calledMeta && data.duration){ data._durationChangeTimer = setTimeout(function(){ data.lastDuration = data.duration; trigger(data._elem, 'durationchange'); }, durDelta > 50 ? 0 : durDelta > 9 ? 9 : 99); } else { data.lastDuration = data.duration; if(data.duration){ trigger(data._elem, 'durationchange'); } if(!data._calledMeta){ trigger(data._elem, 'loadedmetadata'); } } data._calledMeta = true; }, onBuffering: function(jaris, data){ if(data.ended){ data.ended = false; } setReadyState(1, data); trigger(data._elem, 'waiting'); }, onTimeUpdate: function(jaris, data){ if(data.ended){ data.ended = false; } if(data.readyState < 3){ setReadyState(3, data); trigger(data._elem, 'playing'); } if(data.seeking){ callSeeked(data); } trigger(data._elem, 'timeupdate'); }, onProgress: function(jaris, data){ if(data.ended){ data.ended = false; } if(!data.duration || isNaN(data.duration)){ return; } var percentage = jaris.loaded / jaris.total; if(percentage > 0.02 && percentage < 0.2){ setReadyState(3, data); } else if(percentage > 0.2){ if(percentage > 0.99){ data.networkState = 1; } setReadyState(4, data); } if(data._bufferedEnd && (data._bufferedEnd > percentage)){ data._bufferedStart = data.currentTime || 0; } data._bufferedEnd = percentage; data.buffered.length = 1; $.event.trigger('progress', undefined, data._elem, true); }, onPlaybackFinished: function(jaris, data){ if(data.readyState < 4){ setReadyState(4, data); } data.ended = true; trigger(data._elem, 'ended'); }, onVolumeChange: function(jaris, data){ if(data.volume != jaris.volume || data.muted != jaris.mute){ data.volume = jaris.volume; data.muted = jaris.mute; trigger(data._elem, 'volumechange'); } }, ready: (function(){ var testAPI = function(data){ var passed = true; try { data.api.api_get('volume'); } catch(er){ passed = false; } return passed; }; return function(jaris, data){ var i = 0; var doneFn = function(){ if(i > 9){ data.tryedReframeing = 0; return; } i++; data.tryedReframeing++; if(testAPI(data)){ data.wasSwfReady = true; data.tryedReframeing = 0; startAutoPlay(data); workActionQueue(data); } else if(data.tryedReframeing < 6) { if(data.tryedReframeing < 3){ data.reframeTimer = setTimeout(doneFn, 9); data.shadowElem.css({overflow: 'visible'}); setTimeout(function(){ data.shadowElem.css({overflow: 'hidden'}); }, 1); } else { data.shadowElem.css({overflow: 'hidden'}); $(data._elem).mediaLoad(); } } else { clearTimeout(data.reframeTimer); webshims.error("reframing error"); } }; if(!data || !data.api){return;} if(!data.tryedReframeing){ data.tryedReframeing = 0; } clearTimeout(localConnectionTimer); clearTimeout(data.reframeTimer); data.shadowElem.removeClass('flashblocker-assumed'); if(!i){ doneFn(); } else { data.reframeTimer = setTimeout(doneFn, 9); } }; })() }; onEvent.onMute = onEvent.onVolumeChange; var workActionQueue = function(data){ var actionLen = data.actionQueue.length; var i = 0; var operation; if(actionLen && data.isActive == 'third'){ while(data.actionQueue.length && actionLen > i){ i++; operation = data.actionQueue.shift(); try{ data.api[operation.fn].apply(data.api, operation.args); } catch(er){ webshims.warn(er); } } } if(data.actionQueue.length){ data.actionQueue = []; } }; var startAutoPlay = function(data){ if(!data){return;} if( (data._ppFlag === undefined && ($.prop(data._elem, 'autoplay')) || !data.paused)){ setTimeout(function(){ if(data.isActive == 'third' && (data._ppFlag === undefined || !data.paused)){ try { $(data._elem).play(); data._ppFlag = true; } catch(er){} } }, 1); } if(data.muted){ $.prop(data._elem, 'muted', true); } if(data.volume != 1){ $.prop(data._elem, 'volume', data.volume); } }; var addMediaToStopEvents = $.noop; if(hasNative){ var stopEvents = { play: 1, playing: 1 }; var hideEvtArray = ['play', 'pause', 'playing', 'canplay', 'progress', 'waiting', 'ended', 'loadedmetadata', 'durationchange', 'emptied']; var hidevents = hideEvtArray.map(function(evt){ return evt +'.webshimspolyfill'; }).join(' '); var hidePlayerEvents = function(event){ var data = webshims.data(event.target, 'mediaelement'); if(!data){return;} var isNativeHTML5 = ( event.originalEvent && event.originalEvent.type === event.type ); if( isNativeHTML5 == (data.activating == 'third') ){ event.stopImmediatePropagation(); if(stopEvents[event.type]){ if(data.isActive != data.activating){ $(event.target).pause(); } else if(isNativeHTML5){ ($.prop(event.target, 'pause')._supvalue || $.noop).apply(event.target); } } } }; addMediaToStopEvents = function(elem){ $(elem) .off(hidevents) .on(hidevents, hidePlayerEvents) ; hideEvtArray.forEach(function(evt){ webshims.moveToFirstEvent(elem, evt); }); }; addMediaToStopEvents(document); } mediaelement.setActive = function(elem, type, data){ if(!data){ data = webshims.data(elem, 'mediaelement'); } if(!data || data.isActive == type){return;} if(type != 'html5' && type != 'third'){ webshims.warn('wrong type for mediaelement activating: '+ type); } var shadowData = webshims.data(elem, 'shadowData'); data.activating = type; $(elem).pause(); data.isActive = type; if(type == 'third'){ shadowData.shadowElement = shadowData.shadowFocusElement = data.shadowElem[0]; $(elem).addClass('swf-api-active nonnative-api-active').hide().getShadowElement().show(); } else { $(elem).removeClass('swf-api-active nonnative-api-active').show().getShadowElement().hide(); shadowData.shadowElement = shadowData.shadowFocusElement = false; } $(elem).trigger('mediaelementapichange'); }; var resetSwfProps = (function(){ var resetProtoProps = ['_calledMeta', 'lastDuration', '_bufferedEnd', '_bufferedStart', '_ppFlag', 'currentSrc', 'currentTime', 'duration', 'ended', 'networkState', 'paused', 'seeking', 'videoHeight', 'videoWidth']; var len = resetProtoProps.length; return function(data){ if(!data){return;} clearTimeout(data._seekedTimer); var lenI = len; var networkState = data.networkState; setReadyState(0, data); clearTimeout(data._durationChangeTimer); while(--lenI > -1){ delete data[resetProtoProps[lenI]]; } data.actionQueue = []; data.buffered.length = 0; if(networkState){ trigger(data._elem, 'emptied'); } }; })(); var getComputedDimension = (function(){ var dimCache = {}; var getVideoDims = function(data){ var ret, poster, img; if(dimCache[data.currentSrc]){ ret = dimCache[data.currentSrc]; } else if(data.videoHeight && data.videoWidth){ dimCache[data.currentSrc] = { width: data.videoWidth, height: data.videoHeight }; ret = dimCache[data.currentSrc]; } else if((poster = $.attr(data._elem, 'poster'))){ ret = dimCache[poster]; if(!ret){ img = document.createElement('img'); img.onload = function(){ dimCache[poster] = { width: this.width, height: this.height }; if(dimCache[poster].height && dimCache[poster].width){ setElementDimension(data, $.prop(data._elem, 'controls')); } else { delete dimCache[poster]; } img.onload = null; }; img.src = poster; if(img.complete && img.onload){ img.onload(); } } } return ret || {width: 300, height: data._elemNodeName == 'video' ? 150 : 50}; }; var getCssStyle = function(elem, style){ return elem.style[style] || (elem.currentStyle && elem.currentStyle[style]) || (window.getComputedStyle && (window.getComputedStyle( elem, null ) || {} )[style]) || ''; }; var minMaxProps = ['minWidth', 'maxWidth', 'minHeight', 'maxHeight']; var addMinMax = function(elem, ret){ var i, prop; var hasMinMax = false; for (i = 0; i < 4; i++) { prop = getCssStyle(elem, minMaxProps[i]); if(parseFloat(prop, 10)){ hasMinMax = true; ret[minMaxProps[i]] = prop; } } return hasMinMax; }; var retFn = function(data){ var videoDims, ratio, hasMinMax; var elem = data._elem; var autos = { width: getCssStyle(elem, 'width') == 'auto', height: getCssStyle(elem, 'height') == 'auto' }; var ret = { width: !autos.width && $(elem).width(), height: !autos.height && $(elem).height() }; if(autos.width || autos.height){ videoDims = getVideoDims(data); ratio = videoDims.width / videoDims.height; if(autos.width && autos.height){ ret.width = videoDims.width; ret.height = videoDims.height; } else if(autos.width){ ret.width = ret.height * ratio; } else if(autos.height){ ret.height = ret.width / ratio; } if(addMinMax(elem, ret)){ data.shadowElem.css(ret); if(autos.width){ ret.width = data.shadowElem.height() * ratio; } if(autos.height){ ret.height = ((autos.width) ? ret.width : data.shadowElem.width()) / ratio; } if(autos.width && autos.height){ data.shadowElem.css(ret); ret.height = data.shadowElem.width() / ratio; ret.width = ret.height * ratio; data.shadowElem.css(ret); ret.width = data.shadowElem.height() * ratio; ret.height = ret.width / ratio; } if(!Modernizr.video){ ret.width = data.shadowElem.width(); ret.height = data.shadowElem.height(); } } } return ret; }; return retFn; })(); var setElementDimension = function(data, hasControls){ var dims; var box = data.shadowElem; $(data._elem)[hasControls ? 'addClass' : 'removeClass']('webshims-controls'); if(data.isActive == 'third' || data.activating == 'third'){ if(data._elemNodeName == 'audio' && !hasControls){ box.css({width: 0, height: 0}); } else { data._elem.style.display = ''; dims = getComputedDimension(data); data._elem.style.display = 'none'; box.css(dims); } } }; var bufferSrc = (function(){ var preloads = { '': 1, 'auto': 1 }; return function(elem){ var preload = $.attr(elem, 'preload'); if(preload == null || preload == 'none' || $.prop(elem, 'autoplay')){ return false; } preload = $.prop(elem, 'preload'); return !!(preloads[preload] || (preload == 'metadata' && $(elem).is('.preload-in-doubt, video:not([poster])'))); }; })(); var regs = { A: /&amp;/g, a: /&/g, e: /\=/g, q: /\?/g }, replaceVar = function(val){ return (val.replace) ? val.replace(regs.A, '%26').replace(regs.a, '%26').replace(regs.e, '%3D').replace(regs.q, '%3F') : val; }; if('matchMedia' in window){ var allowMediaSorting = false; try { allowMediaSorting = window.matchMedia('only all').matches; } catch(er){} if(allowMediaSorting){ mediaelement.sortMedia = function(src1, src2){ try { src1 = !src1.media || matchMedia( src1.media ).matches; src2 = !src2.media || matchMedia( src2.media ).matches; } catch(er){ return 0; } return src1 == src2 ? 0 : src1 ? -1 : 1; }; } } mediaelement.createSWF = function( elem, canPlaySrc, data ){ if(!hasFlash){ setTimeout(function(){ $(elem).mediaLoad(); //<- this should produce a mediaerror }, 1); return; } var attrStyle = {}; if(loadedSwf < 1){ loadedSwf = 1; } else { loadedSwf++; } if(!data){ data = webshims.data(elem, 'mediaelement'); } if((attrStyle.height = $.attr(elem, 'height') || '') || (attrStyle.width = $.attr(elem, 'width') || '')){ $(elem).css(attrStyle); webshims.warn("width or height content attributes used. Webshims prefers the usage of CSS (computed styles or inline styles) to detect size of a video/audio. It's really more powerfull."); } var isRtmp = canPlaySrc.type == 'audio/rtmp' || canPlaySrc.type == 'video/rtmp'; var vars = $.extend({}, options.vars, { poster: replaceVar($.attr(elem, 'poster') && $.prop(elem, 'poster') || ''), source: replaceVar(canPlaySrc.streamId || canPlaySrc.srcProp), server: replaceVar(canPlaySrc.server || '') }); var elemVars = $(elem).data('vars') || {}; var hasControls = $.prop(elem, 'controls'); var elemId = 'jarisplayer-'+ webshims.getID(elem); var params = $.extend( {}, options.params, $(elem).data('params') ); var elemNodeName = elem.nodeName.toLowerCase(); var attrs = $.extend( {}, options.attrs, { name: elemId, id: elemId }, $(elem).data('attrs') ); var setDimension = function(){ if(data.isActive == 'third'){ setElementDimension(data, $.prop(elem, 'controls')); } }; var box; if(data && data.swfCreated){ mediaelement.setActive(elem, 'third', data); data.currentSrc = canPlaySrc.srcProp; data.shadowElem.html('<div id="'+ elemId +'">'); data.api = false; data.actionQueue = []; box = data.shadowElem; resetSwfProps(data); } else { $(document.getElementById('wrapper-'+ elemId )).remove(); box = $('<div class="polyfill-'+ (elemNodeName) +' polyfill-mediaelement '+ webshims.shadowClass +'" id="wrapper-'+ elemId +'"><div id="'+ elemId +'"></div>') .css({ position: 'relative', overflow: 'hidden' }) ; data = webshims.data(elem, 'mediaelement', webshims.objectCreate(playerStateObj, { actionQueue: { value: [] }, shadowElem: { value: box }, _elemNodeName: { value: elemNodeName }, _elem: { value: elem }, currentSrc: { value: canPlaySrc.srcProp }, swfCreated: { value: true }, id: { value: elemId.replace(/-/g, '') }, buffered: { value: { start: function(index){ if(index >= data.buffered.length){ webshims.error('buffered index size error'); return; } return 0; }, end: function(index){ if(index >= data.buffered.length){ webshims.error('buffered index size error'); return; } return ( (data.duration - data._bufferedStart) * data._bufferedEnd) + data._bufferedStart; }, length: 0 } } })); box.insertBefore(elem); if(hasNative){ $.extend(data, {volume: $.prop(elem, 'volume'), muted: $.prop(elem, 'muted'), paused: $.prop(elem, 'paused')}); } webshims.addShadowDom(elem, box); if(!webshims.data(elem, 'mediaelement')){ webshims.data(elem, 'mediaelement', data); } addMediaToStopEvents(elem); mediaelement.setActive(elem, 'third', data); setElementDimension(data, hasControls); $(elem) .on({ 'updatemediaelementdimensions loadedmetadata emptied': setDimension, 'remove': function(e){ if(!e.originalEvent && mediaelement.jarisEvent[data.id] && mediaelement.jarisEvent[data.id].elem == elem){ delete mediaelement.jarisEvent[data.id]; clearTimeout(localConnectionTimer); clearTimeout(data.flashBlock); } } }) .onWSOff('updateshadowdom', setDimension) ; } if(mediaelement.jarisEvent[data.id] && mediaelement.jarisEvent[data.id].elem != elem){ webshims.error('something went wrong'); return; } else if(!mediaelement.jarisEvent[data.id]){ mediaelement.jarisEvent[data.id] = function(jaris){ if(jaris.type == 'ready'){ var onReady = function(){ if(data.api){ if(!data.paused){ data.api.api_play(); } if(bufferSrc(elem)){ data.api.api_preload(); } onEvent.ready(jaris, data); } }; if(data.api){ onReady(); } else { setTimeout(onReady, 9); } } else { data.currentTime = jaris.position; if(data.api){ if(!data._calledMeta && isNaN(jaris.duration) && data.duration != jaris.duration && isNaN(data.duration)){ onEvent.onDataInitialized(jaris, data); } if(!data._ppFlag && jaris.type != 'onPlayPause'){ onEvent.onPlayPause(jaris, data); } if(onEvent[jaris.type]){ onEvent[jaris.type](jaris, data); } } data.duration = jaris.duration; } }; mediaelement.jarisEvent[data.id].elem = elem; } $.extend(vars, { id: elemId, evtId: data.id, controls: ''+hasControls, autostart: 'false', nodename: elemNodeName }, elemVars ); if(isRtmp){ vars.streamtype = 'rtmp'; } else if(canPlaySrc.type == 'audio/mpeg' || canPlaySrc.type == 'audio/mp3'){ vars.type = 'audio'; vars.streamtype = 'file'; } else if(canPlaySrc.type == 'video/youtube'){ vars.streamtype = 'youtube'; } options.changeSWF(vars, elem, canPlaySrc, data, 'embed'); clearTimeout(data.flashBlock); swfmini.embedSWF(playerSwfPath, elemId, "100%", "100%", "9.0.115", false, vars, params, attrs, function(swfData){ if(swfData.success){ var fBlocker = function(){ if((!swfData.ref.parentNode && box[0].parentNode) || swfData.ref.style.display == "none"){ box.addClass('flashblocker-assumed'); $(elem).trigger('flashblocker'); webshims.warn("flashblocker assumed"); } $(swfData.ref).css({'minHeight': '2px', 'minWidth': '2px', display: 'block'}); }; data.api = swfData.ref; if(!hasControls){ $(swfData.ref).attr('tabindex', '-1').css('outline', 'none'); } data.flashBlock = setTimeout(fBlocker, 99); if(!localConnectionTimer){ clearTimeout(localConnectionTimer); localConnectionTimer = setTimeout(function(){ fBlocker(); var flash = $(swfData.ref); if(flash[0].offsetWidth > 1 && flash[0].offsetHeight > 1 && location.protocol.indexOf('file:') === 0){ webshims.error("Add your local development-directory to the local-trusted security sandbox: http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html"); } else if(flash[0].offsetWidth < 2 || flash[0].offsetHeight < 2) { webshims.warn("JS-SWF connection can't be established on hidden or unconnected flash objects"); } flash = null; }, 8000); } } }); }; var queueSwfMethod = function(elem, fn, args, data){ data = data || getSwfDataFromElem(elem); if(data){ if(data.api && data.api[fn]){ data.api[fn].apply(data.api, args || []); } else { //todo add to queue data.actionQueue.push({fn: fn, args: args}); if(data.actionQueue.length > 10){ setTimeout(function(){ if(data.actionQueue.length > 5){ data.actionQueue.shift(); } }, 99); } } return data; } return false; }; ['audio', 'video'].forEach(function(nodeName){ var descs = {}; var mediaSup; var createGetProp = function(key){ if(nodeName == 'audio' && (key == 'videoHeight' || key == 'videoWidth')){return;} descs[key] = { get: function(){ var data = getSwfDataFromElem(this); if(data){ return data[key]; } else if(hasNative && mediaSup[key].prop._supget) { return mediaSup[key].prop._supget.apply(this); } else { return playerStateObj[key]; } }, writeable: false }; }; var createGetSetProp = function(key, setFn){ createGetProp(key); delete descs[key].writeable; descs[key].set = setFn; }; createGetSetProp('seeking'); createGetSetProp('volume', function(v){ var data = getSwfDataFromElem(this); if(data){ v *= 1; if(!isNaN(v)){ if(v < 0 || v > 1){ webshims.error('volume greater or less than allowed '+ (v / 100)); } queueSwfMethod(this, 'api_volume', [v], data); if(data.volume != v){ data.volume = v; trigger(data._elem, 'volumechange'); } data = null; } } else if(mediaSup.volume.prop._supset) { return mediaSup.volume.prop._supset.apply(this, arguments); } }); createGetSetProp('muted', function(m){ var data = getSwfDataFromElem(this); if(data){ m = !!m; queueSwfMethod(this, 'api_muted', [m], data); if(data.muted != m){ data.muted = m; trigger(data._elem, 'volumechange'); } data = null; } else if(mediaSup.muted.prop._supset) { return mediaSup.muted.prop._supset.apply(this, arguments); } }); createGetSetProp('currentTime', function(t){ var data = getSwfDataFromElem(this); if(data){ t *= 1; if (!isNaN(t)) { queueSwfMethod(this, 'api_seek', [t], data); } } else if(mediaSup.currentTime.prop._supset) { return mediaSup.currentTime.prop._supset.apply(this, arguments); } }); ['play', 'pause'].forEach(function(fn){ descs[fn] = { value: function(){ var data = getSwfDataFromElem(this); if(data){ if(data.stopPlayPause){ clearTimeout(data.stopPlayPause); } queueSwfMethod(this, fn == 'play' ? 'api_play' : 'api_pause', [], data); data._ppFlag = true; if(data.paused != (fn != 'play')){ data.paused = fn != 'play'; trigger(data._elem, fn); } } else if(mediaSup[fn].prop._supvalue) { return mediaSup[fn].prop._supvalue.apply(this, arguments); } } }; }); getPropKeys.forEach(createGetProp); webshims.onNodeNamesPropertyModify(nodeName, 'controls', function(val, boolProp){ var data = getSwfDataFromElem(this); $(this)[boolProp ? 'addClass' : 'removeClass']('webshims-controls'); if(data){ if(nodeName == 'audio'){ setElementDimension(data, boolProp); } queueSwfMethod(this, 'api_controls', [boolProp], data); } }); webshims.onNodeNamesPropertyModify(nodeName, 'preload', function(val){ var data, baseData, elem; if(bufferSrc(this)){ data = getSwfDataFromElem(this); if(data){ queueSwfMethod(this, 'api_preload', [], data); } else if(needsLoadPreload && this.paused && !this.error && !$.data(this, 'mediaerror') && !this.readyState && !this.networkState && !this.autoplay && $(this).is(':not(.nonnative-api-active)')){ elem = this; baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {}); clearTimeout(baseData.loadTimer); baseData.loadTimer = setTimeout(function(){ $(elem).mediaLoad(); }, 9); } } }); mediaSup = webshims.defineNodeNameProperties(nodeName, descs, 'prop'); if(!Modernizr.mediaDefaultMuted){ webshims.defineNodeNameProperties(nodeName, { defaultMuted: { get: function(){ return $.attr(this, 'muted') != null; }, set: function(val){ if(val){ $.attr(this, 'muted', ''); } else { $(this).removeAttr('muted'); } } } }, 'prop'); } }); if(hasFlash && $.cleanData){ var oldClean = $.cleanData; var flashNames = { object: 1, OBJECT: 1 }; $.cleanData = function(elems){ var i, len, prop; if(elems && (len = elems.length) && loadedSwf){ for(i = 0; i < len; i++){ if(flashNames[elems[i].nodeName] && 'api_pause' in elems[i]){ loadedSwf--; try { elems[i].api_pause(); if(elems[i].readyState == 4){ for (prop in elems[i]) { if (typeof elems[i][prop] == "function") { elems[i][prop] = null; } } } } catch(er){} } } } return oldClean.apply(this, arguments); }; } if(!hasNative){ ['poster', 'src'].forEach(function(prop){ webshims.defineNodeNamesProperty(prop == 'src' ? ['audio', 'video', 'source'] : ['video'], prop, { //attr: {}, reflect: true, propType: 'src' }); }); webshims.defineNodeNamesProperty(['audio', 'video'], 'preload', { reflect: true, propType: 'enumarated', defaultValue: '', limitedTo: ['', 'auto', 'metadata', 'none'] }); webshims.reflectProperties('source', ['type', 'media']); ['autoplay', 'controls'].forEach(function(name){ webshims.defineNodeNamesBooleanProperty(['audio', 'video'], name); }); webshims.defineNodeNamesProperties(['audio', 'video'], { HAVE_CURRENT_DATA: { value: 2 }, HAVE_ENOUGH_DATA: { value: 4 }, HAVE_FUTURE_DATA: { value: 3 }, HAVE_METADATA: { value: 1 }, HAVE_NOTHING: { value: 0 }, NETWORK_EMPTY: { value: 0 }, NETWORK_IDLE: { value: 1 }, NETWORK_LOADING: { value: 2 }, NETWORK_NO_SOURCE: { value: 3 } }, 'prop'); if(hasFlash){ webshims.ready('WINDOWLOAD', function(){ setTimeout(function(){ if(!loadedSwf){ document.createElement('img').src = playerSwfPath; } }, 9); }); } } else if(!('media' in document.createElement('source'))){ webshims.reflectProperties('source', ['media']); } if(hasNative && hasFlash && !options.preferFlash){ var switchErrors = { 3: 1, 4: 1 }; var switchOptions = function(e){ var media, error, parent; if( ($(e.target).is('audio, video') || ((parent = e.target.parentNode) && $('source', parent).last()[0] == e.target)) && (media = $(e.target).closest('audio, video')) && !media.is('.nonnative-api-active') ){ error = media.prop('error'); setTimeout(function(){ if(!media.is('.nonnative-api-active')){ if(error && switchErrors[error.code]){ options.preferFlash = true; document.removeEventListener('error', switchOptions, true); $('audio, video').each(function(){ webshims.mediaelement.selectSource(this); }); webshims.error("switching mediaelements option to 'preferFlash', due to an error with native player: "+e.target.src+" Mediaerror: "+ media.prop('error')+ 'first error: '+ error); } webshims.warn('There was a mediaelement error. Run the following line in your console to get more info: webshim.mediaelement.loadDebugger();') } }); } }; document.addEventListener('error', switchOptions, true); setTimeout(function(){ $('audio, video').each(function(){ var error = $.prop(this, 'error'); if(error && switchErrors[error]){ switchOptions({target: this}); } }); }); } });
//// Copyright (c) Microsoft Corporation. All rights reserved (function () { "use strict"; })();
var B = require('../').Buffer var test = require('tape') if (process.env.OBJECT_IMPL) B.TYPED_ARRAY_SUPPORT = false test('modifying buffer created by .slice() modifies original memory', function (t) { if (!B._useTypedArrays) return t.end() var buf1 = new B(26) for (var i = 0 ; i < 26 ; i++) { buf1[i] = i + 97 // 97 is ASCII a } var buf2 = buf1.slice(0, 3) t.equal(buf2.toString('ascii', 0, buf2.length), 'abc') buf2[0] = '!'.charCodeAt(0) t.equal(buf1.toString('ascii', 0, buf2.length), '!bc') t.end() }) test('modifying parent buffer modifies .slice() buffer\'s memory', function (t) { if (!B._useTypedArrays) return t.end() var buf1 = new B(26) for (var i = 0 ; i < 26 ; i++) { buf1[i] = i + 97 // 97 is ASCII a } var buf2 = buf1.slice(0, 3) t.equal(buf2.toString('ascii', 0, buf2.length), 'abc') buf1[0] = '!'.charCodeAt(0) t.equal(buf2.toString('ascii', 0, buf2.length), '!bc') t.end() })
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["Redux"] = factory(); else root["Redux"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.compose = exports.applyMiddleware = exports.bindActionCreators = exports.combineReducers = exports.createStore = undefined; var _createStore = __webpack_require__(2); var _createStore2 = _interopRequireDefault(_createStore); var _combineReducers = __webpack_require__(7); var _combineReducers2 = _interopRequireDefault(_combineReducers); var _bindActionCreators = __webpack_require__(6); var _bindActionCreators2 = _interopRequireDefault(_bindActionCreators); var _applyMiddleware = __webpack_require__(5); var _applyMiddleware2 = _interopRequireDefault(_applyMiddleware); var _compose = __webpack_require__(1); var _compose2 = _interopRequireDefault(_compose); var _warning = __webpack_require__(3); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /* * This is a dummy function to check if the function name has been altered by minification. * If the function has been minified and NODE_ENV !== 'production', warn the user. */ function isCrushed() {} if (("development") !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') { (0, _warning2['default'])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.'); } exports.createStore = _createStore2['default']; exports.combineReducers = _combineReducers2['default']; exports.bindActionCreators = _bindActionCreators2['default']; exports.applyMiddleware = _applyMiddleware2['default']; exports.compose = _compose2['default']; /***/ }, /* 1 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = compose; /** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose(f, g, h) is identical to doing * (...args) => f(g(h(...args))). */ function compose() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } var last = funcs[funcs.length - 1]; var rest = funcs.slice(0, -1); return function () { return rest.reduceRight(function (composed, f) { return f(composed); }, last.apply(undefined, arguments)); }; } /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.ActionTypes = undefined; exports['default'] = createStore; var _isPlainObject = __webpack_require__(4); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _symbolObservable = __webpack_require__(12); var _symbolObservable2 = _interopRequireDefault(_symbolObservable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * These are private action types reserved by Redux. * For any unknown actions, you must return the current state. * If the current state is undefined, you must return the initial state. * Do not reference these action types directly in your code. */ var ActionTypes = exports.ActionTypes = { INIT: '@@redux/INIT' }; /** * Creates a Redux store that holds the state tree. * The only way to change the data in the store is to call `dispatch()` on it. * * There should only be a single store in your app. To specify how different * parts of the state tree respond to actions, you may combine several reducers * into a single reducer function by using `combineReducers`. * * @param {Function} reducer A function that returns the next state tree, given * the current state tree and the action to handle. * * @param {any} [preloadedState] The initial state. You may optionally specify it * to hydrate the state from the server in universal apps, or to restore a * previously serialized user session. * If you use `combineReducers` to produce the root reducer function, this must be * an object with the same shape as `combineReducers` keys. * * @param {Function} enhancer The store enhancer. You may optionally specify it * to enhance the store with third-party capabilities such as middleware, * time travel, persistence, etc. The only store enhancer that ships with Redux * is `applyMiddleware()`. * * @returns {Store} A Redux store that lets you read the state, dispatch actions * and subscribe to changes. */ function createStore(reducer, preloadedState, enhancer) { var _ref2; if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState; preloadedState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.'); } return enhancer(createStore)(reducer, preloadedState); } if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.'); } var currentReducer = reducer; var currentState = preloadedState; var currentListeners = []; var nextListeners = currentListeners; var isDispatching = false; function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { nextListeners = currentListeners.slice(); } } /** * Reads the state tree managed by the store. * * @returns {any} The current state tree of your application. */ function getState() { return currentState; } /** * Adds a change listener. It will be called any time an action is dispatched, * and some part of the state tree may potentially have changed. You may then * call `getState()` to read the current state tree inside the callback. * * You may call `dispatch()` from a change listener, with the following * caveats: * * 1. The subscriptions are snapshotted just before every `dispatch()` call. * If you subscribe or unsubscribe while the listeners are being invoked, this * will not have any effect on the `dispatch()` that is currently in progress. * However, the next `dispatch()` call, whether nested or not, will use a more * recent snapshot of the subscription list. * * 2. The listener should not expect to see all state changes, as the state * might have been updated multiple times during a nested `dispatch()` before * the listener is called. It is, however, guaranteed that all subscribers * registered before the `dispatch()` started will be called with the latest * state by the time it exits. * * @param {Function} listener A callback to be invoked on every dispatch. * @returns {Function} A function to remove this change listener. */ function subscribe(listener) { if (typeof listener !== 'function') { throw new Error('Expected listener to be a function.'); } var isSubscribed = true; ensureCanMutateNextListeners(); nextListeners.push(listener); return function unsubscribe() { if (!isSubscribed) { return; } isSubscribed = false; ensureCanMutateNextListeners(); var index = nextListeners.indexOf(listener); nextListeners.splice(index, 1); }; } /** * Dispatches an action. It is the only way to trigger a state change. * * The `reducer` function, used to create the store, will be called with the * current state tree and the given `action`. Its return value will * be considered the **next** state of the tree, and the change listeners * will be notified. * * The base implementation only supports plain object actions. If you want to * dispatch a Promise, an Observable, a thunk, or something else, you need to * wrap your store creating function into the corresponding middleware. For * example, see the documentation for the `redux-thunk` package. Even the * middleware will eventually dispatch plain object actions using this method. * * @param {Object} action A plain object representing “what changed”. It is * a good idea to keep actions serializable so you can record and replay user * sessions, or use the time travelling `redux-devtools`. An action must have * a `type` property which may not be `undefined`. It is a good idea to use * string constants for action types. * * @returns {Object} For convenience, the same action object you dispatched. * * Note that, if you use a custom middleware, it may wrap `dispatch()` to * return something else (for example, a Promise you can await). */ function dispatch(action) { if (!(0, _isPlainObject2['default'])(action)) { throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.'); } if (typeof action.type === 'undefined') { throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'); } if (isDispatching) { throw new Error('Reducers may not dispatch actions.'); } try { isDispatching = true; currentState = currentReducer(currentState, action); } finally { isDispatching = false; } var listeners = currentListeners = nextListeners; for (var i = 0; i < listeners.length; i++) { listeners[i](); } return action; } /** * Replaces the reducer currently used by the store to calculate the state. * * You might need this if your app implements code splitting and you want to * load some of the reducers dynamically. You might also need this if you * implement a hot reloading mechanism for Redux. * * @param {Function} nextReducer The reducer for the store to use instead. * @returns {void} */ function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; dispatch({ type: ActionTypes.INIT }); } /** * Interoperability point for observable/reactive libraries. * @returns {observable} A minimal observable of state changes. * For more information, see the observable proposal: * https://github.com/zenparsing/es-observable */ function observable() { var _ref; var outerSubscribe = subscribe; return _ref = { /** * The minimal observable subscription method. * @param {Object} observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns {subscription} An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe: function subscribe(observer) { if (typeof observer !== 'object') { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; } }, _ref[_symbolObservable2['default']] = function () { return this; }, _ref; } // When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT }); return _ref2 = { dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }, _ref2[_symbolObservable2['default']] = observable, _ref2; } /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = warning; /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ } /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var getPrototype = __webpack_require__(8), isHostObject = __webpack_require__(9), isObjectLike = __webpack_require__(11); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || objectToString.call(value) != objectTag || isHostObject(value)) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return (typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); } module.exports = isPlainObject; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports['default'] = applyMiddleware; var _compose = __webpack_require__(1); var _compose2 = _interopRequireDefault(_compose); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * See `redux-thunk` package as an example of the Redux middleware. * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. * * @param {...Function} middlewares The middleware chain to be applied. * @returns {Function} A store enhancer applying the middleware. */ function applyMiddleware() { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function (reducer, preloadedState, enhancer) { var store = createStore(reducer, preloadedState, enhancer); var _dispatch = store.dispatch; var chain = []; var middlewareAPI = { getState: store.getState, dispatch: function dispatch(action) { return _dispatch(action); } }; chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = _compose2['default'].apply(undefined, chain)(store.dispatch); return _extends({}, store, { dispatch: _dispatch }); }; }; } /***/ }, /* 6 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = bindActionCreators; function bindActionCreator(actionCreator, dispatch) { return function () { return dispatch(actionCreator.apply(undefined, arguments)); }; } /** * Turns an object whose values are action creators, into an object with the * same keys, but with every function wrapped into a `dispatch` call so they * may be invoked directly. This is just a convenience method, as you can call * `store.dispatch(MyActionCreators.doSomething())` yourself just fine. * * For convenience, you can also pass a single function as the first argument, * and get a function in return. * * @param {Function|Object} actionCreators An object whose values are action * creator functions. One handy way to obtain it is to use ES6 `import * as` * syntax. You may also pass a single function. * * @param {Function} dispatch The `dispatch` function available on your Redux * store. * * @returns {Function|Object} The object mimicking the original object, but with * every action creator wrapped into the `dispatch` call. If you passed a * function as `actionCreators`, the return value will also be a single * function. */ function bindActionCreators(actionCreators, dispatch) { if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch); } if (typeof actionCreators !== 'object' || actionCreators === null) { throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'); } var keys = Object.keys(actionCreators); var boundActionCreators = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var actionCreator = actionCreators[key]; if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); } } return boundActionCreators; } /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = combineReducers; var _createStore = __webpack_require__(2); var _isPlainObject = __webpack_require__(4); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _warning = __webpack_require__(3); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function getUndefinedStateErrorMessage(key, action) { var actionType = action && action.type; var actionName = actionType && '"' + actionType.toString() + '"' || 'an action'; return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state.'; } function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) { var reducerKeys = Object.keys(reducers); var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer'; if (reducerKeys.length === 0) { return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; } if (!(0, _isPlainObject2['default'])(inputState)) { return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"'); } var unexpectedKeys = Object.keys(inputState).filter(function (key) { return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]; }); unexpectedKeys.forEach(function (key) { unexpectedKeyCache[key] = true; }); if (unexpectedKeys.length > 0) { return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.'); } } function assertReducerSanity(reducers) { Object.keys(reducers).forEach(function (key) { var reducer = reducers[key]; var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT }); if (typeof initialState === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.'); } var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.'); if (typeof reducer(undefined, { type: type }) === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.'); } }); } /** * Turns an object whose values are different reducer functions, into a single * reducer function. It will call every child reducer, and gather their results * into a single state object, whose keys correspond to the keys of the passed * reducer functions. * * @param {Object} reducers An object whose values correspond to different * reducer functions that need to be combined into one. One handy way to obtain * it is to use ES6 `import * as reducers` syntax. The reducers may never return * undefined for any action. Instead, they should return their initial state * if the state passed to them was undefined, and the current state for any * unrecognized action. * * @returns {Function} A reducer function that invokes every reducer inside the * passed object, and builds a state object with the same shape. */ function combineReducers(reducers) { var reducerKeys = Object.keys(reducers); var finalReducers = {}; for (var i = 0; i < reducerKeys.length; i++) { var key = reducerKeys[i]; if (true) { if (typeof reducers[key] === 'undefined') { (0, _warning2['default'])('No reducer provided for key "' + key + '"'); } } if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key]; } } var finalReducerKeys = Object.keys(finalReducers); if (true) { var unexpectedKeyCache = {}; } var sanityError; try { assertReducerSanity(finalReducers); } catch (e) { sanityError = e; } return function combination() { var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var action = arguments[1]; if (sanityError) { throw sanityError; } if (true) { var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache); if (warningMessage) { (0, _warning2['default'])(warningMessage); } } var hasChanged = false; var nextState = {}; for (var i = 0; i < finalReducerKeys.length; i++) { var key = finalReducerKeys[i]; var reducer = finalReducers[key]; var previousStateForKey = state[key]; var nextStateForKey = reducer(previousStateForKey, action); if (typeof nextStateForKey === 'undefined') { var errorMessage = getUndefinedStateErrorMessage(key, action); throw new Error(errorMessage); } nextState[key] = nextStateForKey; hasChanged = hasChanged || nextStateForKey !== previousStateForKey; } return hasChanged ? nextState : state; }; } /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(10); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }, /* 9 */ /***/ function(module, exports) { /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } module.exports = isHostObject; /***/ }, /* 10 */ /***/ function(module, exports) { /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } module.exports = overArg; /***/ }, /* 11 */ /***/ function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(13); /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _ponyfill = __webpack_require__(14); var _ponyfill2 = _interopRequireDefault(_ponyfill); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var root = undefined; /* global window */ if (typeof global !== 'undefined') { root = global; } else if (typeof window !== 'undefined') { root = window; } var result = (0, _ponyfill2['default'])(root); exports['default'] = result; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 14 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = symbolObservablePonyfill; function symbolObservablePonyfill(root) { var result; var _Symbol = root.Symbol; if (typeof _Symbol === 'function') { if (_Symbol.observable) { result = _Symbol.observable; } else { result = _Symbol('observable'); _Symbol.observable = result; } } else { result = '@@observable'; } return result; }; /***/ } /******/ ]) }); ;
/*! * TableSorter 2.1.13 - Client-side table sorting with ease! * @requires jQuery v1.2.6+ * * Copyright (c) 2007 Christian Bach * Examples and docs at: http://tablesorter.com * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * @type jQuery * @name tablesorter * @cat Plugins/Tablesorter * @author Christian Bach/christian.bach@polyester.se * @contributor Rob Garrison/https://github.com/Mottie/tablesorter */ !(function($){ $.extend({ tablesorter: new function(){ this.version = "2.1.13"; var parsers = [], widgets = [], tbl; this.defaults = { cssHeader: "tablesorter-header", cssAsc: "tablesorter-headerSortUp", cssDesc: "tablesorter-headerSortDown", cssChildRow: "expand-child", sortInitialOrder: "asc", sortMultiSortKey: "shiftKey", sortForce: null, sortAppend: null, sortLocaleCompare: false, sortReset: false, sortRestart: false, emptyToBottom : true, // sort empty cell to bottom textExtraction: "simple", parsers: {}, widgets: [], headers: {}, widthFixed: false, cancelSelection: true, sortList: [], headerList: [], dateFormat: "mmddyyyy", // other options: "ddmmyyy" or "yyyymmdd" usNumberFormat: true, // false for German "1.234.567,89" or French "1 234 567,89" onRenderHeader: null, selectorHeaders: 'thead th', selectorRemove: "tr.remove-me", tableClass : 'tablesorter', debug: false, widgetOptions : { zebra : [ "even", "odd" ] } // deprecated; but retained for backwards compatibility // widgetZebra: { css: ["even", "odd"] } }; /* debuging utils */ function log(s) { if (typeof console !== "undefined" && typeof console.log !== "undefined") { console.log(s); } else { alert(s); } } function benchmark(s, d) { log(s + " (" + (new Date().getTime() - d.getTime()) + "ms)"); } this.benchmark = benchmark; this.hasInitialized = false; function getElementText(config, node, cellIndex) { var text = "", te = config.textExtraction; if (!node) { return ""; } if (!config.supportsTextContent) { config.supportsTextContent = node.textContent || false; } if (te === "simple") { if (config.supportsTextContent) { text = node.textContent; } else { if (node.childNodes[0] && node.childNodes[0].hasChildNodes()) { text = node.childNodes[0].innerHTML; } else { text = node.innerHTML; } } } else { if (typeof(te) === "function") { text = te(node, tbl, cellIndex); } else if (typeof(te) === "object" && te.hasOwnProperty(cellIndex)){ text = te[cellIndex](node, tbl, cellIndex); } else { text = $(node).text(); } } return text; } /* parsers utils */ function getParserById(name) { var i, l = parsers.length; for (i = 0; i < l; i++) { if (parsers[i].id.toLowerCase() === (name.toString()).toLowerCase()) { return parsers[i]; } } return false; } function trimAndGetNodeText(config, node, cellIndex) { return $.trim(getElementText(config, node, cellIndex)); } function detectParserForColumn(table, rows, rowIndex, cellIndex) { var i, l = parsers.length, node = false, nodeValue = '', keepLooking = true; while (nodeValue === '' && keepLooking) { rowIndex++; if (rows[rowIndex]) { node = rows[rowIndex].cells[cellIndex]; nodeValue = trimAndGetNodeText(table.config, node, cellIndex); if (table.config.debug) { log('Checking if value was empty on row ' + rowIndex + ', column:' + cellIndex + ": " + nodeValue); } } else { keepLooking = false; } } for (i = 1; i < l; i++) { if (parsers[i].is(nodeValue, table, node)) { return parsers[i]; } } // 0 is always the generic parser (text) return parsers[0]; } function buildParserCache(table, $headers) { if (table.tBodies.length === 0) { return; } // In the case of empty tables var rows = table.tBodies[0].rows, list, cells, l, h, i, p, parsersDebug = ""; if (rows[0]) { list = []; cells = rows[0].cells; l = cells.length; for (i = 0; i < l; i++) { p = false; h = $($headers[i]); if ($.metadata && (h.metadata() && h.metadata().sorter)) { p = getParserById(h.metadata().sorter); } else if ((table.config.headers[i] && table.config.headers[i].sorter)) { p = getParserById(table.config.headers[i].sorter); } else if (h.attr('class') && h.attr('class').match('sorter-')){ // include sorter class name "sorter-text", etc p = getParserById(h.attr('class').match(/sorter-(\w+)/)[1] || ''); } if (!p) { p = detectParserForColumn(table, rows, -1, i); } if (table.config.debug) { parsersDebug += "column:" + i + "; parser:" + p.id + "\n"; } list.push(p); } } if (table.config.debug) { log(parsersDebug); } return list; } /* utils */ function buildCache(table) { var b = table.tBodies[0], totalRows = (b && b.rows.length) || 0, totalCells = (b.rows[0] && b.rows[0].cells.length) || 0, parsers = table.config.parsers, cache = { row: [], normalized: [] }, t, i, j, c, cols, cacheTime; if (table.config.debug) { cacheTime = new Date(); } for (i = 0; i < totalRows; ++i) { /** Add the table data to main data array */ c = $(b.rows[i]); cols = []; // if this is a child row, add it to the last row's children and continue to the next row if (c.hasClass(table.config.cssChildRow)) { cache.row[cache.row.length - 1] = cache.row[cache.row.length - 1].add(c); // go to the next for loop continue; } cache.row.push(c); for (j = 0; j < totalCells; ++j) { t = trimAndGetNodeText(table.config, c[0].cells[j], j); // don't bother parsing if the string is empty - previously parsing would change it to zero cols.push( parsers[j].format(t, table, c[0].cells[j], j) ); } cols.push(cache.normalized.length); // add position for rowCache cache.normalized.push(cols); } if (table.config.debug) { benchmark("Building cache for " + totalRows + " rows", cacheTime); } table.config.cache = cache; return cache; } function getWidgetById(name) { var i, w, l = widgets.length; for (i = 0; i < l; i++) { w = widgets[i]; if (w && w.hasOwnProperty('id') && w.id.toLowerCase() === name.toLowerCase()) { return w; } } } function applyWidget(table, init) { var c = table.config.widgets, i, w, l = c.length; for (i = 0; i < l; i++) { w = getWidgetById(c[i]); if ( w ) { if (init && w.hasOwnProperty('init')) { w.init(table, widgets, w); } else if (!init && w.hasOwnProperty('format')) { w.format(table); } } } } function appendToTable(table, cache) { var c = table.config, r = cache.row, n = cache.normalized, totalRows = n.length, checkCell = totalRows ? (n[0].length - 1) : 0, rows = [], i, j, l, pos, appendTime; if (c.debug) { appendTime = new Date(); } for (i = 0; i < totalRows; i++) { pos = n[i][checkCell]; rows.push(r[pos]); // removeRows used by the pager plugin if (!c.appender || !c.removeRows) { l = r[pos].length; for (j = 0; j < l; j++) { table.tBodies[0].appendChild(r[pos][j]); } } } if (c.appender) { c.appender(table, rows); } if (c.debug) { benchmark("Rebuilt table", appendTime); } // apply table widgets applyWidget(table); // trigger sortend $(table).trigger("sortEnd", table); } // from: // http://www.javascripttoolbox.com/lib/table/examples.php // http://www.javascripttoolbox.com/temp/table_cellindex.html function computeTableHeaderCellIndexes(t) { var matrix = [], lookup = {}, thead = t.getElementsByTagName('THEAD')[0], trs = thead.getElementsByTagName('TR'), i, j, k, l, c, cells, rowIndex, cellId, rowSpan, colSpan, firstAvailCol, matrixrow; for (i = 0; i < trs.length; i++) { cells = trs[i].cells; for (j = 0; j < cells.length; j++) { c = cells[j]; rowIndex = c.parentNode.rowIndex; cellId = rowIndex + "-" + c.cellIndex; rowSpan = c.rowSpan || 1; colSpan = c.colSpan || 1; if (typeof(matrix[rowIndex]) === "undefined") { matrix[rowIndex] = []; } // Find first available column in the first row for (k = 0; k < matrix[rowIndex].length + 1; k++) { if (typeof(matrix[rowIndex][k]) === "undefined") { firstAvailCol = k; break; } } lookup[cellId] = firstAvailCol; for (k = rowIndex; k < rowIndex + rowSpan; k++) { if (typeof(matrix[k]) === "undefined") { matrix[k] = []; } matrixrow = matrix[k]; for (l = firstAvailCol; l < firstAvailCol + colSpan; l++) { matrixrow[l] = "x"; } } } } return lookup; } function formatSortingOrder(v) { // look for "d" in "desc" order; return true return (/^d/i.test(v) || v === 1); } function checkHeaderMetadata(cell) { return (($.metadata) && ($(cell).metadata().sorter === false)); } function checkHeaderOptions(table, i) { return ((table.config.headers[i]) && (table.config.headers[i].sorter === false)); } function checkHeaderLocked(table, i) { if ((table.config.headers[i]) && (table.config.headers[i].lockedOrder !== null)) { return table.config.headers[i].lockedOrder; } return false; } function checkHeaderOrder(table, i) { if ((table.config.headers[i]) && (table.config.headers[i].sortInitialOrder)) { return table.config.headers[i].sortInitialOrder; } return table.config.sortInitialOrder; } function buildHeaders(table) { var meta = ($.metadata) ? true : false, header_index = computeTableHeaderCellIndexes(table), $th, lock, time, $tableHeaders, c = table.config; c.headerList = []; if (c.debug) { time = new Date(); } $tableHeaders = $(c.selectorHeaders, table) .wrapInner("<div class='tablesorter-header-inner' />") .each(function (index) { this.column = header_index[this.parentNode.rowIndex + "-" + this.cellIndex]; this.order = formatSortingOrder( checkHeaderOrder(table, index) ) ? [1,0,2] : [0,1,2]; this.count = -1; // set to -1 because clicking on the header automatically adds one if (checkHeaderMetadata(this) || checkHeaderOptions(table, index) || $(this).hasClass('sorter-false')) { this.sortDisabled = true; } this.lockedOrder = false; lock = checkHeaderLocked(table, index); if (typeof(lock) !== 'undefined' && lock !== false) { this.order = this.lockedOrder = formatSortingOrder(lock) ? [1,1,1] : [0,0,0]; } if (!this.sortDisabled) { $th = $(this).addClass(c.cssHeader); if (c.onRenderHeader) { c.onRenderHeader.apply($th, [index]); } } // add cell to headerList c.headerList[index] = this; $(this).parent().addClass(c.cssHeader); }); if (c.debug) { benchmark("Built headers", time); log($tableHeaders); } return $tableHeaders; } // Part of original tablesorter - not even called. function checkCellColSpan(table, rows, row) { var i, cell, arr = [], r = table.tHead.rows, c = r[row].cells; for (i = 0; i < c.length; i++) { cell = c[i]; if (cell.colSpan > 1) { arr = arr.concat(checkCellColSpan(table, rows, row++)); // what is headerArr? } else { if (table.tHead.length === 1 || (cell.rowSpan > 1 || !r[row + 1])) { arr.push(cell); } } } return arr; } function isValueInArray(v, a) { var i, l = a.length; for (i = 0; i < l; i++) { if (a[i][0] === v) { return true; } } return false; } function setHeadersCss(table, $headers, list) { var h = [], i, l, css = [table.config.cssDesc, table.config.cssAsc]; // remove all header information $headers.removeClass(css[0]).removeClass(css[1]); $headers.each(function() { if (!this.sortDisabled) { h[this.column] = $(this); } }); l = list.length; for (i = 0; i < l; i++) { if (list[i][1] === 2) { continue; } // direction = 2 means reset! h[list[i][0]].addClass(css[list[i][1]]); } } function fixColumnWidth(table) { if (table.config.widthFixed) { var colgroup = $('<colgroup>'); $("tr:first td", table.tBodies[0]).each(function () { colgroup.append($('<col>').css('width', $(this).width())); }); $(table).prepend(colgroup); } } function updateHeaderSortCount(table, sortList) { var i, s, o, c = table.config, l = sortList.length; for (i = 0; i < l; i++) { s = sortList[i]; o = c.headerList[s[0]]; o.count = s[1] % (c.sortReset ? 3 : 2); } } function getCachedSortType(parsers, i) { return (parsers) ? parsers[i].type : ''; } /* sorting methods - reverted sorting method back to version 2.0.3 */ function multisort(table,sortList,cache) { var dynamicExp = "var sortWrapper = function(a,b) {", col, mx = 0, dir = 0, tc = table.config, lc = cache.normalized.length, l = sortList.length, sortTime, i, j, c, s, e, order, orgOrderCol; if (tc.debug) { sortTime = new Date(); } for (i=0; i < l; i++) { c = sortList[i][0]; order = sortList[i][1]; s = (getCachedSortType(tc.parsers,c) === "text") ? ((order === 0) ? "sortText" : "sortTextDesc") : ((order === 0) ? "sortNumeric" : "sortNumericDesc"); e = "e" + i; // get max column value (ignore sign) if (/Numeric/.test(s) && tc.headers[c] && tc.headers[c].string){ for (j=0; j < lc; j++) { col = Math.abs(parseFloat(cache.normalized[j][c])); mx = Math.max( mx, isNaN(col) ? 0 : col ); } dir = (tc.headers[c]) ? tc.string[tc.headers[c].string] || 0 : 0; } dynamicExp += "var " + e + " = " + s + "(a[" + c + "],b[" + c + "]," + mx + "," + dir + "); "; dynamicExp += "if (" + e + ") { return " + e + "; } "; dynamicExp += "else { "; } // if value is the same keep orignal order orgOrderCol = (cache.normalized && cache.normalized[0]) ? cache.normalized[0].length - 1 : 0; dynamicExp += "return a[" + orgOrderCol + "]-b[" + orgOrderCol + "];"; for(i=0; i < l; i++) { dynamicExp += "}; "; } dynamicExp += "return 0; "; dynamicExp += "}; "; eval(dynamicExp); cache.normalized.sort(sortWrapper); // sort using eval expression if (tc.debug) { benchmark("Sorting on " + sortList.toString() + " and dir " + order+ " time", sortTime); } return cache; } // Natural sort modified from: http://www.webdeveloper.com/forum/showthread.php?t=107909 function sortText(a, b) { var c = tbl[0].config, cnt = 0, L, t, x; if (a === b) { return 0; } if (a === '' && c.emptyToBottom !== null) { return c.emptyToBottom ? 1 : -1; } if (b === '' && c.emptyToBottom !== null) { return c.emptyToBottom ? -1 : 1; } if (c.sortLocaleCompare) { return a.localeCompare(b); } try { x = /^(\.)?\d/; L = Math.min(a.length, b.length) + 1; while (cnt < L && a.charAt(cnt) === b.charAt(cnt) && x.test(b.substring(cnt)) === false && x.test(a.substring(cnt)) === false) { cnt++; } a = a.substring(cnt); b = b.substring(cnt); if (x.test(a) || x.test(b)) { if (x.test(a) === false) { return (a) ? 1 : -1; } else if (x.test(b) === false) { return (b) ? -1 : 1; } else { t = parseFloat(a) - parseFloat(b); if (t !== 0) { return t; } else { t = a.search(/[^\.\d]/); } if (t === -1) { t = b.search(/[^\.\d]/); } a = a.substring(t); b = b.substring(t); } } return (a > b) ? 1 : -1; } catch (er) { return 0; } } function sortTextDesc(a, b){ var c = tbl[0].config; if (a === b) { return 0; } if (a === '' && c.emptyToBottom !== null) { return c.emptyToBottom ? 1 : -1; } if (b === '' && c.emptyToBottom !== null) { return c.emptyToBottom ? -1 : 1; } if (c.sortLocaleCompare) { return b.localeCompare(a); } return -sortText(a, b); } // return text string value by adding up ascii value // so the text is somewhat sorted when using a digital sort // this is NOT an alphanumeric sort function getTextValue(a, mx, d){ if (mx) { // make sure the text value is greater than the max numerical value (mx) var i, l = a.length, n = mx + d; for (i = 0; i < l; i++){ n += a.charCodeAt(i); } return d * n; } return 0; } function sortNumeric(a, b, mx, d) { var c = tbl[0].config; if (a === b) { return 0; } if (a === '' && c.emptyToBottom !== null) { return c.emptyToBottom ? 1 : -1; } if (b === '' && c.emptyToBottom !== null) { return c.emptyToBottom ? -1 : 1; } if (isNaN(a)) { a = getTextValue(a, mx, d); } if (isNaN(b)) { b = getTextValue(b, mx, d); } return a - b; } function sortNumericDesc(a, b, mx, d) { var c = tbl[0].config; if (a === b) { return 0; } if (a === '' && c.emptyToBottom !== null) { return c.emptyToBottom ? 1 : -1; } if (b === '' && c.emptyToBottom !== null) { return c.emptyToBottom ? -1 : 1; } if (isNaN(a)) { a = getTextValue(a, mx, d); } if (isNaN(b)) { b = getTextValue(b, mx, d); } return b - a; } /* public methods */ this.construct = function(settings){ return this.each(function(){ // if no thead or tbody quit. if (!this.tHead || this.tBodies.length === 0) { return; } // declare var $this, $headers, cache, config, totalRows, $cell, c, i, j, k, a, s, o; // new blank config object this.config = {}; // merge and extend. c = config = $.extend(true, this.config, $.tablesorter.defaults, settings); // store common expression for speed tbl = $this = $(this).addClass(this.config.tableClass); // save the settings where they read $.data(this, "tablesorter", c); // build headers $headers = buildHeaders(this); // try to auto detect column type, and store in tables config c.parsers = buildParserCache(this, $headers); // digit sort text location c.string = { max: 1, 'max+': 1, 'max-': -1, none: 0 }; // build the cache for the tbody cells cache = buildCache(this); // fixate columns if the users supplies the fixedWidth option fixColumnWidth(this); // apply event handling to headers // this is to big, perhaps break it out? $headers .click(function(e){ totalRows = ($this[0].tBodies[0] && $this[0].tBodies[0].rows.length) || 0; if (!this.sortDisabled) { // Only call sortStart if sorting is enabled. $this.trigger("sortStart", tbl[0]); // store exp, for speed $cell = $(this); k = !e[c.sortMultiSortKey]; // get current column sort order this.count = (this.count + 1) % (c.sortReset ? 3 : 2); // reset all sorts on non-current column - issue #30 if (c.sortRestart) { i = this; $headers.each(function(){ // only reset counts on columns that weren't just clicked on and if not included in a multisort if (this !== i && (k || !$(this).is('.' + c.cssDesc + ',.' + c.cssAsc))) { this.count = -1; } }); } // get current column index i = this.column; // user only wants to sort on one column if (k) { // flush the sort list c.sortList = []; if (c.sortForce !== null) { a = c.sortForce; for (j = 0; j < a.length; j++) { if (a[j][0] !== i) { c.sortList.push(a[j]); } } } // add column to sort list if (this.order[this.count] < 2) { c.sortList.push([i, this.order[this.count]]); } // multi column sorting } else { // the user has clicked on an already sorted column. if (isValueInArray(i, c.sortList)) { // reverse the sorting direction for all tables. for (j = 0; j < c.sortList.length; j++) { s = c.sortList[j]; o = c.headerList[s[0]]; if (s[0] === i) { s[1] = o.order[o.count]; if (s[1] === 2) { c.sortList.splice(j,1); o.count = -1; } } } } else { // add column to sort list array if (this.order[this.count] < 2) { c.sortList.push([i, this.order[this.count]]); } } } if (c.sortAppend !== null) { a = c.sortAppend; for (j = 0; j < a.length; j++) { if (a[j][0] !== i) { c.sortList.push(a[j]); } } } // sortBegin event triggered immediately before the sort $this.trigger("sortBegin", tbl[0]); // set css for headers setHeadersCss($this[0], $headers, c.sortList); appendToTable($this[0], multisort($this[0], c.sortList, cache)); // stop normal event by returning false return false; } // cancel selection }) .mousedown(function(){ if (c.cancelSelection) { this.onselectstart = function(){ return false; }; return false; } }); // apply easy methods that trigger binded events $this .bind("update", function(){ var t = this, c = t.config; // remove rows/elements before update $(c.selectorRemove, t.tBodies[0]).remove(); // rebuild parsers. t.config.parsers = buildParserCache(t, $headers); // rebuild the cache map cache = buildCache(t); $this.trigger("sorton", [t.config.sortList]); }) .bind("updateCell", function(e, cell) { // get position from the dom. var pos = [(cell.parentNode.rowIndex - 1), cell.cellIndex]; // update cache - format: function(s, table, cell, cellIndex) cache.normalized[pos[0]][pos[1]] = c.parsers[pos[1]].format(getElementText(c, cell, pos[1]), $this, cell, pos[1]); c.cache = cache; $this.trigger("sorton", [c.sortList]); }) .bind("addRows", function(e, row) { var i, rows = row.filter('tr').length, dat = [], l = row[0].cells.length; // add each row for (i = 0; i < rows; i++) { // add each cell for (j = 0; j < l; j++) { dat[j] = c.parsers[j].format(getElementText(c, row[i].cells[j], j), $this, row[i].cells[j], j ); } // add the row index to the end dat.push(cache.row.length); // update cache cache.row.push([row[i]]); cache.normalized.push(dat); dat = []; } c.cache = cache; // resort using current settings $this.trigger("sorton", [c.sortList]); }) .bind("sorton", function(e, list) { $(this).trigger("sortStart", tbl[0]); c.sortList = list; // update and store the sortlist var sortList = c.sortList; // update header count index updateHeaderSortCount(this, sortList); // set css for headers setHeadersCss(this, $headers, sortList); // sort the table and append it to the dom appendToTable(this, multisort(this, sortList, cache)); }) .bind("appendCache", function () { appendToTable(this, cache); }) .bind("applyWidgetId", function (e, id) { getWidgetById(id).format(this); }) .bind("applyWidgets", function () { // apply widgets applyWidget(this); }); if ($.metadata && ($(this).metadata() && $(this).metadata().sortlist)) { c.sortList = $(this).metadata().sortlist; } // apply widget init code applyWidget(this, true); // if user has supplied a sort list to constructor. if (c.sortList.length > 0) { $this.trigger("sorton", [c.sortList]); } else { // apply widget format applyWidget(this); } this.hasInitialized = true; }); }; this.addParser = function(parser) { var i, l = parsers.length, a = true; for (i = 0; i < l; i++) { if (parsers[i].id.toLowerCase() === parser.id.toLowerCase()) { a = false; } } if (a) { parsers.push(parser); } }; this.addWidget = function (widget) { widgets.push(widget); }; this.formatFloat = function(s) { if (typeof(s) !== 'string') { return s; } if (tbl[0].config.usNumberFormat) { // US Format - 1,234,567.89 -> 1234567.89 s = s.replace(/,/g,''); } else { // German Format = 1.234.567,89 -> 1234567.89 // French Format = 1 234 567,89 -> 1234567.89 s = s.replace(/[\s|\.]/g,'').replace(/,/g,'.'); } if(/^\s*\([.\d]+\)/.test(s)) { s = s.replace(/^\s*\(/,'-').replace(/\)/,''); } var i = parseFloat(s); // return the text instead of zero return isNaN(i) ? $.trim(s) : i; }; this.isDigit = function(s) { // replace all unwanted chars and match. return (/^[\-+(]?\d*[)]?$/).test($.trim(s.replace(/[,.'\s]/g, ''))); }; this.clearTableBody = function (table) { $(table.tBodies[0]).empty(); }; } })(); // extend plugin scope $.fn.extend({ tablesorter: $.tablesorter.construct }); // make shortcut var ts = $.tablesorter; // add default parsers ts.addParser({ id: "text", is: function(s){ return true; }, format: function(s) { return $.trim(s.toLocaleLowerCase()); }, type: "text" }); ts.addParser({ id: "digit", is: function(s){ return $.tablesorter.isDigit(s); }, format: function(s){ return $.tablesorter.formatFloat(s.replace(/[^\w,. \-()]/g, "")); }, type: "numeric" }); ts.addParser({ id: "currency", is: function(s){ return (/^\(?[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]/).test(s); // £$€¤¥¢?. }, format: function(s){ return $.tablesorter.formatFloat(s.replace(/[^0-9,. \-()]/g, "")); }, type: "numeric" }); ts.addParser({ id: "ipAddress", is: function(s) { return (/^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/).test(s); }, format: function(s){ var i, item, a = s.split("."), r = "", l = a.length; for (i = 0; i < l; i++) { item = a[i]; if (item.length === 2) { r += "0" + item; } else { r += item; } } return $.tablesorter.formatFloat(r); }, type: "numeric" }); ts.addParser({ id: "url", is: function(s) { return (/^(https?|ftp|file):\/\/$/).test(s); }, format: function(s) { return $.trim(s.replace(/(https?|ftp|file):\/\//, '')); }, type: "text" }); ts.addParser({ id: "isoDate", is: function(s) { return (/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/).test(s); }, format: function(s) { return $.tablesorter.formatFloat((s !== "") ? new Date(s.replace(/-/g, "/")).getTime() : ""); }, type: "numeric" }); ts.addParser({ id: "percent", is: function(s) { return (/\%\)?$/).test($.trim(s)); }, format: function(s) { return $.tablesorter.formatFloat(s.replace(/%/g, "")); }, type: "numeric" }); ts.addParser({ id: "usLongDate", is: function(s) { return s.match(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/); }, format: function(s) { return $.tablesorter.formatFloat(new Date(s).getTime()); }, type: "numeric" }); ts.addParser({ id: "shortDate", // "mmddyyyy", "ddmmyyyy" or "yyyymmdd" is: function(s) { // testing for ####-####-#### - so it's not perfect return (/\d{1,4}[\/\-\,\.\s+]\d{1,4}[\/\-\.\,\s+]\d{1,4}/).test(s); }, format: function(s, table, cell, cellIndex) { var c = table.config, format = (c.headers && c.headers[cellIndex]) ? c.headers[cellIndex].dateFormat || c.dateFormat : c.dateFormat; // get dateFormat from header or config s = s.replace(/\s+/g," ").replace(/[\-|\.|\,|\s]/g, "/"); if (format === "mmddyyyy") { s = s.replace(/(\d{1,2})\/(\d{1,2})\/(\d{4})/, "$3/$1/$2"); } else if (format === "ddmmyyyy") { s = s.replace(/(\d{1,2})\/(\d{1,2})\/(\d{4})/, "$3/$2/$1"); } else if (format === "yyyymmdd") { s = s.replace(/(\d{4})\/(\d{1,2})\/(\d{1,2})/, "$1/$2/$3"); } return $.tablesorter.formatFloat(new Date(s).getTime()); }, type: "numeric" }); ts.addParser({ id: "time", is: function(s) { return (/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/).test(s); }, format: function(s) { return $.tablesorter.formatFloat(new Date("2000/01/01 " + s).getTime()); }, type: "numeric" }); ts.addParser({ id: "metadata", is: function(s) { return false; }, format: function(s, table, cell) { var c = table.config, p = (!c.parserMetadataName) ? 'sortValue' : c.parserMetadataName; return $(cell).metadata()[p]; }, type: "numeric" }); // add default widgets ts.addWidget({ id: "zebra", format: function(table) { var $tr, row = 0, even, time, c = table.config, child = c.cssChildRow, css = [ "even", "odd" ]; // maintain backwards compatibility css = c.widgetZebra && c.hasOwnProperty('css') ? c.widgetZebra.css : (c.widgetOptions && c.widgetOptions.hasOwnProperty('zebra')) ? c.widgetOptions.zebra : css; if (table.config.debug) { time = new Date(); } // loop through the visible rows $("tr:visible", table.tBodies[0]).each(function(){ $tr = $(this); // style children rows the same way the parent row was styled if (!$tr.hasClass(child)) { row++; } even = (row % 2 === 0); $tr .removeClass(css[even ? 1 : 0]) .addClass(css[even ? 0 : 1]); }); if (table.config.debug) { $.tablesorter.benchmark("Applying Zebra widget", time); } } }); })(jQuery);
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.lang({ source : 'Source', preview : 'Preview', undo : 'Undo(Ctrl+Z)', redo : 'Redo(Ctrl+Y)', cut : 'Cut(Ctrl+X)', copy : 'Copy(Ctrl+C)', paste : 'Paste(Ctrl+V)', plainpaste : 'Paste as plain text', wordpaste : 'Paste from Word', selectall : 'Select all', justifyleft : 'Align left', justifycenter : 'Align center', justifyright : 'Align right', justifyfull : 'Align full', insertorderedlist : 'Ordered list', insertunorderedlist : 'Unordered list', indent : 'Increase indent', outdent : 'Decrease indent', subscript : 'Subscript', superscript : 'Superscript', formatblock : 'Paragraph format', fontname : 'Font family', fontsize : 'Font size', forecolor : 'Text color', hilitecolor : 'Highlight color', bold : 'Bold(Ctrl+B)', italic : 'Italic(Ctrl+I)', underline : 'Underline(Ctrl+U)', strikethrough : 'Strikethrough', removeformat : 'Remove format', image : 'Image', multiimage : 'Multi image', flash : 'Flash', media : 'Embeded media', table : 'Table', tablecell : 'Cell', hr : 'Insert horizontal line', emoticons : 'Insert emoticon', link : 'Link', unlink : 'Unlink', fullscreen : 'Toggle fullscreen mode', about : 'About', print : 'Print', filemanager : 'File Manager', code : 'Insert code', map : 'Google Maps', baidumap : 'Baidu Maps', lineheight : 'Line height', clearhtml : 'Clear HTML code', pagebreak : 'Insert Page Break', quickformat : 'Quick Format', insertfile : 'Insert file', template : 'Insert Template', anchor : 'Anchor', yes : 'OK', no : 'Cancel', close : 'Close', editImage : 'Image properties', deleteImage : 'Delete image', editFlash : 'Flash properties', deleteFlash : 'Delete flash', editMedia : 'Media properties', deleteMedia : 'Delete media', editLink : 'Link properties', deleteLink : 'Unlink', tableprop : 'Table properties', tablecellprop : 'Cell properties', tableinsert : 'Insert table', tabledelete : 'Delete table', tablecolinsertleft : 'Insert column left', tablecolinsertright : 'Insert column right', tablerowinsertabove : 'Insert row above', tablerowinsertbelow : 'Insert row below', tablerowmerge : 'Merge down', tablecolmerge : 'Merge right', tablerowsplit : 'Split row', tablecolsplit : 'Split column', tablecoldelete : 'Delete column', tablerowdelete : 'Delete row', noColor : 'Default', pleaseSelectFile : 'Please select file.', invalidImg : "Please type valid URL.\nAllowed file extension: jpg,gif,bmp,png", invalidMedia : "Please type valid URL.\nAllowed file extension: swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb", invalidWidth : "The width must be number.", invalidHeight : "The height must be number.", invalidBorder : "The border must be number.", invalidUrl : "Please type valid URL.", invalidRows : 'Invalid rows.', invalidCols : 'Invalid columns.', invalidPadding : 'The padding must be number.', invalidSpacing : 'The spacing must be number.', invalidJson : 'Invalid JSON string.', uploadSuccess : 'Upload success.', cutError : 'Currently not supported by your browser, use keyboard shortcut(Ctrl+X) instead.', copyError : 'Currently not supported by your browser, use keyboard shortcut(Ctrl+C) instead.', pasteError : 'Currently not supported by your browser, use keyboard shortcut(Ctrl+V) instead.', ajaxLoading : 'Loading ...', uploadLoading : 'Uploading ...', uploadError : 'Upload Error', 'plainpaste.comment' : 'Use keyboard shortcut(Ctrl+V) to paste the text into the window.', 'wordpaste.comment' : 'Use keyboard shortcut(Ctrl+V) to paste the text into the window.', 'code.pleaseInput' : 'Please input code.', 'link.url' : 'URL', 'link.linkType' : 'Target', 'link.newWindow' : 'New window', 'link.selfWindow' : 'Same window', 'flash.url' : 'URL', 'flash.width' : 'Width', 'flash.height' : 'Height', 'flash.upload' : 'Upload', 'flash.viewServer' : 'Browse', 'media.url' : 'URL', 'media.width' : 'Width', 'media.height' : 'Height', 'media.autostart' : 'Auto start', 'media.upload' : 'Upload', 'media.viewServer' : 'Browse', 'image.remoteImage' : 'Insert URL', 'image.localImage' : 'Upload', 'image.remoteUrl' : 'URL', 'image.localUrl' : 'File', 'image.size' : 'Size', 'image.width' : 'Width', 'image.height' : 'Height', 'image.resetSize' : 'Reset dimensions', 'image.align' : 'Align', 'image.defaultAlign' : 'Default', 'image.leftAlign' : 'Left', 'image.rightAlign' : 'Right', 'image.imgTitle' : 'Title', 'image.upload' : 'Browse', 'image.viewServer' : 'Browse', 'multiimage.uploadDesc' : 'Allows users to upload <%=uploadLimit%> images, single image size not exceeding <%=sizeLimit%>', 'multiimage.startUpload' : 'Start upload', 'multiimage.clearAll' : 'Clear all', 'multiimage.insertAll' : 'Insert all', 'multiimage.queueLimitExceeded' : 'Queue limit exceeded.', 'multiimage.fileExceedsSizeLimit' : 'File exceeds size limit.', 'multiimage.zeroByteFile' : 'Zero byte file.', 'multiimage.invalidFiletype' : 'Invalid file type.', 'multiimage.unknownError' : 'Unknown upload error.', 'multiimage.pending' : 'Pending ...', 'multiimage.uploadError' : 'Upload error', 'filemanager.emptyFolder' : 'Blank', 'filemanager.moveup' : 'Parent folder', 'filemanager.viewType' : 'Display: ', 'filemanager.viewImage' : 'Thumbnails', 'filemanager.listImage' : 'List', 'filemanager.orderType' : 'Sorting: ', 'filemanager.fileName' : 'By name', 'filemanager.fileSize' : 'By size', 'filemanager.fileType' : 'By type', 'insertfile.url' : 'URL', 'insertfile.title' : 'Title', 'insertfile.upload' : 'Upload', 'insertfile.viewServer' : 'Browse', 'table.cells' : 'Cells', 'table.rows' : 'Rows', 'table.cols' : 'Columns', 'table.size' : 'Dimensions', 'table.width' : 'Width', 'table.height' : 'Height', 'table.percent' : '%', 'table.px' : 'px', 'table.space' : 'Space', 'table.padding' : 'Padding', 'table.spacing' : 'Spacing', 'table.align' : 'Align', 'table.textAlign' : 'Horizontal', 'table.verticalAlign' : 'Vertical', 'table.alignDefault' : 'Default', 'table.alignLeft' : 'Left', 'table.alignCenter' : 'Center', 'table.alignRight' : 'Right', 'table.alignTop' : 'Top', 'table.alignMiddle' : 'Middle', 'table.alignBottom' : 'Bottom', 'table.alignBaseline' : 'Baseline', 'table.border' : 'Border', 'table.borderWidth' : 'Width', 'table.borderColor' : 'Color', 'table.backgroundColor' : 'Background', 'map.address' : 'Address: ', 'map.search' : 'Search', 'baidumap.address' : 'Address: ', 'baidumap.search' : 'Search', 'baidumap.insertDynamicMap' : 'Dynamic Map', 'anchor.name' : 'Anchor name', 'formatblock.formatBlock' : { h1 : 'Heading 1', h2 : 'Heading 2', h3 : 'Heading 3', h4 : 'Heading 4', p : 'Normal' }, 'fontname.fontName' : { 'Arial' : 'Arial', 'Arial Black' : 'Arial Black', 'Comic Sans MS' : 'Comic Sans MS', 'Courier New' : 'Courier New', 'Garamond' : 'Garamond', 'Georgia' : 'Georgia', 'Tahoma' : 'Tahoma', 'Times New Roman' : 'Times New Roman', 'Trebuchet MS' : 'Trebuchet MS', 'Verdana' : 'Verdana' }, 'lineheight.lineHeight' : [ {'1' : 'Line height 1'}, {'1.5' : 'Line height 1.5'}, {'2' : 'Line height 2'}, {'2.5' : 'Line height 2.5'}, {'3' : 'Line height 3'} ], 'template.selectTemplate' : 'Template', 'template.replaceContent' : 'Replace current content', 'template.fileList' : { '1.html' : 'Image and Text', '2.html' : 'Table', '3.html' : 'List' } }, 'en');
/*! * URI.js - Mutating URLs * URI Template Support - http://tools.ietf.org/html/rfc6570 * * Version: 1.16.0 * * Author: Rodney Rehm * Web: http://medialize.github.io/URI.js/ * * Licensed under * MIT License http://www.opensource.org/licenses/mit-license * GPL v3 http://opensource.org/licenses/GPL-3.0 * */ (function (root, factory) { 'use strict'; // https://github.com/umdjs/umd/blob/master/returnExports.js if (typeof exports === 'object') { // Node module.exports = factory(require('./URI')); } else if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['./URI'], factory); } else { // Browser globals (root is window) root.URITemplate = factory(root.URI, root); } }(this, function (URI, root) { 'use strict'; // FIXME: v2.0.0 renamce non-camelCase properties to uppercase /*jshint camelcase: false */ // save current URITemplate variable, if any var _URITemplate = root && root.URITemplate; var hasOwn = Object.prototype.hasOwnProperty; function URITemplate(expression) { // serve from cache where possible if (URITemplate._cache[expression]) { return URITemplate._cache[expression]; } // Allow instantiation without the 'new' keyword if (!(this instanceof URITemplate)) { return new URITemplate(expression); } this.expression = expression; URITemplate._cache[expression] = this; return this; } function Data(data) { this.data = data; this.cache = {}; } var p = URITemplate.prototype; // list of operators and their defined options var operators = { // Simple string expansion '' : { prefix: '', separator: ',', named: false, empty_name_separator: false, encode : 'encode' }, // Reserved character strings '+' : { prefix: '', separator: ',', named: false, empty_name_separator: false, encode : 'encodeReserved' }, // Fragment identifiers prefixed by '#' '#' : { prefix: '#', separator: ',', named: false, empty_name_separator: false, encode : 'encodeReserved' }, // Name labels or extensions prefixed by '.' '.' : { prefix: '.', separator: '.', named: false, empty_name_separator: false, encode : 'encode' }, // Path segments prefixed by '/' '/' : { prefix: '/', separator: '/', named: false, empty_name_separator: false, encode : 'encode' }, // Path parameter name or name=value pairs prefixed by ';' ';' : { prefix: ';', separator: ';', named: true, empty_name_separator: false, encode : 'encode' }, // Query component beginning with '?' and consisting // of name=value pairs separated by '&'; an '?' : { prefix: '?', separator: '&', named: true, empty_name_separator: true, encode : 'encode' }, // Continuation of query-style &name=value pairs // within a literal query component. '&' : { prefix: '&', separator: '&', named: true, empty_name_separator: true, encode : 'encode' } // The operator characters equals ("="), comma (","), exclamation ("!"), // at sign ("@"), and pipe ("|") are reserved for future extensions. }; // storage for already parsed templates URITemplate._cache = {}; // pattern to identify expressions [operator, variable-list] in template URITemplate.EXPRESSION_PATTERN = /\{([^a-zA-Z0-9%_]?)([^\}]+)(\}|$)/g; // pattern to identify variables [name, explode, maxlength] in variable-list URITemplate.VARIABLE_PATTERN = /^([^*:]+)((\*)|:(\d+))?$/; // pattern to verify variable name integrity URITemplate.VARIABLE_NAME_PATTERN = /[^a-zA-Z0-9%_]/; // expand parsed expression (expression, not template!) URITemplate.expand = function(expression, data) { // container for defined options for the given operator var options = operators[expression.operator]; // expansion type (include keys or not) var type = options.named ? 'Named' : 'Unnamed'; // list of variables within the expression var variables = expression.variables; // result buffer for evaluating the expression var buffer = []; var d, variable, i; for (i = 0; (variable = variables[i]); i++) { // fetch simplified data source d = data.get(variable.name); if (!d.val.length) { if (d.type) { // empty variables (empty string) // still lead to a separator being appended! buffer.push(''); } // no data, no action continue; } // expand the given variable buffer.push(URITemplate['expand' + type]( d, options, variable.explode, variable.explode && options.separator || ',', variable.maxlength, variable.name )); } if (buffer.length) { return options.prefix + buffer.join(options.separator); } else { // prefix is not prepended for empty expressions return ''; } }; // expand a named variable URITemplate.expandNamed = function(d, options, explode, separator, length, name) { // variable result buffer var result = ''; // peformance crap var encode = options.encode; var empty_name_separator = options.empty_name_separator; // flag noting if values are already encoded var _encode = !d[encode].length; // key for named expansion var _name = d.type === 2 ? '': URI[encode](name); var _value, i, l; // for each found value for (i = 0, l = d.val.length; i < l; i++) { if (length) { // maxlength must be determined before encoding can happen _value = URI[encode](d.val[i][1].substring(0, length)); if (d.type === 2) { // apply maxlength to keys of objects as well _name = URI[encode](d.val[i][0].substring(0, length)); } } else if (_encode) { // encode value _value = URI[encode](d.val[i][1]); if (d.type === 2) { // encode name and cache encoded value _name = URI[encode](d.val[i][0]); d[encode].push([_name, _value]); } else { // cache encoded value d[encode].push([undefined, _value]); } } else { // values are already encoded and can be pulled from cache _value = d[encode][i][1]; if (d.type === 2) { _name = d[encode][i][0]; } } if (result) { // unless we're the first value, prepend the separator result += separator; } if (!explode) { if (!i) { // first element, so prepend variable name result += URI[encode](name) + (empty_name_separator || _value ? '=' : ''); } if (d.type === 2) { // without explode-modifier, keys of objects are returned comma-separated result += _name + ','; } result += _value; } else { // only add the = if it is either default (?&) or there actually is a value (;) result += _name + (empty_name_separator || _value ? '=' : '') + _value; } } return result; }; // expand an unnamed variable URITemplate.expandUnnamed = function(d, options, explode, separator, length) { // variable result buffer var result = ''; // performance crap var encode = options.encode; var empty_name_separator = options.empty_name_separator; // flag noting if values are already encoded var _encode = !d[encode].length; var _name, _value, i, l; // for each found value for (i = 0, l = d.val.length; i < l; i++) { if (length) { // maxlength must be determined before encoding can happen _value = URI[encode](d.val[i][1].substring(0, length)); } else if (_encode) { // encode and cache value _value = URI[encode](d.val[i][1]); d[encode].push([ d.type === 2 ? URI[encode](d.val[i][0]) : undefined, _value ]); } else { // value already encoded, pull from cache _value = d[encode][i][1]; } if (result) { // unless we're the first value, prepend the separator result += separator; } if (d.type === 2) { if (length) { // maxlength also applies to keys of objects _name = URI[encode](d.val[i][0].substring(0, length)); } else { // at this point the name must already be encoded _name = d[encode][i][0]; } result += _name; if (explode) { // explode-modifier separates name and value by "=" result += (empty_name_separator || _value ? '=' : ''); } else { // no explode-modifier separates name and value by "," result += ','; } } result += _value; } return result; }; URITemplate.noConflict = function() { if (root.URITemplate === URITemplate) { root.URITemplate = _URITemplate; } return URITemplate; }; // expand template through given data map p.expand = function(data) { var result = ''; if (!this.parts || !this.parts.length) { // lazilyy parse the template this.parse(); } if (!(data instanceof Data)) { // make given data available through the // optimized data handling thingie data = new Data(data); } for (var i = 0, l = this.parts.length; i < l; i++) { /*jshint laxbreak: true */ result += typeof this.parts[i] === 'string' // literal string ? this.parts[i] // expression : URITemplate.expand(this.parts[i], data); /*jshint laxbreak: false */ } return result; }; // parse template into action tokens p.parse = function() { // performance crap var expression = this.expression; var ePattern = URITemplate.EXPRESSION_PATTERN; var vPattern = URITemplate.VARIABLE_PATTERN; var nPattern = URITemplate.VARIABLE_NAME_PATTERN; // token result buffer var parts = []; // position within source template var pos = 0; var variables, eMatch, vMatch; // RegExp is shared accross all templates, // which requires a manual reset ePattern.lastIndex = 0; // I don't like while(foo = bar()) loops, // to make things simpler I go while(true) and break when required while (true) { eMatch = ePattern.exec(expression); if (eMatch === null) { // push trailing literal parts.push(expression.substring(pos)); break; } else { // push leading literal parts.push(expression.substring(pos, eMatch.index)); pos = eMatch.index + eMatch[0].length; } if (!operators[eMatch[1]]) { throw new Error('Unknown Operator "' + eMatch[1] + '" in "' + eMatch[0] + '"'); } else if (!eMatch[3]) { throw new Error('Unclosed Expression "' + eMatch[0] + '"'); } // parse variable-list variables = eMatch[2].split(','); for (var i = 0, l = variables.length; i < l; i++) { vMatch = variables[i].match(vPattern); if (vMatch === null) { throw new Error('Invalid Variable "' + variables[i] + '" in "' + eMatch[0] + '"'); } else if (vMatch[1].match(nPattern)) { throw new Error('Invalid Variable Name "' + vMatch[1] + '" in "' + eMatch[0] + '"'); } variables[i] = { name: vMatch[1], explode: !!vMatch[3], maxlength: vMatch[4] && parseInt(vMatch[4], 10) }; } if (!variables.length) { throw new Error('Expression Missing Variable(s) "' + eMatch[0] + '"'); } parts.push({ expression: eMatch[0], operator: eMatch[1], variables: variables }); } if (!parts.length) { // template doesn't contain any expressions // so it is a simple literal string // this probably should fire a warning or something? parts.push(expression); } this.parts = parts; return this; }; // simplify data structures Data.prototype.get = function(key) { // performance crap var data = this.data; // cache for processed data-point var d = { // type of data 0: undefined/null, 1: string, 2: object, 3: array type: 0, // original values (except undefined/null) val: [], // cache for encoded values (only for non-maxlength expansion) encode: [], encodeReserved: [] }; var i, l, value; if (this.cache[key] !== undefined) { // we've already processed this key return this.cache[key]; } this.cache[key] = d; if (String(Object.prototype.toString.call(data)) === '[object Function]') { // data itself is a callback (global callback) value = data(key); } else if (String(Object.prototype.toString.call(data[key])) === '[object Function]') { // data is a map of callbacks (local callback) value = data[key](key); } else { // data is a map of data value = data[key]; } // generalize input into [ [name1, value1], [name2, value2], … ] // so expansion has to deal with a single data structure only if (value === undefined || value === null) { // undefined and null values are to be ignored completely return d; } else if (String(Object.prototype.toString.call(value)) === '[object Array]') { for (i = 0, l = value.length; i < l; i++) { if (value[i] !== undefined && value[i] !== null) { // arrays don't have names d.val.push([undefined, String(value[i])]); } } if (d.val.length) { // only treat non-empty arrays as arrays d.type = 3; // array } } else if (String(Object.prototype.toString.call(value)) === '[object Object]') { for (i in value) { if (hasOwn.call(value, i) && value[i] !== undefined && value[i] !== null) { // objects have keys, remember them for named expansion d.val.push([i, String(value[i])]); } } if (d.val.length) { // only treat non-empty objects as objects d.type = 2; // object } } else { d.type = 1; // primitive string (could've been string, number, boolean and objects with a toString()) // arrays don't have names d.val.push([undefined, String(value)]); } return d; }; // hook into URI for fluid access URI.expand = function(expression, data) { var template = new URITemplate(expression); var expansion = template.expand(data); return new URI(expansion); }; return URITemplate; }));
define( "dojo/cldr/nls/ja/buddhist", //begin v1.x content { "dateFormatItem-yM": "y/M", "dateFormatItem-yyyyMMMEd": "Gy年M月d日(EEE)", "dateFormatItem-yQ": "y/Q", "dayPeriods-format-wide-pm": "午後", "dateFormatItem-GGGGyMd": "GGGGy年M月d日", "dateFormatItem-MMMEd": "M月d日(E)", "dateTimeFormat-full": "{1}{0}", "dateFormatItem-hms": "ah:mm:ss", "dateFormatItem-yQQQ": "yQQQ", "dateFormatItem-MMdd": "MM/dd", "dateFormatItem-MMM": "LLL", "dayPeriods-format-wide-am": "午前", "dateFormatItem-y": "Gy年", "timeFormat-full": "H時mm分ss秒 zzzz", "dateFormatItem-yyyy": "Gy年", "dateFormatItem-Ed": "d日(EEE)", "dateFormatItem-yMMM": "y年M月", "days-standAlone-narrow": [ "日", "月", "火", "水", "木", "金", "土" ], "dateFormatItem-yyyyMM": "Gyy/MM", "dateFormat-long": "Gy年M月d日", "timeFormat-medium": "H:mm:ss", "dateFormatItem-Hm": "H:mm", "dateFormat-medium": "Gy/MM/dd", "dateFormatItem-Hms": "H:mm:ss", "dateFormatItem-ms": "mm:ss", "dateTimeFormat-long": "{1}{0}", "dateFormatItem-yyyyMd": "Gyy/M/d", "dateFormatItem-yyyyMMMd": "Gy年M月d日", "dateFormatItem-yyyyMEd": "Gyy/M/d(E)", "dateFormatItem-MMMd": "M月d日", "timeFormat-long": "H:mm:ss z", "timeFormat-short": "H:mm", "dateFormatItem-H": "H時", "days-format-abbr": [ "日", "月", "火", "水", "木", "金", "土" ], "dateFormatItem-M": "M月", "dateFormatItem-MEd": "M/d(E)", "dateFormatItem-hm": "ah:mm", "dateFormat-short": "Gy/MM/dd", "dateFormatItem-yMMMEd": "y年M月d日(EEE)", "dateFormat-full": "Gy年M月d日EEEE", "dateFormatItem-Md": "M/d", "dateFormatItem-yyyyQ": "Gyy/Q", "dateFormatItem-yMEd": "y/M/d(EEE)", "months-format-wide": [ "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月" ], "dateFormatItem-yyyyMMM": "Gy年M月", "dateFormatItem-d": "d日", "quarters-format-wide": [ "第1四半期", "第2四半期", "第3四半期", "第4四半期" ], "days-format-wide": [ "日曜日", "月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日" ], "dateFormatItem-h": "ah時" } //end v1.x content );
/*! * Documentation Content * Copyright (c) 2009 Packt Publishing, http://packtpub.com/ * Copyright (c) 2012 jQuery Foundation, http://jquery.org/ * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision history * and logs, available at http://github.com/jquery/api.jquery.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. */ intellisense.annotate(jQuery, { 'ajax': function() { /// <signature> /// <summary>Perform an asynchronous HTTP (Ajax) request.</summary> /// <param name="url" type="String">A string containing the URL to which the request is sent.</param> /// <param name="settings" type="Object">A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) below for a complete list of all settings.</param> /// <returns type="jqXHR" /> /// </signature> /// <signature> /// <summary>Perform an asynchronous HTTP (Ajax) request.</summary> /// <param name="settings" type="Object">A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup().</param> /// <returns type="jqXHR" /> /// </signature> }, 'ajaxPrefilter': function() { /// <signature> /// <summary>Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax().</summary> /// <param name="dataTypes" type="String">An optional string containing one or more space-separated dataTypes</param> /// <param name="handler(options, originalOptions, jqXHR)" type="Function">A handler to set default values for future Ajax requests.</param> /// </signature> }, 'ajaxSetup': function() { /// <signature> /// <summary>Set default values for future Ajax requests.</summary> /// <param name="options" type="Object">A set of key/value pairs that configure the default Ajax request. All options are optional.</param> /// </signature> }, 'boxModel': function() { /// <summary>Deprecated in jQuery 1.3 (see jQuery.support). States if the current page, in the user's browser, is being rendered using the W3C CSS Box Model.</summary> /// <returns type="Boolean" /> }, 'browser': function() { /// <summary>Contains flags for the useragent, read from navigator.userAgent. We recommend against using this property; please try to use feature detection instead (see jQuery.support). jQuery.browser may be moved to a plugin in a future release of jQuery.</summary> /// <returns type="Map" /> }, 'browser.version': function() { /// <summary>The version number of the rendering engine for the user's browser.</summary> /// <returns type="String" /> }, 'Callbacks': function() { /// <signature> /// <summary>A multi-purpose callbacks list object that provides a powerful way to manage callback lists.</summary> /// <param name="flags" type="String">An optional list of space-separated flags that change how the callback list behaves.</param> /// </signature> }, 'contains': function() { /// <signature> /// <summary>Check to see if a DOM element is within another DOM element.</summary> /// <param name="container" type="Element">The DOM element that may contain the other element.</param> /// <param name="contained" type="Element">The DOM element that may be contained by the other element.</param> /// <returns type="Boolean" /> /// </signature> }, 'cssHooks': function() { /// <summary>Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties.</summary> /// <returns type="Object" /> }, 'data': function() { /// <signature> /// <summary>Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element.</summary> /// <param name="element" type="Element">The DOM element to query for the data.</param> /// <param name="key" type="String">Name of the data stored.</param> /// <returns type="Object" /> /// </signature> /// <signature> /// <summary>Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element.</summary> /// <param name="element" type="Element">The DOM element to query for the data.</param> /// <returns type="Object" /> /// </signature> }, 'dequeue': function() { /// <signature> /// <summary>Execute the next function on the queue for the matched element.</summary> /// <param name="element" type="Element">A DOM element from which to remove and execute a queued function.</param> /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> /// <returns type="jQuery" /> /// </signature> }, 'each': function() { /// <signature> /// <summary>A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.</summary> /// <param name="collection" type="Object">The object or array to iterate over.</param> /// <param name="callback(indexInArray, valueOfElement)" type="Function">The function that will be executed on every object.</param> /// <returns type="Object" /> /// </signature> }, 'error': function() { /// <signature> /// <summary>Takes a string and throws an exception containing it.</summary> /// <param name="message" type="String">The message to send out.</param> /// </signature> }, 'extend': function() { /// <signature> /// <summary>Merge the contents of two or more objects together into the first object.</summary> /// <param name="target" type="Object">An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument.</param> /// <param name="object1" type="Object">An object containing additional properties to merge in.</param> /// <param name="objectN" type="Object">Additional objects containing properties to merge in.</param> /// <returns type="Object" /> /// </signature> /// <signature> /// <summary>Merge the contents of two or more objects together into the first object.</summary> /// <param name="deep" type="Boolean">If true, the merge becomes recursive (aka. deep copy).</param> /// <param name="target" type="Object">The object to extend. It will receive the new properties.</param> /// <param name="object1" type="Object">An object containing additional properties to merge in.</param> /// <param name="objectN" type="Object">Additional objects containing properties to merge in.</param> /// <returns type="Object" /> /// </signature> }, 'get': function() { /// <signature> /// <summary>Load data from the server using a HTTP GET request.</summary> /// <param name="url" type="String">A string containing the URL to which the request is sent.</param> /// <param name="data" type="String">A map or string that is sent to the server with the request.</param> /// <param name="success(data, textStatus, jqXHR)" type="Function">A callback function that is executed if the request succeeds.</param> /// <param name="dataType" type="String">The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).</param> /// <returns type="jqXHR" /> /// </signature> }, 'getJSON': function() { /// <signature> /// <summary>Load JSON-encoded data from the server using a GET HTTP request.</summary> /// <param name="url" type="String">A string containing the URL to which the request is sent.</param> /// <param name="data" type="Object">A map or string that is sent to the server with the request.</param> /// <param name="success(data, textStatus, jqXHR)" type="Function">A callback function that is executed if the request succeeds.</param> /// <returns type="jqXHR" /> /// </signature> }, 'getScript': function() { /// <signature> /// <summary>Load a JavaScript file from the server using a GET HTTP request, then execute it.</summary> /// <param name="url" type="String">A string containing the URL to which the request is sent.</param> /// <param name="success(script, textStatus, jqXHR)" type="Function">A callback function that is executed if the request succeeds.</param> /// <returns type="jqXHR" /> /// </signature> }, 'globalEval': function() { /// <signature> /// <summary>Execute some JavaScript code globally.</summary> /// <param name="code" type="String">The JavaScript code to execute.</param> /// </signature> }, 'grep': function() { /// <signature> /// <summary>Finds the elements of an array which satisfy a filter function. The original array is not affected.</summary> /// <param name="array" type="Array">The array to search through.</param> /// <param name="function(elementOfArray, indexInArray)" type="Function">The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object.</param> /// <param name="invert" type="Boolean">If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false.</param> /// <returns type="Array" /> /// </signature> }, 'hasData': function() { /// <signature> /// <summary>Determine whether an element has any jQuery data associated with it.</summary> /// <param name="element" type="Element">A DOM element to be checked for data.</param> /// <returns type="Boolean" /> /// </signature> }, 'holdReady': function() { /// <signature> /// <summary>Holds or releases the execution of jQuery's ready event.</summary> /// <param name="hold" type="Boolean">Indicates whether the ready hold is being requested or released</param> /// </signature> }, 'inArray': function() { /// <signature> /// <summary>Search for a specified value within an array and return its index (or -1 if not found).</summary> /// <param name="value" type="Object">The value to search for.</param> /// <param name="array" type="Array">An array through which to search.</param> /// <param name="fromIndex" type="Number">The index of the array at which to begin the search. The default is 0, which will search the whole array.</param> /// <returns type="Number" /> /// </signature> }, 'isArray': function() { /// <signature> /// <summary>Determine whether the argument is an array.</summary> /// <param name="obj" type="Object">Object to test whether or not it is an array.</param> /// <returns type="boolean" /> /// </signature> }, 'isEmptyObject': function() { /// <signature> /// <summary>Check to see if an object is empty (contains no properties).</summary> /// <param name="object" type="Object">The object that will be checked to see if it's empty.</param> /// <returns type="Boolean" /> /// </signature> }, 'isFunction': function() { /// <signature> /// <summary>Determine if the argument passed is a Javascript function object.</summary> /// <param name="obj" type="Object">Object to test whether or not it is a function.</param> /// <returns type="boolean" /> /// </signature> }, 'isNumeric': function() { /// <signature> /// <summary>Determines whether its argument is a number.</summary> /// <param name="value" type="Object">The value to be tested.</param> /// <returns type="Boolean" /> /// </signature> }, 'isPlainObject': function() { /// <signature> /// <summary>Check to see if an object is a plain object (created using "{}" or "new Object").</summary> /// <param name="object" type="Object">The object that will be checked to see if it's a plain object.</param> /// <returns type="Boolean" /> /// </signature> }, 'isWindow': function() { /// <signature> /// <summary>Determine whether the argument is a window.</summary> /// <param name="obj" type="Object">Object to test whether or not it is a window.</param> /// <returns type="boolean" /> /// </signature> }, 'isXMLDoc': function() { /// <signature> /// <summary>Check to see if a DOM node is within an XML document (or is an XML document).</summary> /// <param name="node" type="Element">The DOM node that will be checked to see if it's in an XML document.</param> /// <returns type="Boolean" /> /// </signature> }, 'makeArray': function() { /// <signature> /// <summary>Convert an array-like object into a true JavaScript array.</summary> /// <param name="obj" type="Object">Any object to turn into a native Array.</param> /// <returns type="Array" /> /// </signature> }, 'map': function() { /// <signature> /// <summary>Translate all items in an array or object to new array of items.</summary> /// <param name="array" type="Array">The Array to translate.</param> /// <param name="callback(elementOfArray, indexInArray)" type="Function">The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object.</param> /// <returns type="Array" /> /// </signature> /// <signature> /// <summary>Translate all items in an array or object to new array of items.</summary> /// <param name="arrayOrObject" type="Object">The Array or Object to translate.</param> /// <param name="callback( value, indexOrKey )" type="Function">The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object.</param> /// <returns type="Array" /> /// </signature> }, 'merge': function() { /// <signature> /// <summary>Merge the contents of two arrays together into the first array.</summary> /// <param name="first" type="Array">The first array to merge, the elements of second added.</param> /// <param name="second" type="Array">The second array to merge into the first, unaltered.</param> /// <returns type="Array" /> /// </signature> }, 'noConflict': function() { /// <signature> /// <summary>Relinquish jQuery's control of the $ variable.</summary> /// <param name="removeAll" type="Boolean">A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself).</param> /// <returns type="Object" /> /// </signature> }, 'noop': function() { /// <summary>An empty function.</summary> /// <returns type="Function" /> }, 'now': function() { /// <summary>Return a number representing the current time.</summary> /// <returns type="Number" /> }, 'param': function() { /// <signature> /// <summary>Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.</summary> /// <param name="obj" type="Object">An array or object to serialize.</param> /// <returns type="String" /> /// </signature> /// <signature> /// <summary>Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.</summary> /// <param name="obj" type="Object">An array or object to serialize.</param> /// <param name="traditional" type="Boolean">A Boolean indicating whether to perform a traditional "shallow" serialization.</param> /// <returns type="String" /> /// </signature> }, 'parseJSON': function() { /// <signature> /// <summary>Takes a well-formed JSON string and returns the resulting JavaScript object.</summary> /// <param name="json" type="String">The JSON string to parse.</param> /// <returns type="Object" /> /// </signature> }, 'parseXML': function() { /// <signature> /// <summary>Parses a string into an XML document.</summary> /// <param name="data" type="String">a well-formed XML string to be parsed</param> /// <returns type="XMLDocument" /> /// </signature> }, 'post': function() { /// <signature> /// <summary>Load data from the server using a HTTP POST request.</summary> /// <param name="url" type="String">A string containing the URL to which the request is sent.</param> /// <param name="data" type="String">A map or string that is sent to the server with the request.</param> /// <param name="success(data, textStatus, jqXHR)" type="Function">A callback function that is executed if the request succeeds.</param> /// <param name="dataType" type="String">The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).</param> /// <returns type="jqXHR" /> /// </signature> }, 'proxy': function() { /// <signature> /// <summary>Takes a function and returns a new one that will always have a particular context.</summary> /// <param name="function" type="Function">The function whose context will be changed.</param> /// <param name="context" type="Object">The object to which the context (this) of the function should be set.</param> /// <returns type="Function" /> /// </signature> /// <signature> /// <summary>Takes a function and returns a new one that will always have a particular context.</summary> /// <param name="context" type="Object">The object to which the context of the function should be set.</param> /// <param name="name" type="String">The name of the function whose context will be changed (should be a property of the context object).</param> /// <returns type="Function" /> /// </signature> }, 'queue': function() { /// <signature> /// <summary>Manipulate the queue of functions to be executed on the matched element.</summary> /// <param name="element" type="Element">A DOM element where the array of queued functions is attached.</param> /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> /// <param name="newQueue" type="Array">An array of functions to replace the current queue contents.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Manipulate the queue of functions to be executed on the matched element.</summary> /// <param name="element" type="Element">A DOM element on which to add a queued function.</param> /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> /// <param name="callback()" type="Function">The new function to add to the queue.</param> /// <returns type="jQuery" /> /// </signature> }, 'removeData': function() { /// <signature> /// <summary>Remove a previously-stored piece of data.</summary> /// <param name="element" type="Element">A DOM element from which to remove data.</param> /// <param name="name" type="String">A string naming the piece of data to remove.</param> /// <returns type="jQuery" /> /// </signature> }, 'sub': function() { /// <summary>Creates a new copy of jQuery whose properties and methods can be modified without affecting the original jQuery object.</summary> /// <returns type="jQuery" /> }, 'support': function() { /// <summary>A collection of properties that represent the presence of different browser features or bugs. Primarily intended for jQuery's internal use; specific properties may be removed when they are no longer needed internally to improve page startup performance.</summary> /// <returns type="Object" /> }, 'trim': function() { /// <signature> /// <summary>Remove the whitespace from the beginning and end of a string.</summary> /// <param name="str" type="String">The string to trim.</param> /// <returns type="String" /> /// </signature> }, 'type': function() { /// <signature> /// <summary>Determine the internal JavaScript [[Class]] of an object.</summary> /// <param name="obj" type="Object">Object to get the internal JavaScript [[Class]] of.</param> /// <returns type="String" /> /// </signature> }, 'unique': function() { /// <signature> /// <summary>Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.</summary> /// <param name="array" type="Array">The Array of DOM elements.</param> /// <returns type="Array" /> /// </signature> }, 'when': function() { /// <signature> /// <summary>Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.</summary> /// <param name="deferreds" type="Deferred">One or more Deferred objects, or plain JavaScript objects.</param> /// <returns type="Promise" /> /// </signature> }, }); var _1228819969 = jQuery.Callbacks; jQuery.Callbacks = function(flags) { var _object = _1228819969(flags); intellisense.annotate(_object, { 'add': function() { /// <signature> /// <summary>Add a callback or a collection of callbacks to a callback list.</summary> /// <param name="callbacks" type="Function">A function, or array of functions, that are to be added to the callback list.</param> /// </signature> }, 'disable': function() { /// <summary>Disable a callback list from doing anything more.</summary> }, 'empty': function() { /// <summary>Remove all of the callbacks from a list.</summary> }, 'fire': function() { /// <signature> /// <summary>Call all of the callbacks with the given arguments</summary> /// <param name="arguments" type="">The argument or list of arguments to pass back to the callback list.</param> /// </signature> }, 'fired': function() { /// <summary>Determine if the callbacks have already been called at least once.</summary> /// <returns type="Boolean" /> }, 'fireWith': function() { /// <signature> /// <summary>Call all callbacks in a list with the given context and arguments.</summary> /// <param name="context" type="">A reference to the context in which the callbacks in the list should be fired.</param> /// <param name="args" type="">An argument, or array of arguments, to pass to the callbacks in the list.</param> /// </signature> }, 'has': function() { /// <signature> /// <summary>Determine whether a supplied callback is in a list</summary> /// <param name="callback" type="Function">The callback to search for.</param> /// <returns type="Boolean" /> /// </signature> }, 'lock': function() { /// <summary>Lock a callback list in its current state.</summary> }, 'locked': function() { /// <summary>Determine if the callbacks list has been locked.</summary> /// <returns type="Boolean" /> }, 'remove': function() { /// <signature> /// <summary>Remove a callback or a collection of callbacks from a callback list.</summary> /// <param name="callbacks" type="Function">A function, or array of functions, that are to be removed from the callback list.</param> /// </signature> }, }); return _object; }; var _731531622 = jQuery.Deferred; jQuery.Deferred = function(func) { var _object = _731531622(func); intellisense.annotate(_object, { 'always': function() { /// <signature> /// <summary>Add handlers to be called when the Deferred object is either resolved or rejected.</summary> /// <param name="alwaysCallbacks" type="Function">A function, or array of functions, that is called when the Deferred is resolved or rejected.</param> /// <param name="alwaysCallbacks" type="Function">Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected.</param> /// <returns type="Deferred" /> /// </signature> }, 'done': function() { /// <signature> /// <summary>Add handlers to be called when the Deferred object is resolved.</summary> /// <param name="doneCallbacks" type="Function">A function, or array of functions, that are called when the Deferred is resolved.</param> /// <param name="doneCallbacks" type="Function">Optional additional functions, or arrays of functions, that are called when the Deferred is resolved.</param> /// <returns type="Deferred" /> /// </signature> }, 'fail': function() { /// <signature> /// <summary>Add handlers to be called when the Deferred object is rejected.</summary> /// <param name="failCallbacks" type="Function">A function, or array of functions, that are called when the Deferred is rejected.</param> /// <param name="failCallbacks" type="Function">Optional additional functions, or arrays of functions, that are called when the Deferred is rejected.</param> /// <returns type="Deferred" /> /// </signature> }, 'isRejected': function() { /// <summary>Determine whether a Deferred object has been rejected.</summary> /// <returns type="Boolean" /> }, 'isResolved': function() { /// <summary>Determine whether a Deferred object has been resolved.</summary> /// <returns type="Boolean" /> }, 'notify': function() { /// <signature> /// <summary>Call the progressCallbacks on a Deferred object with the given args.</summary> /// <param name="args" type="Object">Optional arguments that are passed to the progressCallbacks.</param> /// <returns type="Deferred" /> /// </signature> }, 'notifyWith': function() { /// <signature> /// <summary>Call the progressCallbacks on a Deferred object with the given context and args.</summary> /// <param name="context" type="Object">Context passed to the progressCallbacks as the this object.</param> /// <param name="args" type="Object">Optional arguments that are passed to the progressCallbacks.</param> /// <returns type="Deferred" /> /// </signature> }, 'pipe': function() { /// <signature> /// <summary>Utility method to filter and/or chain Deferreds.</summary> /// <param name="doneFilter" type="Function">An optional function that is called when the Deferred is resolved.</param> /// <param name="failFilter" type="Function">An optional function that is called when the Deferred is rejected.</param> /// <returns type="Promise" /> /// </signature> /// <signature> /// <summary>Utility method to filter and/or chain Deferreds.</summary> /// <param name="doneFilter" type="Function">An optional function that is called when the Deferred is resolved.</param> /// <param name="failFilter" type="Function">An optional function that is called when the Deferred is rejected.</param> /// <param name="progressFilter" type="Function">An optional function that is called when progress notifications are sent to the Deferred.</param> /// <returns type="Promise" /> /// </signature> }, 'progress': function() { /// <signature> /// <summary>Add handlers to be called when the Deferred object generates progress notifications.</summary> /// <param name="progressCallbacks" type="Function">A function, or array of functions, that is called when the Deferred generates progress notifications.</param> /// <returns type="Deferred" /> /// </signature> }, 'promise': function() { /// <signature> /// <summary>Return a Deferred's Promise object.</summary> /// <param name="target" type="Object">Object onto which the promise methods have to be attached</param> /// <returns type="Promise" /> /// </signature> }, 'reject': function() { /// <signature> /// <summary>Reject a Deferred object and call any failCallbacks with the given args.</summary> /// <param name="args" type="Object">Optional arguments that are passed to the failCallbacks.</param> /// <returns type="Deferred" /> /// </signature> }, 'rejectWith': function() { /// <signature> /// <summary>Reject a Deferred object and call any failCallbacks with the given context and args.</summary> /// <param name="context" type="Object">Context passed to the failCallbacks as the this object.</param> /// <param name="args" type="Array">An optional array of arguments that are passed to the failCallbacks.</param> /// <returns type="Deferred" /> /// </signature> }, 'resolve': function() { /// <signature> /// <summary>Resolve a Deferred object and call any doneCallbacks with the given args.</summary> /// <param name="args" type="Object">Optional arguments that are passed to the doneCallbacks.</param> /// <returns type="Deferred" /> /// </signature> }, 'resolveWith': function() { /// <signature> /// <summary>Resolve a Deferred object and call any doneCallbacks with the given context and args.</summary> /// <param name="context" type="Object">Context passed to the doneCallbacks as the this object.</param> /// <param name="args" type="Array">An optional array of arguments that are passed to the doneCallbacks.</param> /// <returns type="Deferred" /> /// </signature> }, 'state': function() { /// <summary>Determine the current state of a Deferred object.</summary> /// <returns type="String" /> }, 'then': function() { /// <signature> /// <summary>Add handlers to be called when the Deferred object is resolved or rejected.</summary> /// <param name="doneCallbacks" type="Function">A function, or array of functions, called when the Deferred is resolved.</param> /// <param name="failCallbacks" type="Function">A function, or array of functions, called when the Deferred is rejected.</param> /// <returns type="Deferred" /> /// </signature> /// <signature> /// <summary>Add handlers to be called when the Deferred object is resolved or rejected.</summary> /// <param name="doneCallbacks" type="Function">A function, or array of functions, called when the Deferred is resolved.</param> /// <param name="failCallbacks" type="Function">A function, or array of functions, called when the Deferred is rejected.</param> /// <param name="progressCallbacks" type="Function">A function, or array of functions, called when the Deferred notifies progress.</param> /// <returns type="Deferred" /> /// </signature> }, }); return _object; }; intellisense.annotate(jQuery.Event.prototype, { 'currentTarget': function() { /// <summary>The current DOM element within the event bubbling phase.</summary> /// <returns type="Element" /> }, 'data': function() { /// <summary>An optional data map passed to an event method when the current executing handler is bound.</summary> }, 'delegateTarget': function() { /// <summary>The element where the currently-called jQuery event handler was attached.</summary> /// <returns type="Element" /> }, 'isDefaultPrevented': function() { /// <summary>Returns whether event.preventDefault() was ever called on this event object.</summary> /// <returns type="Boolean" /> }, 'isImmediatePropagationStopped': function() { /// <summary>Returns whether event.stopImmediatePropagation() was ever called on this event object.</summary> /// <returns type="Boolean" /> }, 'isPropagationStopped': function() { /// <summary>Returns whether event.stopPropagation() was ever called on this event object.</summary> /// <returns type="Boolean" /> }, 'namespace': function() { /// <summary>The namespace specified when the event was triggered.</summary> /// <returns type="String" /> }, 'pageX': function() { /// <summary>The mouse position relative to the left edge of the document.</summary> /// <returns type="Number" /> }, 'pageY': function() { /// <summary>The mouse position relative to the top edge of the document.</summary> /// <returns type="Number" /> }, 'preventDefault': function() { /// <summary>If this method is called, the default action of the event will not be triggered.</summary> }, 'relatedTarget': function() { /// <summary>The other DOM element involved in the event, if any.</summary> /// <returns type="Element" /> }, 'result': function() { /// <summary>The last value returned by an event handler that was triggered by this event, unless the value was undefined.</summary> /// <returns type="Object" /> }, 'stopImmediatePropagation': function() { /// <summary>Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.</summary> }, 'stopPropagation': function() { /// <summary>Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.</summary> }, 'target': function() { /// <summary>The DOM element that initiated the event.</summary> /// <returns type="Element" /> }, 'timeStamp': function() { /// <summary>The difference in milliseconds between the time the browser created the event and January 1, 1970.</summary> /// <returns type="Number" /> }, 'type': function() { /// <summary>Describes the nature of the event.</summary> /// <returns type="String" /> }, 'which': function() { /// <summary>For key or mouse events, this property indicates the specific key or button that was pressed.</summary> /// <returns type="Number" /> }, }); intellisense.annotate(jQuery.fn, { 'add': function() { /// <signature> /// <summary>Add elements to the set of matched elements.</summary> /// <param name="selector" type="String">A string representing a selector expression to find additional elements to add to the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Add elements to the set of matched elements.</summary> /// <param name="elements" type="Array">One or more elements to add to the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Add elements to the set of matched elements.</summary> /// <param name="html" type="String">An HTML fragment to add to the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Add elements to the set of matched elements.</summary> /// <param name="jQuery object" type="jQuery object ">An existing jQuery object to add to the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Add elements to the set of matched elements.</summary> /// <param name="selector" type="String">A string representing a selector expression to find additional elements to add to the set of matched elements.</param> /// <param name="context" type="Element">The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method.</param> /// <returns type="jQuery" /> /// </signature> }, 'addClass': function() { /// <signature> /// <summary>Adds the specified class(es) to each of the set of matched elements.</summary> /// <param name="className" type="String">One or more class names to be added to the class attribute of each matched element.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Adds the specified class(es) to each of the set of matched elements.</summary> /// <param name="function(index, currentClass)" type="Function">A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'after': function() { /// <signature> /// <summary>Insert content, specified by the parameter, after each element in the set of matched elements.</summary> /// <param name="content" type="jQuery">HTML string, DOM element, or jQuery object to insert after each element in the set of matched elements.</param> /// <param name="content" type="jQuery">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Insert content, specified by the parameter, after each element in the set of matched elements.</summary> /// <param name="function(index)" type="Function">A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'ajaxComplete': function() { /// <signature> /// <summary>Register a handler to be called when Ajax requests complete. This is an Ajax Event.</summary> /// <param name="handler(event, XMLHttpRequest, ajaxOptions)" type="Function">The function to be invoked.</param> /// <returns type="jQuery" /> /// </signature> }, 'ajaxError': function() { /// <signature> /// <summary>Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event.</summary> /// <param name="handler(event, jqXHR, ajaxSettings, thrownError)" type="Function">The function to be invoked.</param> /// <returns type="jQuery" /> /// </signature> }, 'ajaxSend': function() { /// <signature> /// <summary>Attach a function to be executed before an Ajax request is sent. This is an Ajax Event.</summary> /// <param name="handler(event, jqXHR, ajaxOptions)" type="Function">The function to be invoked.</param> /// <returns type="jQuery" /> /// </signature> }, 'ajaxStart': function() { /// <signature> /// <summary>Register a handler to be called when the first Ajax request begins. This is an Ajax Event.</summary> /// <param name="handler()" type="Function">The function to be invoked.</param> /// <returns type="jQuery" /> /// </signature> }, 'ajaxStop': function() { /// <signature> /// <summary>Register a handler to be called when all Ajax requests have completed. This is an Ajax Event.</summary> /// <param name="handler()" type="Function">The function to be invoked.</param> /// <returns type="jQuery" /> /// </signature> }, 'ajaxSuccess': function() { /// <signature> /// <summary>Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.</summary> /// <param name="handler(event, XMLHttpRequest, ajaxOptions)" type="Function">The function to be invoked.</param> /// <returns type="jQuery" /> /// </signature> }, 'all': function() { /// <summary>Selects all elements.</summary> }, 'andSelf': function() { /// <summary>Add the previous set of elements on the stack to the current set.</summary> /// <returns type="jQuery" /> }, 'animate': function() { /// <signature> /// <summary>Perform a custom animation of a set of CSS properties.</summary> /// <param name="properties" type="Object">A map of CSS properties that the animation will move toward.</param> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Perform a custom animation of a set of CSS properties.</summary> /// <param name="properties" type="Object">A map of CSS properties that the animation will move toward.</param> /// <param name="options" type="Object">A map of additional options to pass to the method. Supported keys: duration: A string or number determining how long the animation will run.easing: A string indicating which easing function to use for the transition.complete: A function to call once the animation is complete.step: A function to be called after each step of the animation.queue: A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string.specialEasing: A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions (added 1.4).</param> /// <returns type="jQuery" /> /// </signature> }, 'animated': function() { /// <summary>Select all elements that are in the progress of an animation at the time the selector is run.</summary> }, 'append': function() { /// <signature> /// <summary>Insert content, specified by the parameter, to the end of each element in the set of matched elements.</summary> /// <param name="content" type="jQuery">DOM element, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param> /// <param name="content" type="jQuery">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Insert content, specified by the parameter, to the end of each element in the set of matched elements.</summary> /// <param name="function(index, html)" type="Function">A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'appendTo': function() { /// <signature> /// <summary>Insert every element in the set of matched elements to the end of the target.</summary> /// <param name="target" type="jQuery">A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.</param> /// <returns type="jQuery" /> /// </signature> }, 'attr': function() { /// <signature> /// <summary>Set one or more attributes for the set of matched elements.</summary> /// <param name="attributeName" type="String">The name of the attribute to set.</param> /// <param name="value" type="Number">A value to set for the attribute.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set one or more attributes for the set of matched elements.</summary> /// <param name="map" type="Object">A map of attribute-value pairs to set.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set one or more attributes for the set of matched elements.</summary> /// <param name="attributeName" type="String">The name of the attribute to set.</param> /// <param name="function(index, attr)" type="Function">A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments.</param> /// <returns type="jQuery" /> /// </signature> }, 'attributeContains': function() { /// <signature> /// <summary>Selects elements that have the specified attribute with a value containing the a given substring.</summary> /// <param name="attribute" type="String">An attribute name.</param> /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> /// </signature> }, 'attributeContainsPrefix': function() { /// <signature> /// <summary>Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-).</summary> /// <param name="attribute" type="String">An attribute name.</param> /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> /// </signature> }, 'attributeContainsWord': function() { /// <signature> /// <summary>Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.</summary> /// <param name="attribute" type="String">An attribute name.</param> /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> /// </signature> }, 'attributeEndsWith': function() { /// <signature> /// <summary>Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.</summary> /// <param name="attribute" type="String">An attribute name.</param> /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> /// </signature> }, 'attributeEquals': function() { /// <signature> /// <summary>Selects elements that have the specified attribute with a value exactly equal to a certain value.</summary> /// <param name="attribute" type="String">An attribute name.</param> /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> /// </signature> }, 'attributeHas': function() { /// <signature> /// <summary>Selects elements that have the specified attribute, with any value.</summary> /// <param name="attribute" type="String">An attribute name.</param> /// </signature> }, 'attributeMultiple': function() { /// <signature> /// <summary>Matches elements that match all of the specified attribute filters.</summary> /// <param name="attributeFilter1" type="String">An attribute filter.</param> /// <param name="attributeFilter2" type="String">Another attribute filter, reducing the selection even more</param> /// <param name="attributeFilterN" type="String">As many more attribute filters as necessary</param> /// </signature> }, 'attributeNotEqual': function() { /// <signature> /// <summary>Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.</summary> /// <param name="attribute" type="String">An attribute name.</param> /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> /// </signature> }, 'attributeStartsWith': function() { /// <signature> /// <summary>Selects elements that have the specified attribute with a value beginning exactly with a given string.</summary> /// <param name="attribute" type="String">An attribute name.</param> /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> /// </signature> }, 'before': function() { /// <signature> /// <summary>Insert content, specified by the parameter, before each element in the set of matched elements.</summary> /// <param name="content" type="jQuery">HTML string, DOM element, or jQuery object to insert before each element in the set of matched elements.</param> /// <param name="content" type="jQuery">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Insert content, specified by the parameter, before each element in the set of matched elements.</summary> /// <param name="function" type="Function">A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'bind': function() { /// <signature> /// <summary>Attach a handler to an event for the elements.</summary> /// <param name="eventType" type="String">A string containing one or more DOM event types, such as "click" or "submit," or custom event names.</param> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach a handler to an event for the elements.</summary> /// <param name="eventType" type="String">A string containing one or more DOM event types, such as "click" or "submit," or custom event names.</param> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="preventBubble" type="Boolean">Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach a handler to an event for the elements.</summary> /// <param name="events" type="Object">A map of one or more DOM event types and functions to execute for them.</param> /// <returns type="jQuery" /> /// </signature> }, 'blur': function() { /// <signature> /// <summary>Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'button': function() { /// <summary>Selects all button elements and elements of type button.</summary> }, 'change': function() { /// <signature> /// <summary>Bind an event handler to the "change" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "change" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'checkbox': function() { /// <summary>Selects all elements of type checkbox.</summary> }, 'checked': function() { /// <summary>Matches all elements that are checked.</summary> }, 'child': function() { /// <signature> /// <summary>Selects all direct child elements specified by "child" of elements specified by "parent".</summary> /// <param name="parent" type="String">Any valid selector.</param> /// <param name="child" type="String">A selector to filter the child elements.</param> /// </signature> }, 'children': function() { /// <signature> /// <summary>Get the children of each element in the set of matched elements, optionally filtered by a selector.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'class': function() { /// <signature> /// <summary>Selects all elements with the given class.</summary> /// <param name="class" type="String">A class to search for. An element can have multiple classes; only one of them must match.</param> /// </signature> }, 'clearQueue': function() { /// <signature> /// <summary>Remove from the queue all items that have not yet been run.</summary> /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> /// <returns type="jQuery" /> /// </signature> }, 'click': function() { /// <signature> /// <summary>Bind an event handler to the "click" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "click" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'clone': function() { /// <signature> /// <summary>Create a deep copy of the set of matched elements.</summary> /// <param name="withDataAndEvents" type="Boolean">A Boolean indicating whether event handlers should be copied along with the elements. As of jQuery 1.4, element data will be copied as well.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Create a deep copy of the set of matched elements.</summary> /// <param name="withDataAndEvents" type="Boolean">A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. *In jQuery 1.5.0 the default value was incorrectly true; it was changed back to false in 1.5.1 and up.</param> /// <param name="deepWithDataAndEvents" type="Boolean">A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false).</param> /// <returns type="jQuery" /> /// </signature> }, 'closest': function() { /// <signature> /// <summary>Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <param name="context" type="Element">A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.</summary> /// <param name="jQuery object" type="jQuery">A jQuery object to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.</summary> /// <param name="element" type="Element">An element to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'contains': function() { /// <signature> /// <summary>Select all elements that contain the specified text.</summary> /// <param name="text" type="String">A string of text to look for. It's case sensitive.</param> /// </signature> }, 'contents': function() { /// <summary>Get the children of each element in the set of matched elements, including text and comment nodes.</summary> /// <returns type="jQuery" /> }, 'context': function() { /// <summary>The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document.</summary> /// <returns type="Element" /> }, 'css': function() { /// <signature> /// <summary>Set one or more CSS properties for the set of matched elements.</summary> /// <param name="propertyName" type="String">A CSS property name.</param> /// <param name="value" type="Number">A value to set for the property.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set one or more CSS properties for the set of matched elements.</summary> /// <param name="propertyName" type="String">A CSS property name.</param> /// <param name="function(index, value)" type="Function">A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set one or more CSS properties for the set of matched elements.</summary> /// <param name="map" type="Object">A map of property-value pairs to set.</param> /// <returns type="jQuery" /> /// </signature> }, 'data': function() { /// <signature> /// <summary>Store arbitrary data associated with the matched elements.</summary> /// <param name="key" type="String">A string naming the piece of data to set.</param> /// <param name="value" type="Object">The new data value; it can be any Javascript type including Array or Object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Store arbitrary data associated with the matched elements.</summary> /// <param name="obj" type="Object">An object of key-value pairs of data to update.</param> /// <returns type="jQuery" /> /// </signature> }, 'dblclick': function() { /// <signature> /// <summary>Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'delay': function() { /// <signature> /// <summary>Set a timer to delay execution of subsequent items in the queue.</summary> /// <param name="duration" type="Number">An integer indicating the number of milliseconds to delay execution of the next item in the queue.</param> /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> /// <returns type="jQuery" /> /// </signature> }, 'delegate': function() { /// <signature> /// <summary>Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.</summary> /// <param name="selector" type="String">A selector to filter the elements that trigger the event.</param> /// <param name="eventType" type="String">A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names.</param> /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.</summary> /// <param name="selector" type="String">A selector to filter the elements that trigger the event.</param> /// <param name="eventType" type="String">A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names.</param> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.</summary> /// <param name="selector" type="String">A selector to filter the elements that trigger the event.</param> /// <param name="events" type="Object">A map of one or more event types and functions to execute for them.</param> /// <returns type="jQuery" /> /// </signature> }, 'dequeue': function() { /// <signature> /// <summary>Execute the next function on the queue for the matched elements.</summary> /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> /// <returns type="jQuery" /> /// </signature> }, 'descendant': function() { /// <signature> /// <summary>Selects all elements that are descendants of a given ancestor.</summary> /// <param name="ancestor" type="String">Any valid selector.</param> /// <param name="descendant" type="String">A selector to filter the descendant elements.</param> /// </signature> }, 'detach': function() { /// <signature> /// <summary>Remove the set of matched elements from the DOM.</summary> /// <param name="selector" type="String">A selector expression that filters the set of matched elements to be removed.</param> /// <returns type="jQuery" /> /// </signature> }, 'die': function() { /// <signature> /// <summary>Remove an event handler previously attached using .live() from the elements.</summary> /// <param name="eventType" type="String">A string containing a JavaScript event type, such as click or keydown.</param> /// <param name="handler" type="String">The function that is no longer to be executed.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove an event handler previously attached using .live() from the elements.</summary> /// <param name="eventTypes" type="Object">A map of one or more event types, such as click or keydown and their corresponding functions that are no longer to be executed.</param> /// <returns type="jQuery" /> /// </signature> }, 'disabled': function() { /// <summary>Selects all elements that are disabled.</summary> }, 'each': function() { /// <signature> /// <summary>Iterate over a jQuery object, executing a function for each matched element.</summary> /// <param name="function(index, Element)" type="Function">A function to execute for each matched element.</param> /// <returns type="jQuery" /> /// </signature> }, 'element': function() { /// <signature> /// <summary>Selects all elements with the given tag name.</summary> /// <param name="element" type="String">An element to search for. Refers to the tagName of DOM nodes.</param> /// </signature> }, 'empty': function() { /// <summary>Select all elements that have no children (including text nodes).</summary> }, 'enabled': function() { /// <summary>Selects all elements that are enabled.</summary> }, 'end': function() { /// <summary>End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.</summary> /// <returns type="jQuery" /> }, 'eq': function() { /// <signature> /// <summary>Reduce the set of matched elements to the one at the specified index.</summary> /// <param name="index" type="Number">An integer indicating the 0-based position of the element.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Reduce the set of matched elements to the one at the specified index.</summary> /// <param name="-index" type="Number">An integer indicating the position of the element, counting backwards from the last element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'error': function() { /// <signature> /// <summary>Bind an event handler to the "error" JavaScript event.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute when the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "error" JavaScript event.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'even': function() { /// <summary>Selects even elements, zero-indexed. See also odd.</summary> }, 'fadeIn': function() { /// <signature> /// <summary>Display the matched elements by fading them to opaque.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display the matched elements by fading them to opaque.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> }, 'fadeOut': function() { /// <signature> /// <summary>Hide the matched elements by fading them to transparent.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Hide the matched elements by fading them to transparent.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> }, 'fadeTo': function() { /// <signature> /// <summary>Adjust the opacity of the matched elements.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="opacity" type="Number">A number between 0 and 1 denoting the target opacity.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Adjust the opacity of the matched elements.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="opacity" type="Number">A number between 0 and 1 denoting the target opacity.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> }, 'fadeToggle': function() { /// <signature> /// <summary>Display or hide the matched elements by animating their opacity.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> }, 'file': function() { /// <summary>Selects all elements of type file.</summary> }, 'filter': function() { /// <signature> /// <summary>Reduce the set of matched elements to those that match the selector or pass the function's test.</summary> /// <param name="selector" type="String">A string containing a selector expression to match the current set of elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Reduce the set of matched elements to those that match the selector or pass the function's test.</summary> /// <param name="function(index)" type="Function">A function used as a test for each element in the set. this is the current DOM element.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Reduce the set of matched elements to those that match the selector or pass the function's test.</summary> /// <param name="element" type="Element">An element to match the current set of elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Reduce the set of matched elements to those that match the selector or pass the function's test.</summary> /// <param name="jQuery object" type="Object">An existing jQuery object to match the current set of elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'find': function() { /// <signature> /// <summary>Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.</summary> /// <param name="jQuery object" type="Object">A jQuery object to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.</summary> /// <param name="element" type="Element">An element to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'first': function() { /// <summary>Selects the first matched element.</summary> }, 'first-child': function() { /// <summary>Selects all elements that are the first child of their parent.</summary> }, 'focus': function() { /// <signature> /// <summary>Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'focusin': function() { /// <signature> /// <summary>Bind an event handler to the "focusin" event.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "focusin" event.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'focusout': function() { /// <signature> /// <summary>Bind an event handler to the "focusout" JavaScript event.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "focusout" JavaScript event.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'get': function() { /// <signature> /// <summary>Retrieve the DOM elements matched by the jQuery object.</summary> /// <param name="index" type="Number">A zero-based integer indicating which element to retrieve.</param> /// <returns type="Element, Array" /> /// </signature> }, 'gt': function() { /// <signature> /// <summary>Select all elements at an index greater than index within the matched set.</summary> /// <param name="index" type="Number">Zero-based index.</param> /// </signature> }, 'has': function() { /// <signature> /// <summary>Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.</summary> /// <param name="contained" type="Element">A DOM element to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'hasClass': function() { /// <signature> /// <summary>Determine whether any of the matched elements are assigned the given class.</summary> /// <param name="className" type="String">The class name to search for.</param> /// <returns type="Boolean" /> /// </signature> }, 'header': function() { /// <summary>Selects all elements that are headers, like h1, h2, h3 and so on.</summary> }, 'height': function() { /// <signature> /// <summary>Set the CSS height of every matched element.</summary> /// <param name="value" type="Number">An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string).</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set the CSS height of every matched element.</summary> /// <param name="function(index, height)" type="Function">A function returning the height to set. Receives the index position of the element in the set and the old height as arguments. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'hidden': function() { /// <summary>Selects all elements that are hidden.</summary> }, 'hide': function() { /// <signature> /// <summary>Hide the matched elements.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Hide the matched elements.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> }, 'hover': function() { /// <signature> /// <summary>Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.</summary> /// <param name="handlerIn(eventObject)" type="Function">A function to execute when the mouse pointer enters the element.</param> /// <param name="handlerOut(eventObject)" type="Function">A function to execute when the mouse pointer leaves the element.</param> /// <returns type="jQuery" /> /// </signature> }, 'html': function() { /// <signature> /// <summary>Set the HTML contents of each element in the set of matched elements.</summary> /// <param name="htmlString" type="String">A string of HTML to set as the content of each matched element.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set the HTML contents of each element in the set of matched elements.</summary> /// <param name="function(index, oldhtml)" type="Function">A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'id': function() { /// <signature> /// <summary>Selects a single element with the given id attribute.</summary> /// <param name="id" type="String">An ID to search for, specified via the id attribute of an element.</param> /// </signature> }, 'image': function() { /// <summary>Selects all elements of type image.</summary> }, 'index': function() { /// <signature> /// <summary>Search for a given element from among the matched elements.</summary> /// <param name="selector" type="String">A selector representing a jQuery collection in which to look for an element.</param> /// <returns type="Number" /> /// </signature> /// <signature> /// <summary>Search for a given element from among the matched elements.</summary> /// <param name="element" type="jQuery">The DOM element or first element within the jQuery object to look for.</param> /// <returns type="Number" /> /// </signature> }, 'init': function() { /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="selector" type="String">A string containing a selector expression</param> /// <param name="context" type="jQuery">A DOM Element, Document, or jQuery to use as context</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="element" type="Element">A DOM element to wrap in a jQuery object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="object" type="Object">A plain object to wrap in a jQuery object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="elementArray" type="Array">An array containing a set of DOM elements to wrap in a jQuery object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="jQuery object" type="Object">An existing jQuery object to clone.</param> /// <returns type="jQuery" /> /// </signature> }, 'innerHeight': function() { /// <summary>Get the current computed height for the first element in the set of matched elements, including padding but not border.</summary> /// <returns type="Integer" /> }, 'innerWidth': function() { /// <summary>Get the current computed width for the first element in the set of matched elements, including padding but not border.</summary> /// <returns type="Integer" /> }, 'input': function() { /// <summary>Selects all input, textarea, select and button elements.</summary> }, 'insertAfter': function() { /// <signature> /// <summary>Insert every element in the set of matched elements after the target.</summary> /// <param name="target" type="jQuery">A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter.</param> /// <returns type="jQuery" /> /// </signature> }, 'insertBefore': function() { /// <signature> /// <summary>Insert every element in the set of matched elements before the target.</summary> /// <param name="target" type="jQuery">A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter.</param> /// <returns type="jQuery" /> /// </signature> }, 'is': function() { /// <signature> /// <summary>Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="Boolean" /> /// </signature> /// <signature> /// <summary>Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.</summary> /// <param name="function(index)" type="Function">A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element.</param> /// <returns type="Boolean" /> /// </signature> /// <signature> /// <summary>Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.</summary> /// <param name="jQuery object" type="Object">An existing jQuery object to match the current set of elements against.</param> /// <returns type="Boolean" /> /// </signature> /// <signature> /// <summary>Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.</summary> /// <param name="element" type="Element">An element to match the current set of elements against.</param> /// <returns type="Boolean" /> /// </signature> }, 'jquery': function() { /// <summary>A string containing the jQuery version number.</summary> /// <returns type="String" /> }, 'keydown': function() { /// <signature> /// <summary>Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'keypress': function() { /// <signature> /// <summary>Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'keyup': function() { /// <signature> /// <summary>Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'last': function() { /// <summary>Selects the last matched element.</summary> }, 'last-child': function() { /// <summary>Selects all elements that are the last child of their parent.</summary> }, 'length': function() { /// <summary>The number of elements in the jQuery object.</summary> /// <returns type="Number" /> }, 'live': function() { /// <signature> /// <summary>Attach an event handler for all elements which match the current selector, now and in the future.</summary> /// <param name="events" type="String">A string containing a JavaScript event type, such as "click" or "keydown." As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names.</param> /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach an event handler for all elements which match the current selector, now and in the future.</summary> /// <param name="events" type="String">A string containing a JavaScript event type, such as "click" or "keydown." As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names.</param> /// <param name="data" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach an event handler for all elements which match the current selector, now and in the future.</summary> /// <param name="events-map" type="Object">A map of one or more JavaScript event types and functions to execute for them.</param> /// <returns type="jQuery" /> /// </signature> }, 'load': function() { /// <signature> /// <summary>Bind an event handler to the "load" JavaScript event.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute when the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "load" JavaScript event.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'lt': function() { /// <signature> /// <summary>Select all elements at an index less than index within the matched set.</summary> /// <param name="index" type="Number">Zero-based index.</param> /// </signature> }, 'map': function() { /// <signature> /// <summary>Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.</summary> /// <param name="callback(index, domElement)" type="Function">A function object that will be invoked for each element in the current set.</param> /// <returns type="jQuery" /> /// </signature> }, 'mousedown': function() { /// <signature> /// <summary>Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'mouseenter': function() { /// <signature> /// <summary>Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'mouseleave': function() { /// <signature> /// <summary>Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'mousemove': function() { /// <signature> /// <summary>Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'mouseout': function() { /// <signature> /// <summary>Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'mouseover': function() { /// <signature> /// <summary>Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'mouseup': function() { /// <signature> /// <summary>Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'multiple': function() { /// <signature> /// <summary>Selects the combined results of all the specified selectors.</summary> /// <param name="selector1" type="String">Any valid selector.</param> /// <param name="selector2" type="String">Another valid selector.</param> /// <param name="selectorN" type="String">As many more valid selectors as you like.</param> /// </signature> }, 'next': function() { /// <signature> /// <summary>Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'next adjacent': function() { /// <signature> /// <summary>Selects all next elements matching "next" that are immediately preceded by a sibling "prev".</summary> /// <param name="prev" type="String">Any valid selector.</param> /// <param name="next" type="String">A selector to match the element that is next to the first selector.</param> /// </signature> }, 'next siblings': function() { /// <signature> /// <summary>Selects all sibling elements that follow after the "prev" element, have the same parent, and match the filtering "siblings" selector.</summary> /// <param name="prev" type="String">Any valid selector.</param> /// <param name="siblings" type="String">A selector to filter elements that are the following siblings of the first selector.</param> /// </signature> }, 'nextAll': function() { /// <signature> /// <summary>Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'nextUntil': function() { /// <signature> /// <summary>Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.</summary> /// <param name="selector" type="String">A string containing a selector expression to indicate where to stop matching following sibling elements.</param> /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.</summary> /// <param name="element" type="Element">A DOM node or jQuery object indicating where to stop matching following sibling elements.</param> /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'not': function() { /// <signature> /// <summary>Remove elements from the set of matched elements.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove elements from the set of matched elements.</summary> /// <param name="elements" type="Array">One or more DOM elements to remove from the matched set.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove elements from the set of matched elements.</summary> /// <param name="function(index)" type="Function">A function used as a test for each element in the set. this is the current DOM element.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove elements from the set of matched elements.</summary> /// <param name="jQuery object" type="Object">An existing jQuery object to match the current set of elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'nth-child': function() { /// <signature> /// <summary>Selects all elements that are the nth-child of their parent.</summary> /// <param name="index" type="String">The index of each child to match, starting with 1, the string even or odd, or an equation ( eg. :nth-child(even), :nth-child(4n) )</param> /// </signature> }, 'odd': function() { /// <summary>Selects odd elements, zero-indexed. See also even.</summary> }, 'off': function() { /// <signature> /// <summary>Remove an event handler.</summary> /// <param name="events" type="String">One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin".</param> /// <param name="selector" type="String">A selector which should match the one originally passed to .on() when attaching event handlers.</param> /// <param name="handler(eventObject)" type="Function">A handler function previously attached for the event(s), or the special value false.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove an event handler.</summary> /// <param name="events-map" type="Object">A map where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s).</param> /// <param name="selector" type="String">A selector which should match the one originally passed to .on() when attaching event handlers.</param> /// <returns type="jQuery" /> /// </signature> }, 'offset': function() { /// <signature> /// <summary>Set the current coordinates of every element in the set of matched elements, relative to the document.</summary> /// <param name="coordinates" type="Object">An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set the current coordinates of every element in the set of matched elements, relative to the document.</summary> /// <param name="function(index, coords)" type="Function">A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new top and left properties.</param> /// <returns type="jQuery" /> /// </signature> }, 'offsetParent': function() { /// <summary>Get the closest ancestor element that is positioned.</summary> /// <returns type="jQuery" /> }, 'on': function() { /// <signature> /// <summary>Attach an event handler function for one or more events to the selected elements.</summary> /// <param name="events" type="String">One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".</param> /// <param name="selector" type="String">A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.</param> /// <param name="data" type="Anything">Data to be passed to the handler in event.data when an event is triggered.</param> /// <param name="handler(eventObject)" type="Function">A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach an event handler function for one or more events to the selected elements.</summary> /// <param name="events-map" type="Object">A map in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).</param> /// <param name="selector" type="String">A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element.</param> /// <param name="data" type="Anything">Data to be passed to the handler in event.data when an event occurs.</param> /// <returns type="jQuery" /> /// </signature> }, 'one': function() { /// <signature> /// <summary>Attach a handler to an event for the elements. The handler is executed at most once per element.</summary> /// <param name="events" type="String">A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names.</param> /// <param name="data" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach a handler to an event for the elements. The handler is executed at most once per element.</summary> /// <param name="events" type="String">One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".</param> /// <param name="selector" type="String">A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.</param> /// <param name="data" type="Anything">Data to be passed to the handler in event.data when an event is triggered.</param> /// <param name="handler(eventObject)" type="Function">A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach a handler to an event for the elements. The handler is executed at most once per element.</summary> /// <param name="events-map" type="Object">A map in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).</param> /// <param name="selector" type="String">A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element.</param> /// <param name="data" type="Anything">Data to be passed to the handler in event.data when an event occurs.</param> /// <returns type="jQuery" /> /// </signature> }, 'only-child': function() { /// <summary>Selects all elements that are the only child of their parent.</summary> }, 'outerHeight': function() { /// <signature> /// <summary>Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without "px") representation of the value or null if called on an empty set of elements.</summary> /// <param name="includeMargin" type="Boolean">A Boolean indicating whether to include the element's margin in the calculation.</param> /// <returns type="Integer" /> /// </signature> }, 'outerWidth': function() { /// <signature> /// <summary>Get the current computed width for the first element in the set of matched elements, including padding and border.</summary> /// <param name="includeMargin" type="Boolean">A Boolean indicating whether to include the element's margin in the calculation.</param> /// <returns type="Integer" /> /// </signature> }, 'parent': function() { /// <signature> /// <summary>Get the parent of each element in the current set of matched elements, optionally filtered by a selector.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'parents': function() { /// <signature> /// <summary>Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'parentsUntil': function() { /// <signature> /// <summary>Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object.</summary> /// <param name="selector" type="String">A string containing a selector expression to indicate where to stop matching ancestor elements.</param> /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object.</summary> /// <param name="element" type="Element">A DOM node or jQuery object indicating where to stop matching ancestor elements.</param> /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'password': function() { /// <summary>Selects all elements of type password.</summary> }, 'position': function() { /// <summary>Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.</summary> /// <returns type="Object" /> }, 'prepend': function() { /// <signature> /// <summary>Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.</summary> /// <param name="content" type="jQuery">DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements.</param> /// <param name="content" type="jQuery">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.</summary> /// <param name="function(index, html)" type="Function">A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'prependTo': function() { /// <signature> /// <summary>Insert every element in the set of matched elements to the beginning of the target.</summary> /// <param name="target" type="jQuery">A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter.</param> /// <returns type="jQuery" /> /// </signature> }, 'prev': function() { /// <signature> /// <summary>Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'prevAll': function() { /// <signature> /// <summary>Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'prevUntil': function() { /// <signature> /// <summary>Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.</summary> /// <param name="selector" type="String">A string containing a selector expression to indicate where to stop matching preceding sibling elements.</param> /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.</summary> /// <param name="element" type="Element">A DOM node or jQuery object indicating where to stop matching preceding sibling elements.</param> /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'promise': function() { /// <signature> /// <summary>Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished.</summary> /// <param name="type" type="String">The type of queue that needs to be observed.</param> /// <param name="target" type="Object">Object onto which the promise methods have to be attached</param> /// <returns type="Promise" /> /// </signature> }, 'prop': function() { /// <signature> /// <summary>Set one or more properties for the set of matched elements.</summary> /// <param name="propertyName" type="String">The name of the property to set.</param> /// <param name="value" type="Boolean">A value to set for the property.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set one or more properties for the set of matched elements.</summary> /// <param name="map" type="Object">A map of property-value pairs to set.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set one or more properties for the set of matched elements.</summary> /// <param name="propertyName" type="String">The name of the property to set.</param> /// <param name="function(index, oldPropertyValue)" type="Function">A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element.</param> /// <returns type="jQuery" /> /// </signature> }, 'pushStack': function() { /// <signature> /// <summary>Add a collection of DOM elements onto the jQuery stack.</summary> /// <param name="elements" type="Array">An array of elements to push onto the stack and make into a new jQuery object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Add a collection of DOM elements onto the jQuery stack.</summary> /// <param name="elements" type="Array">An array of elements to push onto the stack and make into a new jQuery object.</param> /// <param name="name" type="String">The name of a jQuery method that generated the array of elements.</param> /// <param name="arguments" type="Array">The arguments that were passed in to the jQuery method (for serialization).</param> /// <returns type="jQuery" /> /// </signature> }, 'queue': function() { /// <signature> /// <summary>Manipulate the queue of functions to be executed on the matched elements.</summary> /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> /// <param name="newQueue" type="Array">An array of functions to replace the current queue contents.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Manipulate the queue of functions to be executed on the matched elements.</summary> /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> /// <param name="callback( next )" type="Function">The new function to add to the queue, with a function to call that will dequeue the next item.</param> /// <returns type="jQuery" /> /// </signature> }, 'radio': function() { /// <summary>Selects all elements of type radio.</summary> }, 'ready': function() { /// <signature> /// <summary>Specify a function to execute when the DOM is fully loaded.</summary> /// <param name="handler" type="Function">A function to execute after the DOM is ready.</param> /// <returns type="jQuery" /> /// </signature> }, 'remove': function() { /// <signature> /// <summary>Remove the set of matched elements from the DOM.</summary> /// <param name="selector" type="String">A selector expression that filters the set of matched elements to be removed.</param> /// <returns type="jQuery" /> /// </signature> }, 'removeAttr': function() { /// <signature> /// <summary>Remove an attribute from each element in the set of matched elements.</summary> /// <param name="attributeName" type="String">An attribute to remove; as of version 1.7, it can be a space-separated list of attributes.</param> /// <returns type="jQuery" /> /// </signature> }, 'removeClass': function() { /// <signature> /// <summary>Remove a single class, multiple classes, or all classes from each element in the set of matched elements.</summary> /// <param name="className" type="String">One or more space-separated classes to be removed from the class attribute of each matched element.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove a single class, multiple classes, or all classes from each element in the set of matched elements.</summary> /// <param name="function(index, class)" type="Function">A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments.</param> /// <returns type="jQuery" /> /// </signature> }, 'removeData': function() { /// <signature> /// <summary>Remove a previously-stored piece of data.</summary> /// <param name="name" type="String">A string naming the piece of data to delete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove a previously-stored piece of data.</summary> /// <param name="list" type="String">An array or space-separated string naming the pieces of data to delete.</param> /// <returns type="jQuery" /> /// </signature> }, 'removeProp': function() { /// <signature> /// <summary>Remove a property for the set of matched elements.</summary> /// <param name="propertyName" type="String">The name of the property to set.</param> /// <returns type="jQuery" /> /// </signature> }, 'replaceAll': function() { /// <signature> /// <summary>Replace each target element with the set of matched elements.</summary> /// <param name="target" type="String">A selector expression indicating which element(s) to replace.</param> /// <returns type="jQuery" /> /// </signature> }, 'replaceWith': function() { /// <signature> /// <summary>Replace each element in the set of matched elements with the provided new content.</summary> /// <param name="newContent" type="jQuery">The content to insert. May be an HTML string, DOM element, or jQuery object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Replace each element in the set of matched elements with the provided new content.</summary> /// <param name="function" type="Function">A function that returns content with which to replace the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> }, 'reset': function() { /// <summary>Selects all elements of type reset.</summary> }, 'resize': function() { /// <signature> /// <summary>Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'scroll': function() { /// <signature> /// <summary>Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'scrollLeft': function() { /// <signature> /// <summary>Set the current horizontal position of the scroll bar for each of the set of matched elements.</summary> /// <param name="value" type="Number">An integer indicating the new position to set the scroll bar to.</param> /// <returns type="jQuery" /> /// </signature> }, 'scrollTop': function() { /// <signature> /// <summary>Set the current vertical position of the scroll bar for each of the set of matched elements.</summary> /// <param name="value" type="Number">An integer indicating the new position to set the scroll bar to.</param> /// <returns type="jQuery" /> /// </signature> }, 'select': function() { /// <signature> /// <summary>Bind an event handler to the "select" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "select" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'selected': function() { /// <summary>Selects all elements that are selected.</summary> }, 'serialize': function() { /// <summary>Encode a set of form elements as a string for submission.</summary> /// <returns type="String" /> }, 'serializeArray': function() { /// <summary>Encode a set of form elements as an array of names and values.</summary> /// <returns type="Array" /> }, 'show': function() { /// <signature> /// <summary>Display the matched elements.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display the matched elements.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> }, 'siblings': function() { /// <signature> /// <summary>Get the siblings of each element in the set of matched elements, optionally filtered by a selector.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'size': function() { /// <summary>Return the number of elements in the jQuery object.</summary> /// <returns type="Number" /> }, 'slice': function() { /// <signature> /// <summary>Reduce the set of matched elements to a subset specified by a range of indices.</summary> /// <param name="start" type="Number">An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set.</param> /// <param name="end" type="Number">An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'slideDown': function() { /// <signature> /// <summary>Display the matched elements with a sliding motion.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display the matched elements with a sliding motion.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> }, 'slideToggle': function() { /// <signature> /// <summary>Display or hide the matched elements with a sliding motion.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display or hide the matched elements with a sliding motion.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> }, 'slideUp': function() { /// <signature> /// <summary>Hide the matched elements with a sliding motion.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Hide the matched elements with a sliding motion.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> }, 'stop': function() { /// <signature> /// <summary>Stop the currently-running animation on the matched elements.</summary> /// <param name="clearQueue" type="Boolean">A Boolean indicating whether to remove queued animation as well. Defaults to false.</param> /// <param name="jumpToEnd" type="Boolean">A Boolean indicating whether to complete the current animation immediately. Defaults to false.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Stop the currently-running animation on the matched elements.</summary> /// <param name="queue" type="String">The name of the queue in which to stop animations.</param> /// <param name="clearQueue" type="Boolean">A Boolean indicating whether to remove queued animation as well. Defaults to false.</param> /// <param name="jumpToEnd" type="Boolean">A Boolean indicating whether to complete the current animation immediately. Defaults to false.</param> /// <returns type="jQuery" /> /// </signature> }, 'submit': function() { /// <signature> /// <summary>Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'text': function() { /// <signature> /// <summary>Set the content of each element in the set of matched elements to the specified text.</summary> /// <param name="textString" type="String">A string of text to set as the content of each matched element.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set the content of each element in the set of matched elements to the specified text.</summary> /// <param name="function(index, text)" type="Function">A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.</param> /// <returns type="jQuery" /> /// </signature> }, 'toArray': function() { /// <summary>Retrieve all the DOM elements contained in the jQuery set, as an array.</summary> /// <returns type="Array" /> }, 'toggle': function() { /// <signature> /// <summary>Display or hide the matched elements.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display or hide the matched elements.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="callback" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display or hide the matched elements.</summary> /// <param name="showOrHide" type="Boolean">A Boolean indicating whether to show or hide the elements.</param> /// <returns type="jQuery" /> /// </signature> }, 'toggleClass': function() { /// <signature> /// <summary>Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.</summary> /// <param name="className" type="String">One or more class names (separated by spaces) to be toggled for each element in the matched set.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.</summary> /// <param name="className" type="String">One or more class names (separated by spaces) to be toggled for each element in the matched set.</param> /// <param name="switch" type="Boolean">A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.</summary> /// <param name="switch" type="Boolean">A boolean value to determine whether the class should be added or removed.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.</summary> /// <param name="function(index, class, switch)" type="Function">A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments.</param> /// <param name="switch" type="Boolean">A boolean value to determine whether the class should be added or removed.</param> /// <returns type="jQuery" /> /// </signature> }, 'trigger': function() { /// <signature> /// <summary>Execute all handlers and behaviors attached to the matched elements for the given event type.</summary> /// <param name="eventType" type="String">A string containing a JavaScript event type, such as click or submit.</param> /// <param name="extraParameters" type="Object">Additional parameters to pass along to the event handler.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Execute all handlers and behaviors attached to the matched elements for the given event type.</summary> /// <param name="event" type="Event">A jQuery.Event object.</param> /// <returns type="jQuery" /> /// </signature> }, 'triggerHandler': function() { /// <signature> /// <summary>Execute all handlers attached to an element for an event.</summary> /// <param name="eventType" type="String">A string containing a JavaScript event type, such as click or submit.</param> /// <param name="extraParameters" type="Array">An array of additional parameters to pass along to the event handler.</param> /// <returns type="Object" /> /// </signature> }, 'unbind': function() { /// <signature> /// <summary>Remove a previously-attached event handler from the elements.</summary> /// <param name="eventType" type="String">A string containing a JavaScript event type, such as click or submit.</param> /// <param name="handler(eventObject)" type="Function">The function that is to be no longer executed.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove a previously-attached event handler from the elements.</summary> /// <param name="eventType" type="String">A string containing a JavaScript event type, such as click or submit.</param> /// <param name="false" type="Boolean">Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ).</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove a previously-attached event handler from the elements.</summary> /// <param name="event" type="Object">A JavaScript event object as passed to an event handler.</param> /// <returns type="jQuery" /> /// </signature> }, 'undelegate': function() { /// <signature> /// <summary>Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.</summary> /// <param name="selector" type="String">A selector which will be used to filter the event results.</param> /// <param name="eventType" type="String">A string containing a JavaScript event type, such as "click" or "keydown"</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.</summary> /// <param name="selector" type="String">A selector which will be used to filter the event results.</param> /// <param name="eventType" type="String">A string containing a JavaScript event type, such as "click" or "keydown"</param> /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.</summary> /// <param name="selector" type="String">A selector which will be used to filter the event results.</param> /// <param name="events" type="Object">A map of one or more event types and previously bound functions to unbind from them.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.</summary> /// <param name="namespace" type="String">A string containing a namespace to unbind all events from.</param> /// <returns type="jQuery" /> /// </signature> }, 'unload': function() { /// <signature> /// <summary>Bind an event handler to the "unload" JavaScript event.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute when the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "unload" JavaScript event.</summary> /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'unwrap': function() { /// <summary>Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.</summary> /// <returns type="jQuery" /> }, 'val': function() { /// <signature> /// <summary>Set the value of each element in the set of matched elements.</summary> /// <param name="value" type="String">A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set the value of each element in the set of matched elements.</summary> /// <param name="function(index, value)" type="Function">A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.</param> /// <returns type="jQuery" /> /// </signature> }, 'visible': function() { /// <summary>Selects all elements that are visible.</summary> }, 'width': function() { /// <signature> /// <summary>Set the CSS width of each element in the set of matched elements.</summary> /// <param name="value" type="Number">An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string).</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set the CSS width of each element in the set of matched elements.</summary> /// <param name="function(index, width)" type="Function">A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'wrap': function() { /// <signature> /// <summary>Wrap an HTML structure around each element in the set of matched elements.</summary> /// <param name="wrappingElement" type="jQuery">An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Wrap an HTML structure around each element in the set of matched elements.</summary> /// <param name="function(index)" type="Function">A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'wrapAll': function() { /// <signature> /// <summary>Wrap an HTML structure around all elements in the set of matched elements.</summary> /// <param name="wrappingElement" type="jQuery">An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.</param> /// <returns type="jQuery" /> /// </signature> }, 'wrapInner': function() { /// <signature> /// <summary>Wrap an HTML structure around the content of each element in the set of matched elements.</summary> /// <param name="wrappingElement" type="String">An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Wrap an HTML structure around the content of each element in the set of matched elements.</summary> /// <param name="function(index)" type="Function">A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, }); intellisense.annotate(window, { '$': function() { /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="selector" type="String">A string containing a selector expression</param> /// <param name="context" type="jQuery">A DOM Element, Document, or jQuery to use as context</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="element" type="Element">A DOM element to wrap in a jQuery object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="object" type="Object">A plain object to wrap in a jQuery object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="elementArray" type="Array">An array containing a set of DOM elements to wrap in a jQuery object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="jQuery object" type="Object">An existing jQuery object to clone.</param> /// <returns type="jQuery" /> /// </signature> }, });
var path = require('path'); var srcPath = path.join(__dirname, '../../src/'); module.exports = { devtool: 'eval', module: { loaders: [ { test: /\.(png|jpg|gif|woff|woff2|md|css|sass|scss|less|styl)$/, loader: 'null-loader' }, { test: /\.(js|jsx)$/, loader: 'babel', exclude: [/node_modules/] } ] }, node : { fs: 'empty' }, resolve: { extensions: ['', '.js', '.jsx'], alias: { helpers: path.join(__dirname, '../../test/helpers'), actions: srcPath + '/common' + '/actions/', components: srcPath + '/common' + '/components/', containers: srcPath + '/common' + '/containers/', content: srcPath + '/common' + '/content/', icons: srcPath + '/common' + '/components/icons/', images: srcPath + '/common' + '/images/', lib: srcPath + '/common' + '/lib/', reducers: srcPath + '/common' + '/reducers/', styles: srcPath + '/common' + '/styles/', validators: srcPath + '/common' + '/validators/', types: srcPath + '/common' + '/types/', schemas: srcPath + '/common' + '/schemas/', } } };