code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
/* YUI 3.9.1 (build 5852) Copyright 2013 Yahoo! Inc. http://yuilibrary.com/license/ */
YUI.add("pluginhost-config",function(e,t){var n=e.Plugin.Host,r=e.Lang;n.prototype._initConfigPlugins=function(t){var n=this._getClasses?this._getClasses():[this.constructor],r=[],i={},s,o,u,a,f;for(o=n.length-1;o>=0;o--)s=n[o],a=s._UNPLUG,a&&e.mix(i,a,!0),u=s._PLUG,u&&e.mix(r,u,!0);for(f in r)r.hasOwnProperty(f)&&(i[f]||this.plug(r[f]));t&&t.plugins&&this.plug(t.plugins)},n.plug=function(t,n,i){var s,o,u,a;if(t!==e.Base){t._PLUG=t._PLUG||{},r.isArray(n)||(i&&(n={fn:n,cfg:i}),n=[n]);for(o=0,u=n.length;o<u;o++)s=n[o],a=s.NAME||s.fn.NAME,t._PLUG[a]=s}},n.unplug=function(t,n){var i,s,o,u;if(t!==e.Base){t._UNPLUG=t._UNPLUG||{},r.isArray(n)||(n=[n]);for(s=0,o=n.length;s<o;s++)i=n[s],u=i.NAME,t._PLUG[u]?delete t._PLUG[u]:t._UNPLUG[u]=i}}},"3.9.1",{requires:["pluginhost-base"]});
| berkmancenter/spectacle | web/js/app/editor/node_modules/grunt-contrib/node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/pluginhost-config/pluginhost-config-min.js | JavaScript | gpl-2.0 | 871 |
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Course selector adaptor for auto-complete form element.
*
* @module core/form-cohort-selector
* @copyright 2016 Damyon Wiese <damyon@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since 3.1
*/
define(['core/ajax', 'jquery'], function(ajax, $) {
return {
// Public variables and functions.
processResults: function(selector, data) {
// Mangle the results into an array of objects.
var results = [];
var i = 0;
var excludelist = String($(selector).data('exclude')).split(',');
for (i = 0; i < data.cohorts.length; i++) {
if (excludelist.indexOf(String(data.cohorts[i].id)) === -1) {
results.push({value: data.cohorts[i].id, label: data.cohorts[i].name});
}
}
return results;
},
transport: function(selector, query, success, failure) {
var el = $(selector);
// Parse some data-attributes from the form element.
// Build the query.
var promises = null;
if (typeof query === "undefined") {
query = '';
}
var contextid = el.data('contextid');
var searchargs = {
query: query,
includes: 'parents',
limitfrom: 0,
limitnum: 100,
context: {contextid: contextid}
};
var calls = [{
methodname: 'core_cohort_search_cohorts', args: searchargs
}];
// Go go go!
promises = ajax.call(calls);
$.when.apply($.when, promises).done(function(data) {
success(data);
}).fail(failure);
}
};
});
| lameze/moodle | lib/amd/src/form-cohort-selector.js | JavaScript | gpl-3.0 | 2,517 |
$(document).ready(function() {
$('#object_description').editable(function(value, settings) {
var revert = this.revert;
return function(value, settings, elem) {
var data = {
type: subscription_type,
id: subscription_id,
description: value,
};
$.ajax({
type: "POST",
async: false,
url: description_update,
data: data,
success: function(data) {
if (!data.success) {
value = revert;
$('#object_description_error').text(' Error: ' + data.message);
}
}
});
var escapes = {
'&': '&',
'"': '"',
"'": ''',
'>': '>',
'<': '<'
};
return value.replace(/&(?!amp;|quot;|apos;|gt;|lt;)|["'><]/g,
function (s) { return escapes[s]; });
}(value, settings, this);
},
{
type: 'textarea',
height: "50px",
width: "400px",
tooltip: "",
cancel: "Cancel",
submit: "Ok",
onblur: 'ignore',
});
});
| cfossace/crits | extras/www/static/js/descriptions.js | JavaScript | mit | 1,193 |
var div = document.getElementById('barChartContainer');
BarChart(div);
| theclinicdotcom/screencasts | generalizingD3/examples/snapshots/snapshot11/main.js | JavaScript | mit | 71 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
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 __());
};
import { BaseError, WrappedError } from '../facade/errors';
import { stringify } from '../facade/lang';
/**
* @param {?} keys
* @return {?}
*/
function findFirstClosedCycle(keys) {
var /** @type {?} */ res = [];
for (var /** @type {?} */ i = 0; i < keys.length; ++i) {
if (res.indexOf(keys[i]) > -1) {
res.push(keys[i]);
return res;
}
res.push(keys[i]);
}
return res;
}
/**
* @param {?} keys
* @return {?}
*/
function constructResolvingPath(keys) {
if (keys.length > 1) {
var /** @type {?} */ reversed = findFirstClosedCycle(keys.slice().reverse());
var /** @type {?} */ tokenStrs = reversed.map(function (k) { return stringify(k.token); });
return ' (' + tokenStrs.join(' -> ') + ')';
}
return '';
}
/**
* Base class for all errors arising from misconfigured providers.
* \@stable
*/
export var AbstractProviderError = (function (_super) {
__extends(AbstractProviderError, _super);
/**
* @param {?} injector
* @param {?} key
* @param {?} constructResolvingMessage
*/
function AbstractProviderError(injector, key, constructResolvingMessage) {
_super.call(this, 'DI Error');
this.keys = [key];
this.injectors = [injector];
this.constructResolvingMessage = constructResolvingMessage;
this.message = this.constructResolvingMessage(this.keys);
}
/**
* @param {?} injector
* @param {?} key
* @return {?}
*/
AbstractProviderError.prototype.addKey = function (injector, key) {
this.injectors.push(injector);
this.keys.push(key);
this.message = this.constructResolvingMessage(this.keys);
};
return AbstractProviderError;
}(BaseError));
function AbstractProviderError_tsickle_Closure_declarations() {
/**
* \@internal
* @type {?}
*/
AbstractProviderError.prototype.message;
/**
* \@internal
* @type {?}
*/
AbstractProviderError.prototype.keys;
/**
* \@internal
* @type {?}
*/
AbstractProviderError.prototype.injectors;
/**
* \@internal
* @type {?}
*/
AbstractProviderError.prototype.constructResolvingMessage;
}
/**
* Thrown when trying to retrieve a dependency by key from {\@link Injector}, but the
* {\@link Injector} does not have a {\@link Provider} for the given key.
*
* ### Example ([live demo](http://plnkr.co/edit/vq8D3FRB9aGbnWJqtEPE?p=preview))
*
* ```typescript
* class A {
* constructor(b:B) {}
* }
*
* expect(() => Injector.resolveAndCreate([A])).toThrowError();
* ```
* \@stable
*/
export var NoProviderError = (function (_super) {
__extends(NoProviderError, _super);
/**
* @param {?} injector
* @param {?} key
*/
function NoProviderError(injector, key) {
_super.call(this, injector, key, function (keys) {
var first = stringify(keys[0].token);
return "No provider for " + first + "!" + constructResolvingPath(keys);
});
}
return NoProviderError;
}(AbstractProviderError));
/**
* Thrown when dependencies form a cycle.
*
* ### Example ([live demo](http://plnkr.co/edit/wYQdNos0Tzql3ei1EV9j?p=info))
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* {provide: "one", useFactory: (two) => "two", deps: [[new Inject("two")]]},
* {provide: "two", useFactory: (one) => "one", deps: [[new Inject("one")]]}
* ]);
*
* expect(() => injector.get("one")).toThrowError();
* ```
*
* Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed.
* \@stable
*/
export var CyclicDependencyError = (function (_super) {
__extends(CyclicDependencyError, _super);
/**
* @param {?} injector
* @param {?} key
*/
function CyclicDependencyError(injector, key) {
_super.call(this, injector, key, function (keys) {
return "Cannot instantiate cyclic dependency!" + constructResolvingPath(keys);
});
}
return CyclicDependencyError;
}(AbstractProviderError));
/**
* Thrown when a constructing type returns with an Error.
*
* The `InstantiationError` class contains the original error plus the dependency graph which caused
* this object to be instantiated.
*
* ### Example ([live demo](http://plnkr.co/edit/7aWYdcqTQsP0eNqEdUAf?p=preview))
*
* ```typescript
* class A {
* constructor() {
* throw new Error('message');
* }
* }
*
* var injector = Injector.resolveAndCreate([A]);
* try {
* injector.get(A);
* } catch (e) {
* expect(e instanceof InstantiationError).toBe(true);
* expect(e.originalException.message).toEqual("message");
* expect(e.originalStack).toBeDefined();
* }
* ```
* \@stable
*/
export var InstantiationError = (function (_super) {
__extends(InstantiationError, _super);
/**
* @param {?} injector
* @param {?} originalException
* @param {?} originalStack
* @param {?} key
*/
function InstantiationError(injector, originalException, originalStack, key) {
_super.call(this, 'DI Error', originalException);
this.keys = [key];
this.injectors = [injector];
}
/**
* @param {?} injector
* @param {?} key
* @return {?}
*/
InstantiationError.prototype.addKey = function (injector, key) {
this.injectors.push(injector);
this.keys.push(key);
};
Object.defineProperty(InstantiationError.prototype, "message", {
/**
* @return {?}
*/
get: function () {
var /** @type {?} */ first = stringify(this.keys[0].token);
return this.originalError.message + ": Error during instantiation of " + first + "!" + constructResolvingPath(this.keys) + ".";
},
enumerable: true,
configurable: true
});
Object.defineProperty(InstantiationError.prototype, "causeKey", {
/**
* @return {?}
*/
get: function () { return this.keys[0]; },
enumerable: true,
configurable: true
});
return InstantiationError;
}(WrappedError));
function InstantiationError_tsickle_Closure_declarations() {
/**
* \@internal
* @type {?}
*/
InstantiationError.prototype.keys;
/**
* \@internal
* @type {?}
*/
InstantiationError.prototype.injectors;
}
/**
* Thrown when an object other then {\@link Provider} (or `Type`) is passed to {\@link Injector}
* creation.
*
* ### Example ([live demo](http://plnkr.co/edit/YatCFbPAMCL0JSSQ4mvH?p=preview))
*
* ```typescript
* expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError();
* ```
* \@stable
*/
export var InvalidProviderError = (function (_super) {
__extends(InvalidProviderError, _super);
/**
* @param {?} provider
*/
function InvalidProviderError(provider) {
_super.call(this, "Invalid provider - only instances of Provider and Type are allowed, got: " + provider);
}
return InvalidProviderError;
}(BaseError));
/**
* Thrown when the class has no annotation information.
*
* Lack of annotation information prevents the {\@link Injector} from determining which dependencies
* need to be injected into the constructor.
*
* ### Example ([live demo](http://plnkr.co/edit/rHnZtlNS7vJOPQ6pcVkm?p=preview))
*
* ```typescript
* class A {
* constructor(b) {}
* }
*
* expect(() => Injector.resolveAndCreate([A])).toThrowError();
* ```
*
* This error is also thrown when the class not marked with {\@link Injectable} has parameter types.
*
* ```typescript
* class B {}
*
* class A {
* constructor(b:B) {} // no information about the parameter types of A is available at runtime.
* }
*
* expect(() => Injector.resolveAndCreate([A,B])).toThrowError();
* ```
* \@stable
*/
export var NoAnnotationError = (function (_super) {
__extends(NoAnnotationError, _super);
/**
* @param {?} typeOrFunc
* @param {?} params
*/
function NoAnnotationError(typeOrFunc, params) {
_super.call(this, NoAnnotationError._genMessage(typeOrFunc, params));
}
/**
* @param {?} typeOrFunc
* @param {?} params
* @return {?}
*/
NoAnnotationError._genMessage = function (typeOrFunc, params) {
var /** @type {?} */ signature = [];
for (var /** @type {?} */ i = 0, /** @type {?} */ ii = params.length; i < ii; i++) {
var /** @type {?} */ parameter = params[i];
if (!parameter || parameter.length == 0) {
signature.push('?');
}
else {
signature.push(parameter.map(stringify).join(' '));
}
}
return 'Cannot resolve all parameters for \'' + stringify(typeOrFunc) + '\'(' +
signature.join(', ') + '). ' +
'Make sure that all the parameters are decorated with Inject or have valid type annotations and that \'' +
stringify(typeOrFunc) + '\' is decorated with Injectable.';
};
return NoAnnotationError;
}(BaseError));
/**
* Thrown when getting an object by index.
*
* ### Example ([live demo](http://plnkr.co/edit/bRs0SX2OTQiJzqvjgl8P?p=preview))
*
* ```typescript
* class A {}
*
* var injector = Injector.resolveAndCreate([A]);
*
* expect(() => injector.getAt(100)).toThrowError();
* ```
* \@stable
*/
export var OutOfBoundsError = (function (_super) {
__extends(OutOfBoundsError, _super);
/**
* @param {?} index
*/
function OutOfBoundsError(index) {
_super.call(this, "Index " + index + " is out-of-bounds.");
}
return OutOfBoundsError;
}(BaseError));
/**
* Thrown when a multi provider and a regular provider are bound to the same token.
*
* ### Example
*
* ```typescript
* expect(() => Injector.resolveAndCreate([
* { provide: "Strings", useValue: "string1", multi: true},
* { provide: "Strings", useValue: "string2", multi: false}
* ])).toThrowError();
* ```
*/
export var MixingMultiProvidersWithRegularProvidersError = (function (_super) {
__extends(MixingMultiProvidersWithRegularProvidersError, _super);
/**
* @param {?} provider1
* @param {?} provider2
*/
function MixingMultiProvidersWithRegularProvidersError(provider1, provider2) {
_super.call(this, 'Cannot mix multi providers and regular providers, got: ' + provider1.toString() + ' ' +
provider2.toString());
}
return MixingMultiProvidersWithRegularProvidersError;
}(BaseError));
//# sourceMappingURL=reflective_errors.js.map | mo-norant/FinHeartBel | website/node_modules/@angular/core/src/di/reflective_errors.js | JavaScript | gpl-3.0 | 11,050 |
(function (define) {
'use strict';
define([
'jquery',
'backbone',
'underscore',
'gettext',
'moment-with-locales',
'js/components/card/views/card',
'teams/js/views/team_utils',
'text!teams/templates/team-membership-details.underscore',
'text!teams/templates/team-country-language.underscore',
'text!teams/templates/date.underscore'
], function (
$,
Backbone,
_,
gettext,
moment,
CardView,
TeamUtils,
teamMembershipDetailsTemplate,
teamCountryLanguageTemplate,
dateTemplate
) {
var TeamMembershipView, TeamCountryLanguageView, TeamActivityView, TeamCardView;
TeamMembershipView = Backbone.View.extend({
tagName: 'div',
className: 'team-members',
template: _.template(teamMembershipDetailsTemplate),
initialize: function (options) {
this.maxTeamSize = options.maxTeamSize;
this.memberships = options.memberships;
},
render: function () {
var allMemberships = _(this.memberships).sortBy(function (member) {
return new Date(member.last_activity_at);
}).reverse(),
displayableMemberships = allMemberships.slice(0, 5),
maxMemberCount = this.maxTeamSize;
this.$el.html(this.template({
membership_message: TeamUtils.teamCapacityText(allMemberships.length, maxMemberCount),
memberships: displayableMemberships,
has_additional_memberships: displayableMemberships.length < allMemberships.length,
// Translators: "and others" refers to fact that additional members of a team exist that are not displayed.
sr_message: gettext('and others')
}));
return this;
}
});
TeamCountryLanguageView = Backbone.View.extend({
template: _.template(teamCountryLanguageTemplate),
initialize: function (options) {
this.countries = options.countries;
this.languages = options.languages;
},
render: function() {
// this.$el should be the card meta div
this.$el.append(this.template({
country: this.countries[this.model.get('country')],
language: this.languages[this.model.get('language')]
}));
}
});
TeamActivityView = Backbone.View.extend({
tagName: 'div',
className: 'team-activity',
template: _.template(dateTemplate),
initialize: function (options) {
this.date = options.date;
},
render: function () {
var lastActivity = moment(this.date),
currentLanguage = $('html').attr('lang');
lastActivity.locale(currentLanguage);
this.$el.html(
interpolate(
// Translators: 'date' is a placeholder for a fuzzy, relative timestamp (see: http://momentjs.com/)
gettext("Last activity %(date)s"),
{date: this.template({date: lastActivity.format('MMMM Do YYYY, h:mm:ss a')})},
true
)
);
this.$('abbr').text(lastActivity.fromNow());
}
});
TeamCardView = CardView.extend({
initialize: function () {
CardView.prototype.initialize.apply(this, arguments);
// TODO: show last activity detail view
this.detailViews = [
new TeamMembershipView({memberships: this.model.get('membership'), maxTeamSize: this.maxTeamSize}),
new TeamCountryLanguageView({
model: this.model,
countries: this.countries,
languages: this.languages
}),
new TeamActivityView({date: this.model.get('last_activity_at')})
];
this.model.on('change:membership', function () {
this.detailViews[0].memberships = this.model.get('membership');
}, this);
},
configuration: 'list_card',
cardClass: 'team-card',
title: function () { return this.model.get('name'); },
description: function () { return this.model.get('description'); },
details: function () { return this.detailViews; },
actionClass: 'action-view',
actionContent: function() {
return interpolate(
gettext('View %(span_start)s %(team_name)s %(span_end)s'),
{span_start: '<span class="sr">', team_name: _.escape(this.model.get('name')), span_end: '</span>'},
true
);
},
actionUrl: function () {
return '#teams/' + this.model.get('topic_id') + '/' + this.model.get('id');
}
});
return TeamCardView;
});
}).call(this, define || RequireJS.define);
| ahmadiga/min_edx | lms/djangoapps/teams/static/teams/js/views/team_card.js | JavaScript | agpl-3.0 | 5,379 |
(function($){var localization=$.spectrum.localization["es"]={cancelText:"Cancelar",chooseText:"Elegir",clearText:"Borrar color seleccionado",noColorSelectedText:"Ningún color seleccionado",togglePaletteMoreText:"Más",togglePaletteLessText:"Menos"};$.extend($.fn.spectrum.defaults,localization)})(jQuery);
| kennynaoh/cdnjs | ajax/libs/spectrum/1.8.0/i18n/jquery.spectrum-es.min.js | JavaScript | mit | 307 |
// PouchDB 5.4.4
//
// (c) 2012-2016 Dale Harvey and the PouchDB team
// PouchDB may be freely distributed under the Apache license, version 2.0.
// For all details and documentation:
// http://pouchdb.com
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.PouchDB = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],2:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
(function () {
try {
cachedSetTimeout = setTimeout;
} catch (e) {
cachedSetTimeout = function () {
throw new Error('setTimeout is not defined');
}
}
try {
cachedClearTimeout = clearTimeout;
} catch (e) {
cachedClearTimeout = function () {
throw new Error('clearTimeout is not defined');
}
}
} ())
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = cachedSetTimeout(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;
cachedClearTimeout(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) {
cachedSetTimeout(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; };
},{}],3:[function(_dereq_,module,exports){
(function (process,global){
'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var jsExtend = _dereq_(9);
var debug = _interopDefault(_dereq_(5));
var inherits = _interopDefault(_dereq_(8));
var lie = _interopDefault(_dereq_(10));
var pouchdbCollections = _dereq_(14);
var getArguments = _interopDefault(_dereq_(4));
var events = _dereq_(1);
var scopedEval = _interopDefault(_dereq_(15));
var Md5 = _interopDefault(_dereq_(16));
var vuvuzela = _interopDefault(_dereq_(17));
var pouchdbCollate = _dereq_(12);
/* istanbul ignore next */
var PouchPromise = typeof Promise === 'function' ? Promise : lie;
function isBinaryObject(object) {
return object instanceof ArrayBuffer ||
(typeof Blob !== 'undefined' && object instanceof Blob);
}
function cloneArrayBuffer(buff) {
if (typeof buff.slice === 'function') {
return buff.slice(0);
}
// IE10-11 slice() polyfill
var target = new ArrayBuffer(buff.byteLength);
var targetArray = new Uint8Array(target);
var sourceArray = new Uint8Array(buff);
targetArray.set(sourceArray);
return target;
}
function cloneBinaryObject(object) {
if (object instanceof ArrayBuffer) {
return cloneArrayBuffer(object);
}
var size = object.size;
var type = object.type;
// Blob
if (typeof object.slice === 'function') {
return object.slice(0, size, type);
}
// PhantomJS slice() replacement
return object.webkitSlice(0, size, type);
}
// most of this is borrowed from lodash.isPlainObject:
// https://github.com/fis-components/lodash.isplainobject/
// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
var funcToString = Function.prototype.toString;
var objectCtorString = funcToString.call(Object);
function isPlainObject(value) {
var proto = Object.getPrototypeOf(value);
/* istanbul ignore if */
if (proto === null) { // not sure when this happens, but I guess it can
return true;
}
var Ctor = proto.constructor;
return (typeof Ctor == 'function' &&
Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
}
function clone(object) {
var newObject;
var i;
var len;
if (!object || typeof object !== 'object') {
return object;
}
if (Array.isArray(object)) {
newObject = [];
for (i = 0, len = object.length; i < len; i++) {
newObject[i] = clone(object[i]);
}
return newObject;
}
// special case: to avoid inconsistencies between IndexedDB
// and other backends, we automatically stringify Dates
if (object instanceof Date) {
return object.toISOString();
}
if (isBinaryObject(object)) {
return cloneBinaryObject(object);
}
if (!isPlainObject(object)) {
return object; // don't clone objects like Workers
}
newObject = {};
for (i in object) {
if (Object.prototype.hasOwnProperty.call(object, i)) {
var value = clone(object[i]);
if (typeof value !== 'undefined') {
newObject[i] = value;
}
}
}
return newObject;
}
function once(fun) {
var called = false;
return getArguments(function (args) {
/* istanbul ignore if */
if (called) {
// this is a smoke test and should never actually happen
throw new Error('once called more than once');
} else {
called = true;
fun.apply(this, args);
}
});
}
function toPromise(func) {
//create the function we will be returning
return getArguments(function (args) {
// Clone arguments
args = clone(args);
var self = this;
var tempCB =
(typeof args[args.length - 1] === 'function') ? args.pop() : false;
// if the last argument is a function, assume its a callback
var usedCB;
if (tempCB) {
// if it was a callback, create a new callback which calls it,
// but do so async so we don't trap any errors
usedCB = function (err, resp) {
process.nextTick(function () {
tempCB(err, resp);
});
};
}
var promise = new PouchPromise(function (fulfill, reject) {
var resp;
try {
var callback = once(function (err, mesg) {
if (err) {
reject(err);
} else {
fulfill(mesg);
}
});
// create a callback for this invocation
// apply the function in the orig context
args.push(callback);
resp = func.apply(self, args);
if (resp && typeof resp.then === 'function') {
fulfill(resp);
}
} catch (e) {
reject(e);
}
});
// if there is a callback, call it back
if (usedCB) {
promise.then(function (result) {
usedCB(null, result);
}, usedCB);
}
return promise;
});
}
var log = debug('pouchdb:api');
function adapterFun(name, callback) {
function logApiCall(self, name, args) {
/* istanbul ignore if */
if (log.enabled) {
var logArgs = [self._db_name, name];
for (var i = 0; i < args.length - 1; i++) {
logArgs.push(args[i]);
}
log.apply(null, logArgs);
// override the callback itself to log the response
var origCallback = args[args.length - 1];
args[args.length - 1] = function (err, res) {
var responseArgs = [self._db_name, name];
responseArgs = responseArgs.concat(
err ? ['error', err] : ['success', res]
);
log.apply(null, responseArgs);
origCallback(err, res);
};
}
}
return toPromise(getArguments(function (args) {
if (this._closed) {
return PouchPromise.reject(new Error('database is closed'));
}
if (this._destroyed) {
return PouchPromise.reject(new Error('database is destroyed'));
}
var self = this;
logApiCall(self, name, args);
if (!this.taskqueue.isReady) {
return new PouchPromise(function (fulfill, reject) {
self.taskqueue.addTask(function (failed) {
if (failed) {
reject(failed);
} else {
fulfill(self[name].apply(self, args));
}
});
});
}
return callback.apply(this, args);
}));
}
// like underscore/lodash _.pick()
function pick(obj, arr) {
var res = {};
for (var i = 0, len = arr.length; i < len; i++) {
var prop = arr[i];
if (prop in obj) {
res[prop] = obj[prop];
}
}
return res;
}
// Most browsers throttle concurrent requests at 6, so it's silly
// to shim _bulk_get by trying to launch potentially hundreds of requests
// and then letting the majority time out. We can handle this ourselves.
var MAX_NUM_CONCURRENT_REQUESTS = 6;
function identityFunction(x) {
return x;
}
function formatResultForOpenRevsGet(result) {
return [{
ok: result
}];
}
// shim for P/CouchDB adapters that don't directly implement _bulk_get
function bulkGet(db, opts, callback) {
var requests = opts.docs;
// consolidate into one request per doc if possible
var requestsById = {};
requests.forEach(function (request) {
if (request.id in requestsById) {
requestsById[request.id].push(request);
} else {
requestsById[request.id] = [request];
}
});
var numDocs = Object.keys(requestsById).length;
var numDone = 0;
var perDocResults = new Array(numDocs);
function collapseResultsAndFinish() {
var results = [];
perDocResults.forEach(function (res) {
res.docs.forEach(function (info) {
results.push({
id: res.id,
docs: [info]
});
});
});
callback(null, {results: results});
}
function checkDone() {
if (++numDone === numDocs) {
collapseResultsAndFinish();
}
}
function gotResult(docIndex, id, docs) {
perDocResults[docIndex] = {id: id, docs: docs};
checkDone();
}
var allRequests = Object.keys(requestsById);
var i = 0;
function nextBatch() {
if (i >= allRequests.length) {
return;
}
var upTo = Math.min(i + MAX_NUM_CONCURRENT_REQUESTS, allRequests.length);
var batch = allRequests.slice(i, upTo);
processBatch(batch, i);
i += batch.length;
}
function processBatch(batch, offset) {
batch.forEach(function (docId, j) {
var docIdx = offset + j;
var docRequests = requestsById[docId];
// just use the first request as the "template"
// TODO: The _bulk_get API allows for more subtle use cases than this,
// but for now it is unlikely that there will be a mix of different
// "atts_since" or "attachments" in the same request, since it's just
// replicate.js that is using this for the moment.
// Also, atts_since is aspirational, since we don't support it yet.
var docOpts = pick(docRequests[0], ['atts_since', 'attachments']);
docOpts.open_revs = docRequests.map(function (request) {
// rev is optional, open_revs disallowed
return request.rev;
});
// remove falsey / undefined revisions
docOpts.open_revs = docOpts.open_revs.filter(identityFunction);
var formatResult = identityFunction;
if (docOpts.open_revs.length === 0) {
delete docOpts.open_revs;
// when fetching only the "winning" leaf,
// transform the result so it looks like an open_revs
// request
formatResult = formatResultForOpenRevsGet;
}
// globally-supplied options
['revs', 'attachments', 'binary', 'ajax'].forEach(function (param) {
if (param in opts) {
docOpts[param] = opts[param];
}
});
db.get(docId, docOpts, function (err, res) {
var result;
/* istanbul ignore if */
if (err) {
result = [{error: err}];
} else {
result = formatResult(res);
}
gotResult(docIdx, docId, result);
nextBatch();
});
});
}
nextBatch();
}
function isChromeApp() {
return (typeof chrome !== "undefined" &&
typeof chrome.storage !== "undefined" &&
typeof chrome.storage.local !== "undefined");
}
var hasLocal;
if (isChromeApp()) {
hasLocal = false;
} else {
try {
localStorage.setItem('_pouch_check_localstorage', 1);
hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
} catch (e) {
hasLocal = false;
}
}
function hasLocalStorage() {
return hasLocal;
}
inherits(Changes$1, events.EventEmitter);
/* istanbul ignore next */
function attachBrowserEvents(self) {
if (isChromeApp()) {
chrome.storage.onChanged.addListener(function (e) {
// make sure it's event addressed to us
if (e.db_name != null) {
//object only has oldValue, newValue members
self.emit(e.dbName.newValue);
}
});
} else if (hasLocalStorage()) {
if (typeof addEventListener !== 'undefined') {
addEventListener("storage", function (e) {
self.emit(e.key);
});
} else { // old IE
window.attachEvent("storage", function (e) {
self.emit(e.key);
});
}
}
}
function Changes$1() {
events.EventEmitter.call(this);
this._listeners = {};
attachBrowserEvents(this);
}
Changes$1.prototype.addListener = function (dbName, id, db, opts) {
/* istanbul ignore if */
if (this._listeners[id]) {
return;
}
var self = this;
var inprogress = false;
function eventFunction() {
/* istanbul ignore if */
if (!self._listeners[id]) {
return;
}
if (inprogress) {
inprogress = 'waiting';
return;
}
inprogress = true;
var changesOpts = pick(opts, [
'style', 'include_docs', 'attachments', 'conflicts', 'filter',
'doc_ids', 'view', 'since', 'query_params', 'binary'
]);
/* istanbul ignore next */
function onError() {
inprogress = false;
}
db.changes(changesOpts).on('change', function (c) {
if (c.seq > opts.since && !opts.cancelled) {
opts.since = c.seq;
opts.onChange(c);
}
}).on('complete', function () {
if (inprogress === 'waiting') {
setTimeout(function (){
eventFunction();
},0);
}
inprogress = false;
}).on('error', onError);
}
this._listeners[id] = eventFunction;
this.on(dbName, eventFunction);
};
Changes$1.prototype.removeListener = function (dbName, id) {
/* istanbul ignore if */
if (!(id in this._listeners)) {
return;
}
events.EventEmitter.prototype.removeListener.call(this, dbName,
this._listeners[id]);
};
/* istanbul ignore next */
Changes$1.prototype.notifyLocalWindows = function (dbName) {
//do a useless change on a storage thing
//in order to get other windows's listeners to activate
if (isChromeApp()) {
chrome.storage.local.set({dbName: dbName});
} else if (hasLocalStorage()) {
localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
}
};
Changes$1.prototype.notify = function (dbName) {
this.emit(dbName);
this.notifyLocalWindows(dbName);
};
function guardedConsole(method) {
if (console !== 'undefined' && method in console) {
var args = Array.prototype.slice.call(arguments, 1);
console[method].apply(console, args);
}
}
function randomNumber(min, max) {
var maxTimeout = 600000; // Hard-coded default of 10 minutes
min = parseInt(min, 10) || 0;
max = parseInt(max, 10);
if (max !== max || max <= min) {
max = (min || 1) << 1; //doubling
} else {
max = max + 1;
}
// In order to not exceed maxTimeout, pick a random value between half of maxTimeout and maxTimeout
if(max > maxTimeout) {
min = maxTimeout >> 1; // divide by two
max = maxTimeout;
}
var ratio = Math.random();
var range = max - min;
return ~~(range * ratio + min); // ~~ coerces to an int, but fast.
}
function defaultBackOff(min) {
var max = 0;
if (!min) {
max = 2000;
}
return randomNumber(min, max);
}
// designed to give info to browser users, who are disturbed
// when they see http errors in the console
function explainError(status, str) {
guardedConsole('info', 'The above ' + status + ' is totally normal. ' + str);
}
inherits(PouchError, Error);
function PouchError(opts) {
Error.call(this, opts.reason);
this.status = opts.status;
this.name = opts.error;
this.message = opts.reason;
this.error = true;
}
PouchError.prototype.toString = function () {
return JSON.stringify({
status: this.status,
name: this.name,
message: this.message,
reason: this.reason
});
};
var UNAUTHORIZED = new PouchError({
status: 401,
error: 'unauthorized',
reason: "Name or password is incorrect."
});
var MISSING_BULK_DOCS = new PouchError({
status: 400,
error: 'bad_request',
reason: "Missing JSON list of 'docs'"
});
var MISSING_DOC = new PouchError({
status: 404,
error: 'not_found',
reason: 'missing'
});
var REV_CONFLICT = new PouchError({
status: 409,
error: 'conflict',
reason: 'Document update conflict'
});
var INVALID_ID = new PouchError({
status: 400,
error: 'invalid_id',
reason: '_id field must contain a string'
});
var MISSING_ID = new PouchError({
status: 412,
error: 'missing_id',
reason: '_id is required for puts'
});
var RESERVED_ID = new PouchError({
status: 400,
error: 'bad_request',
reason: 'Only reserved document ids may start with underscore.'
});
var NOT_OPEN = new PouchError({
status: 412,
error: 'precondition_failed',
reason: 'Database not open'
});
var UNKNOWN_ERROR = new PouchError({
status: 500,
error: 'unknown_error',
reason: 'Database encountered an unknown error'
});
var BAD_ARG = new PouchError({
status: 500,
error: 'badarg',
reason: 'Some query argument is invalid'
});
var INVALID_REQUEST = new PouchError({
status: 400,
error: 'invalid_request',
reason: 'Request was invalid'
});
var QUERY_PARSE_ERROR = new PouchError({
status: 400,
error: 'query_parse_error',
reason: 'Some query parameter is invalid'
});
var DOC_VALIDATION = new PouchError({
status: 500,
error: 'doc_validation',
reason: 'Bad special document member'
});
var BAD_REQUEST = new PouchError({
status: 400,
error: 'bad_request',
reason: 'Something wrong with the request'
});
var NOT_AN_OBJECT = new PouchError({
status: 400,
error: 'bad_request',
reason: 'Document must be a JSON object'
});
var DB_MISSING = new PouchError({
status: 404,
error: 'not_found',
reason: 'Database not found'
});
var IDB_ERROR = new PouchError({
status: 500,
error: 'indexed_db_went_bad',
reason: 'unknown'
});
var WSQ_ERROR = new PouchError({
status: 500,
error: 'web_sql_went_bad',
reason: 'unknown'
});
var LDB_ERROR = new PouchError({
status: 500,
error: 'levelDB_went_went_bad',
reason: 'unknown'
});
var FORBIDDEN = new PouchError({
status: 403,
error: 'forbidden',
reason: 'Forbidden by design doc validate_doc_update function'
});
var INVALID_REV = new PouchError({
status: 400,
error: 'bad_request',
reason: 'Invalid rev format'
});
var FILE_EXISTS = new PouchError({
status: 412,
error: 'file_exists',
reason: 'The database could not be created, the file already exists.'
});
var MISSING_STUB = new PouchError({
status: 412,
error: 'missing_stub'
});
var INVALID_URL = new PouchError({
status: 413,
error: 'invalid_url',
reason: 'Provided URL is invalid'
});
var allErrors = [
UNAUTHORIZED,
MISSING_BULK_DOCS,
MISSING_DOC,
REV_CONFLICT,
INVALID_ID,
MISSING_ID,
RESERVED_ID,
NOT_OPEN,
UNKNOWN_ERROR,
BAD_ARG,
INVALID_REQUEST,
QUERY_PARSE_ERROR,
DOC_VALIDATION,
BAD_REQUEST,
NOT_AN_OBJECT,
DB_MISSING,
WSQ_ERROR,
LDB_ERROR,
FORBIDDEN,
INVALID_REV,
FILE_EXISTS,
MISSING_STUB,
IDB_ERROR,
INVALID_URL
];
function createError(error, reason, name) {
function CustomPouchError(reason) {
// inherit error properties from our parent error manually
// so as to allow proper JSON parsing.
/* jshint ignore:start */
for (var p in error) {
if (typeof error[p] !== 'function') {
this[p] = error[p];
}
}
/* jshint ignore:end */
if (name !== undefined) {
this.name = name;
}
if (reason !== undefined) {
this.reason = reason;
}
}
CustomPouchError.prototype = PouchError.prototype;
return new CustomPouchError(reason);
}
// Find one of the errors defined above based on the value
// of the specified property.
// If reason is provided prefer the error matching that reason.
// This is for differentiating between errors with the same name and status,
// eg, bad_request.
var getErrorTypeByProp = function (prop, value, reason) {
var errorsByProp = allErrors.filter(function (error) {
return error[prop] === value;
});
return (reason && errorsByProp.filter(function (error) {
return error.message === reason;
})[0]) || errorsByProp[0];
};
function generateErrorFromResponse(res) {
var error, errName, errType, errMsg, errReason;
errName = (res.error === true && typeof res.name === 'string') ?
res.name :
res.error;
errReason = res.reason;
errType = getErrorTypeByProp('name', errName, errReason);
if (res.missing ||
errReason === 'missing' ||
errReason === 'deleted' ||
errName === 'not_found') {
errType = MISSING_DOC;
} else if (errName === 'doc_validation') {
// doc validation needs special treatment since
// res.reason depends on the validation error.
// see utils.js
errType = DOC_VALIDATION;
errMsg = errReason;
} else if (errName === 'bad_request' && errType.message !== errReason) {
// if bad_request error already found based on reason don't override.
errType = BAD_REQUEST;
}
// fallback to error by status or unknown error.
if (!errType) {
errType = getErrorTypeByProp('status', res.status, errReason) ||
UNKNOWN_ERROR;
}
error = createError(errType, errReason, errName);
// Keep custom message.
if (errMsg) {
error.message = errMsg;
}
// Keep helpful response data in our error messages.
if (res.id) {
error.id = res.id;
}
if (res.status) {
error.status = res.status;
}
if (res.missing) {
error.missing = res.missing;
}
return error;
}
function tryFilter(filter, doc, req) {
try {
return !filter(doc, req);
} catch (err) {
var msg = 'Filter function threw: ' + err.toString();
return createError(BAD_REQUEST, msg);
}
}
function filterChange(opts) {
var req = {};
var hasFilter = opts.filter && typeof opts.filter === 'function';
req.query = opts.query_params;
return function filter(change) {
if (!change.doc) {
// CSG sends events on the changes feed that don't have documents,
// this hack makes a whole lot of existing code robust.
change.doc = {};
}
var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
if (typeof filterReturn === 'object') {
return filterReturn;
}
if (filterReturn) {
return false;
}
if (!opts.include_docs) {
delete change.doc;
} else if (!opts.attachments) {
for (var att in change.doc._attachments) {
/* istanbul ignore else */
if (change.doc._attachments.hasOwnProperty(att)) {
change.doc._attachments[att].stub = true;
}
}
}
return true;
};
}
function flatten(arrs) {
var res = [];
for (var i = 0, len = arrs.length; i < len; i++) {
res = res.concat(arrs[i]);
}
return res;
}
// Determine id an ID is valid
// - invalid IDs begin with an underescore that does not begin '_design' or
// '_local'
// - any other string value is a valid id
// Returns the specific error object for each case
function invalidIdError(id) {
var err;
if (!id) {
err = createError(MISSING_ID);
} else if (typeof id !== 'string') {
err = createError(INVALID_ID);
} else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
err = createError(RESERVED_ID);
}
if (err) {
throw err;
}
}
function listenerCount(ee, type) {
return 'listenerCount' in ee ? ee.listenerCount(type) :
events.EventEmitter.listenerCount(ee, type);
}
function parseDesignDocFunctionName(s) {
if (!s) {
return null;
}
var parts = s.split('/');
if (parts.length === 2) {
return parts;
}
if (parts.length === 1) {
return [s, s];
}
return null;
}
function normalizeDesignDocFunctionName(s) {
var normalized = parseDesignDocFunctionName(s);
return normalized ? normalized.join('/') : null;
}
// originally parseUri 1.2.2, now patched by us
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
var keys = ["source", "protocol", "authority", "userInfo", "user", "password",
"host", "port", "relative", "path", "directory", "file", "query", "anchor"];
var qName ="queryKey";
var qParser = /(?:^|&)([^&=]*)=?([^&]*)/g;
// use the "loose" parser
/* jshint maxlen: false */
var parser = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
function parseUri(str) {
var m = parser.exec(str);
var uri = {};
var i = 14;
while (i--) {
var key = keys[i];
var value = m[i] || "";
var encoded = ['user', 'password'].indexOf(key) !== -1;
uri[key] = encoded ? decodeURIComponent(value) : value;
}
uri[qName] = {};
uri[keys[12]].replace(qParser, function ($0, $1, $2) {
if ($1) {
uri[qName][$1] = $2;
}
});
return uri;
}
// this is essentially the "update sugar" function from daleharvey/pouchdb#1388
// the diffFun tells us what delta to apply to the doc. it either returns
// the doc, or false if it doesn't need to do an update after all
function upsert(db, docId, diffFun) {
return new PouchPromise(function (fulfill, reject) {
db.get(docId, function (err, doc) {
if (err) {
/* istanbul ignore next */
if (err.status !== 404) {
return reject(err);
}
doc = {};
}
// the user might change the _rev, so save it for posterity
var docRev = doc._rev;
var newDoc = diffFun(doc);
if (!newDoc) {
// if the diffFun returns falsy, we short-circuit as
// an optimization
return fulfill({updated: false, rev: docRev});
}
// users aren't allowed to modify these values,
// so reset them here
newDoc._id = docId;
newDoc._rev = docRev;
fulfill(tryAndPut(db, newDoc, diffFun));
});
});
}
function tryAndPut(db, doc, diffFun) {
return db.put(doc).then(function (res) {
return {
updated: true,
rev: res.rev
};
}, function (err) {
/* istanbul ignore next */
if (err.status !== 409) {
throw err;
}
return upsert(db, doc._id, diffFun);
});
}
// BEGIN Math.uuid.js
/*!
Math.uuid.js (v1.4)
http://www.broofa.com
mailto:robert@broofa.com
Copyright (c) 2010 Robert Kieffer
Dual licensed under the MIT and GPL licenses.
*/
/*
* Generate a random uuid.
*
* USAGE: Math.uuid(length, radix)
* length - the desired number of characters
* radix - the number of allowable values for each character.
*
* EXAMPLES:
* // No arguments - returns RFC4122, version 4 ID
* >>> Math.uuid()
* "92329D39-6F5C-4520-ABFC-AAB64544E172"
*
* // One argument - returns ID of the specified length
* >>> Math.uuid(15) // 15 character ID (default base=62)
* "VcydxgltxrVZSTV"
*
* // Two arguments - returns ID of the specified length, and radix.
* // (Radix must be <= 62)
* >>> Math.uuid(8, 2) // 8 character ID (base=2)
* "01001010"
* >>> Math.uuid(8, 10) // 8 character ID (base=10)
* "47473046"
* >>> Math.uuid(8, 16) // 8 character ID (base=16)
* "098F4D35"
*/
var chars = (
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz'
).split('');
function getValue(radix) {
return 0 | Math.random() * radix;
}
function uuid(len, radix) {
radix = radix || chars.length;
var out = '';
var i = -1;
if (len) {
// Compact form
while (++i < len) {
out += chars[getValue(radix)];
}
return out;
}
// rfc4122, version 4 form
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
while (++i < 36) {
switch (i) {
case 8:
case 13:
case 18:
case 23:
out += '-';
break;
case 19:
out += chars[(getValue(16) & 0x3) | 0x8];
break;
default:
out += chars[getValue(16)];
}
}
return out;
}
// We fetch all leafs of the revision tree, and sort them based on tree length
// and whether they were deleted, undeleted documents with the longest revision
// tree (most edits) win
// The final sort algorithm is slightly documented in a sidebar here:
// http://guide.couchdb.org/draft/conflicts.html
function winningRev(metadata) {
var winningId;
var winningPos;
var winningDeleted;
var toVisit = metadata.rev_tree.slice();
var node;
while ((node = toVisit.pop())) {
var tree = node.ids;
var branches = tree[2];
var pos = node.pos;
if (branches.length) { // non-leaf
for (var i = 0, len = branches.length; i < len; i++) {
toVisit.push({pos: pos + 1, ids: branches[i]});
}
continue;
}
var deleted = !!tree[1].deleted;
var id = tree[0];
// sort by deleted, then pos, then id
if (!winningId || (winningDeleted !== deleted ? winningDeleted :
winningPos !== pos ? winningPos < pos : winningId < id)) {
winningId = id;
winningPos = pos;
winningDeleted = deleted;
}
}
return winningPos + '-' + winningId;
}
// Pretty much all below can be combined into a higher order function to
// traverse revisions
// The return value from the callback will be passed as context to all
// children of that node
function traverseRevTree(revs, callback) {
var toVisit = revs.slice();
var node;
while ((node = toVisit.pop())) {
var pos = node.pos;
var tree = node.ids;
var branches = tree[2];
var newCtx =
callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
for (var i = 0, len = branches.length; i < len; i++) {
toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
}
}
}
function sortByPos(a, b) {
return a.pos - b.pos;
}
function collectLeaves(revs) {
var leaves = [];
traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {
if (isLeaf) {
leaves.push({rev: pos + "-" + id, pos: pos, opts: opts});
}
});
leaves.sort(sortByPos).reverse();
for (var i = 0, len = leaves.length; i < len; i++) {
delete leaves[i].pos;
}
return leaves;
}
// returns revs of all conflicts that is leaves such that
// 1. are not deleted and
// 2. are different than winning revision
function collectConflicts(metadata) {
var win = winningRev(metadata);
var leaves = collectLeaves(metadata.rev_tree);
var conflicts = [];
for (var i = 0, len = leaves.length; i < len; i++) {
var leaf = leaves[i];
if (leaf.rev !== win && !leaf.opts.deleted) {
conflicts.push(leaf.rev);
}
}
return conflicts;
}
// compact a tree by marking its non-leafs as missing,
// and return a list of revs to delete
function compactTree(metadata) {
var revs = [];
traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
revHash, ctx, opts) {
if (opts.status === 'available' && !isLeaf) {
revs.push(pos + '-' + revHash);
opts.status = 'missing';
}
});
return revs;
}
// build up a list of all the paths to the leafs in this revision tree
function rootToLeaf(revs) {
var paths = [];
var toVisit = revs.slice();
var node;
while ((node = toVisit.pop())) {
var pos = node.pos;
var tree = node.ids;
var id = tree[0];
var opts = tree[1];
var branches = tree[2];
var isLeaf = branches.length === 0;
var history = node.history ? node.history.slice() : [];
history.push({id: id, opts: opts});
if (isLeaf) {
paths.push({pos: (pos + 1 - history.length), ids: history});
}
for (var i = 0, len = branches.length; i < len; i++) {
toVisit.push({pos: pos + 1, ids: branches[i], history: history});
}
}
return paths.reverse();
}
function sortByPos$1(a, b) {
return a.pos - b.pos;
}
// classic binary search
function binarySearch(arr, item, comparator) {
var low = 0;
var high = arr.length;
var mid;
while (low < high) {
mid = (low + high) >>> 1;
if (comparator(arr[mid], item) < 0) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
// assuming the arr is sorted, insert the item in the proper place
function insertSorted(arr, item, comparator) {
var idx = binarySearch(arr, item, comparator);
arr.splice(idx, 0, item);
}
// Turn a path as a flat array into a tree with a single branch.
// If any should be stemmed from the beginning of the array, that's passed
// in as the second argument
function pathToTree(path, numStemmed) {
var root;
var leaf;
for (var i = numStemmed, len = path.length; i < len; i++) {
var node = path[i];
var currentLeaf = [node.id, node.opts, []];
if (leaf) {
leaf[2].push(currentLeaf);
leaf = currentLeaf;
} else {
root = leaf = currentLeaf;
}
}
return root;
}
// compare the IDs of two trees
function compareTree(a, b) {
return a[0] < b[0] ? -1 : 1;
}
// Merge two trees together
// The roots of tree1 and tree2 must be the same revision
function mergeTree(in_tree1, in_tree2) {
var queue = [{tree1: in_tree1, tree2: in_tree2}];
var conflicts = false;
while (queue.length > 0) {
var item = queue.pop();
var tree1 = item.tree1;
var tree2 = item.tree2;
if (tree1[1].status || tree2[1].status) {
tree1[1].status =
(tree1[1].status === 'available' ||
tree2[1].status === 'available') ? 'available' : 'missing';
}
for (var i = 0; i < tree2[2].length; i++) {
if (!tree1[2][0]) {
conflicts = 'new_leaf';
tree1[2][0] = tree2[2][i];
continue;
}
var merged = false;
for (var j = 0; j < tree1[2].length; j++) {
if (tree1[2][j][0] === tree2[2][i][0]) {
queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
merged = true;
}
}
if (!merged) {
conflicts = 'new_branch';
insertSorted(tree1[2], tree2[2][i], compareTree);
}
}
}
return {conflicts: conflicts, tree: in_tree1};
}
function doMerge(tree, path, dontExpand) {
var restree = [];
var conflicts = false;
var merged = false;
var res;
if (!tree.length) {
return {tree: [path], conflicts: 'new_leaf'};
}
for (var i = 0, len = tree.length; i < len; i++) {
var branch = tree[i];
if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {
// Paths start at the same position and have the same root, so they need
// merged
res = mergeTree(branch.ids, path.ids);
restree.push({pos: branch.pos, ids: res.tree});
conflicts = conflicts || res.conflicts;
merged = true;
} else if (dontExpand !== true) {
// The paths start at a different position, take the earliest path and
// traverse up until it as at the same point from root as the path we
// want to merge. If the keys match we return the longer path with the
// other merged After stemming we dont want to expand the trees
var t1 = branch.pos < path.pos ? branch : path;
var t2 = branch.pos < path.pos ? path : branch;
var diff = t2.pos - t1.pos;
var candidateParents = [];
var trees = [];
trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null});
while (trees.length > 0) {
var item = trees.pop();
if (item.diff === 0) {
if (item.ids[0] === t2.ids[0]) {
candidateParents.push(item);
}
continue;
}
var elements = item.ids[2];
for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {
trees.push({
ids: elements[j],
diff: item.diff - 1,
parent: item.ids,
parentIdx: j
});
}
}
var el = candidateParents[0];
if (!el) {
restree.push(branch);
} else {
res = mergeTree(el.ids, t2.ids);
el.parent[2][el.parentIdx] = res.tree;
restree.push({pos: t1.pos, ids: t1.ids});
conflicts = conflicts || res.conflicts;
merged = true;
}
} else {
restree.push(branch);
}
}
// We didnt find
if (!merged) {
restree.push(path);
}
restree.sort(sortByPos$1);
return {
tree: restree,
conflicts: conflicts || 'internal_node'
};
}
// To ensure we dont grow the revision tree infinitely, we stem old revisions
function stem(tree, depth) {
// First we break out the tree into a complete list of root to leaf paths
var paths = rootToLeaf(tree);
var maybeStem = {};
var result;
for (var i = 0, len = paths.length; i < len; i++) {
// Then for each path, we cut off the start of the path based on the
// `depth` to stem to, and generate a new set of flat trees
var path = paths[i];
var stemmed = path.ids;
var numStemmed = Math.max(0, stemmed.length - depth);
var stemmedNode = {
pos: path.pos + numStemmed,
ids: pathToTree(stemmed, numStemmed)
};
for (var s = 0; s < numStemmed; s++) {
var rev = (path.pos + s) + '-' + stemmed[s].id;
maybeStem[rev] = true;
}
// Then we remerge all those flat trees together, ensuring that we dont
// connect trees that would go beyond the depth limit
if (result) {
result = doMerge(result, stemmedNode, true).tree;
} else {
result = [stemmedNode];
}
}
traverseRevTree(result, function (isLeaf, pos, revHash) {
// some revisions may have been removed in a branch but not in another
delete maybeStem[pos + '-' + revHash];
});
return {
tree: result,
revs: Object.keys(maybeStem)
};
}
function merge(tree, path, depth) {
var newTree = doMerge(tree, path);
var stemmed = stem(newTree.tree, depth);
return {
tree: stemmed.tree,
stemmedRevs: stemmed.revs,
conflicts: newTree.conflicts
};
}
// return true if a rev exists in the rev tree, false otherwise
function revExists(revs, rev) {
var toVisit = revs.slice();
var splitRev = rev.split('-');
var targetPos = parseInt(splitRev[0], 10);
var targetId = splitRev[1];
var node;
while ((node = toVisit.pop())) {
if (node.pos === targetPos && node.ids[0] === targetId) {
return true;
}
var branches = node.ids[2];
for (var i = 0, len = branches.length; i < len; i++) {
toVisit.push({pos: node.pos + 1, ids: branches[i]});
}
}
return false;
}
function getTrees(node) {
return node.ids;
}
// check if a specific revision of a doc has been deleted
// - metadata: the metadata object from the doc store
// - rev: (optional) the revision to check. defaults to winning revision
function isDeleted(metadata, rev) {
if (!rev) {
rev = winningRev(metadata);
}
var id = rev.substring(rev.indexOf('-') + 1);
var toVisit = metadata.rev_tree.map(getTrees);
var tree;
while ((tree = toVisit.pop())) {
if (tree[0] === id) {
return !!tree[1].deleted;
}
toVisit = toVisit.concat(tree[2]);
}
}
function isLocalId(id) {
return (/^_local/).test(id);
}
function evalFilter(input) {
return scopedEval('return ' + input + ';', {});
}
function evalView(input) {
/* jshint evil:true */
return new Function('doc', [
'var emitted = false;',
'var emit = function (a, b) {',
' emitted = true;',
'};',
'var view = ' + input + ';',
'view(doc);',
'if (emitted) {',
' return true;',
'}'
].join('\n'));
}
inherits(Changes, events.EventEmitter);
function tryCatchInChangeListener(self, change) {
// isolate try/catches to avoid V8 deoptimizations
try {
self.emit('change', change);
} catch (e) {
guardedConsole('error', 'Error in .on("change", function):', e);
}
}
function Changes(db, opts, callback) {
events.EventEmitter.call(this);
var self = this;
this.db = db;
opts = opts ? clone(opts) : {};
var complete = opts.complete = once(function (err, resp) {
if (err) {
if (listenerCount(self, 'error') > 0) {
self.emit('error', err);
}
} else {
self.emit('complete', resp);
}
self.removeAllListeners();
db.removeListener('destroyed', onDestroy);
});
if (callback) {
self.on('complete', function (resp) {
callback(null, resp);
});
self.on('error', callback);
}
function onDestroy() {
self.cancel();
}
db.once('destroyed', onDestroy);
opts.onChange = function (change) {
/* istanbul ignore if */
if (opts.isCancelled) {
return;
}
tryCatchInChangeListener(self, change);
if (self.startSeq && self.startSeq <= change.seq) {
self.startSeq = false;
}
};
var promise = new PouchPromise(function (fulfill, reject) {
opts.complete = function (err, res) {
if (err) {
reject(err);
} else {
fulfill(res);
}
};
});
self.once('cancel', function () {
db.removeListener('destroyed', onDestroy);
opts.complete(null, {status: 'cancelled'});
});
this.then = promise.then.bind(promise);
this['catch'] = promise['catch'].bind(promise);
this.then(function (result) {
complete(null, result);
}, complete);
if (!db.taskqueue.isReady) {
db.taskqueue.addTask(function () {
if (self.isCancelled) {
self.emit('cancel');
} else {
self.doChanges(opts);
}
});
} else {
self.doChanges(opts);
}
}
Changes.prototype.cancel = function () {
this.isCancelled = true;
if (this.db.taskqueue.isReady) {
this.emit('cancel');
}
};
function processChange(doc, metadata, opts) {
var changeList = [{rev: doc._rev}];
if (opts.style === 'all_docs') {
changeList = collectLeaves(metadata.rev_tree)
.map(function (x) { return {rev: x.rev}; });
}
var change = {
id: metadata.id,
changes: changeList,
doc: doc
};
if (isDeleted(metadata, doc._rev)) {
change.deleted = true;
}
if (opts.conflicts) {
change.doc._conflicts = collectConflicts(metadata);
if (!change.doc._conflicts.length) {
delete change.doc._conflicts;
}
}
return change;
}
Changes.prototype.doChanges = function (opts) {
var self = this;
var callback = opts.complete;
opts = clone(opts);
if ('live' in opts && !('continuous' in opts)) {
opts.continuous = opts.live;
}
opts.processChange = processChange;
if (opts.since === 'latest') {
opts.since = 'now';
}
if (!opts.since) {
opts.since = 0;
}
if (opts.since === 'now') {
this.db.info().then(function (info) {
/* istanbul ignore if */
if (self.isCancelled) {
callback(null, {status: 'cancelled'});
return;
}
opts.since = info.update_seq;
self.doChanges(opts);
}, callback);
return;
}
if (opts.continuous && opts.since !== 'now') {
this.db.info().then(function (info) {
self.startSeq = info.update_seq;
/* istanbul ignore next */
}, function (err) {
if (err.id === 'idbNull') {
// db closed before this returned thats ok
return;
}
throw err;
});
}
if (opts.view && !opts.filter) {
opts.filter = '_view';
}
if (opts.filter && typeof opts.filter === 'string') {
if (opts.filter === '_view') {
opts.view = normalizeDesignDocFunctionName(opts.view);
} else {
opts.filter = normalizeDesignDocFunctionName(opts.filter);
}
if (this.db.type() !== 'http' && !opts.doc_ids) {
return this.filterChanges(opts);
}
}
if (!('descending' in opts)) {
opts.descending = false;
}
// 0 and 1 should return 1 document
opts.limit = opts.limit === 0 ? 1 : opts.limit;
opts.complete = callback;
var newPromise = this.db._changes(opts);
if (newPromise && typeof newPromise.cancel === 'function') {
var cancel = self.cancel;
self.cancel = getArguments(function (args) {
newPromise.cancel();
cancel.apply(this, args);
});
}
};
Changes.prototype.filterChanges = function (opts) {
var self = this;
var callback = opts.complete;
if (opts.filter === '_view') {
if (!opts.view || typeof opts.view !== 'string') {
var err = createError(BAD_REQUEST,
'`view` filter parameter not found or invalid.');
return callback(err);
}
// fetch a view from a design doc, make it behave like a filter
var viewName = parseDesignDocFunctionName(opts.view);
this.db.get('_design/' + viewName[0], function (err, ddoc) {
/* istanbul ignore if */
if (self.isCancelled) {
return callback(null, {status: 'cancelled'});
}
/* istanbul ignore next */
if (err) {
return callback(generateErrorFromResponse(err));
}
var mapFun = ddoc && ddoc.views && ddoc.views[viewName[1]] &&
ddoc.views[viewName[1]].map;
if (!mapFun) {
return callback(createError(MISSING_DOC,
(ddoc.views ? 'missing json key: ' + viewName[1] :
'missing json key: views')));
}
opts.filter = evalView(mapFun);
self.doChanges(opts);
});
} else {
// fetch a filter from a design doc
var filterName = parseDesignDocFunctionName(opts.filter);
if (!filterName) {
return self.doChanges(opts);
}
this.db.get('_design/' + filterName[0], function (err, ddoc) {
/* istanbul ignore if */
if (self.isCancelled) {
return callback(null, {status: 'cancelled'});
}
/* istanbul ignore next */
if (err) {
return callback(generateErrorFromResponse(err));
}
var filterFun = ddoc && ddoc.filters && ddoc.filters[filterName[1]];
if (!filterFun) {
return callback(createError(MISSING_DOC,
((ddoc && ddoc.filters) ? 'missing json key: ' + filterName[1]
: 'missing json key: filters')));
}
opts.filter = evalFilter(filterFun);
self.doChanges(opts);
});
}
};
/*
* A generic pouch adapter
*/
function compare(left, right) {
return left < right ? -1 : left > right ? 1 : 0;
}
// returns first element of arr satisfying callback predicate
function arrayFirst(arr, callback) {
for (var i = 0; i < arr.length; i++) {
if (callback(arr[i], i) === true) {
return arr[i];
}
}
}
// Wrapper for functions that call the bulkdocs api with a single doc,
// if the first result is an error, return an error
function yankError(callback) {
return function (err, results) {
if (err || (results[0] && results[0].error)) {
callback(err || results[0]);
} else {
callback(null, results.length ? results[0] : results);
}
};
}
// clean docs given to us by the user
function cleanDocs(docs) {
for (var i = 0; i < docs.length; i++) {
var doc = docs[i];
if (doc._deleted) {
delete doc._attachments; // ignore atts for deleted docs
} else if (doc._attachments) {
// filter out extraneous keys from _attachments
var atts = Object.keys(doc._attachments);
for (var j = 0; j < atts.length; j++) {
var att = atts[j];
doc._attachments[att] = pick(doc._attachments[att],
['data', 'digest', 'content_type', 'length', 'revpos', 'stub']);
}
}
}
}
// compare two docs, first by _id then by _rev
function compareByIdThenRev(a, b) {
var idCompare = compare(a._id, b._id);
if (idCompare !== 0) {
return idCompare;
}
var aStart = a._revisions ? a._revisions.start : 0;
var bStart = b._revisions ? b._revisions.start : 0;
return compare(aStart, bStart);
}
// for every node in a revision tree computes its distance from the closest
// leaf
function computeHeight(revs) {
var height = {};
var edges = [];
traverseRevTree(revs, function (isLeaf, pos, id, prnt) {
var rev = pos + "-" + id;
if (isLeaf) {
height[rev] = 0;
}
if (prnt !== undefined) {
edges.push({from: prnt, to: rev});
}
return rev;
});
edges.reverse();
edges.forEach(function (edge) {
if (height[edge.from] === undefined) {
height[edge.from] = 1 + height[edge.to];
} else {
height[edge.from] = Math.min(height[edge.from], 1 + height[edge.to]);
}
});
return height;
}
function allDocsKeysQuery(api, opts, callback) {
var keys = ('limit' in opts) ?
opts.keys.slice(opts.skip, opts.limit + opts.skip) :
(opts.skip > 0) ? opts.keys.slice(opts.skip) : opts.keys;
if (opts.descending) {
keys.reverse();
}
if (!keys.length) {
return api._allDocs({limit: 0}, callback);
}
var finalResults = {
offset: opts.skip
};
return PouchPromise.all(keys.map(function (key) {
var subOpts = jsExtend.extend({key: key, deleted: 'ok'}, opts);
['limit', 'skip', 'keys'].forEach(function (optKey) {
delete subOpts[optKey];
});
return new PouchPromise(function (resolve, reject) {
api._allDocs(subOpts, function (err, res) {
/* istanbul ignore if */
if (err) {
return reject(err);
}
finalResults.total_rows = res.total_rows;
resolve(res.rows[0] || {key: key, error: 'not_found'});
});
});
})).then(function (results) {
finalResults.rows = results;
return finalResults;
});
}
// all compaction is done in a queue, to avoid attaching
// too many listeners at once
function doNextCompaction(self) {
var task = self._compactionQueue[0];
var opts = task.opts;
var callback = task.callback;
self.get('_local/compaction')["catch"](function () {
return false;
}).then(function (doc) {
if (doc && doc.last_seq) {
opts.last_seq = doc.last_seq;
}
self._compact(opts, function (err, res) {
/* istanbul ignore if */
if (err) {
callback(err);
} else {
callback(null, res);
}
process.nextTick(function () {
self._compactionQueue.shift();
if (self._compactionQueue.length) {
doNextCompaction(self);
}
});
});
});
}
function attachmentNameError(name) {
if (name.charAt(0) === '_') {
return name + 'is not a valid attachment name, attachment ' +
'names cannot start with \'_\'';
}
return false;
}
inherits(AbstractPouchDB, events.EventEmitter);
function AbstractPouchDB() {
events.EventEmitter.call(this);
}
AbstractPouchDB.prototype.post =
adapterFun('post', function (doc, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
if (typeof doc !== 'object' || Array.isArray(doc)) {
return callback(createError(NOT_AN_OBJECT));
}
this.bulkDocs({docs: [doc]}, opts, yankError(callback));
});
AbstractPouchDB.prototype.put =
adapterFun('put', getArguments(function (args) {
var temp, temptype, opts, callback;
var warned = false;
var doc = args.shift();
var id = '_id' in doc;
if (typeof doc !== 'object' || Array.isArray(doc)) {
callback = args.pop();
return callback(createError(NOT_AN_OBJECT));
}
function warn() {
if (warned) {
return;
}
guardedConsole('warn', 'db.put(doc, id, rev) has been deprecated and will be ' +
'removed in a future release, please use ' +
'db.put({_id: id, _rev: rev}) instead');
warned = true;
}
/* eslint no-constant-condition: 0 */
while (true) {
temp = args.shift();
temptype = typeof temp;
if (temptype === "string" && !id) {
warn();
doc._id = temp;
id = true;
} else if (temptype === "string" && id && !('_rev' in doc)) {
warn();
doc._rev = temp;
} else if (temptype === "object") {
opts = temp;
} else if (temptype === "function") {
callback = temp;
}
if (!args.length) {
break;
}
}
opts = opts || {};
invalidIdError(doc._id);
if (isLocalId(doc._id) && typeof this._putLocal === 'function') {
if (doc._deleted) {
return this._removeLocal(doc, callback);
} else {
return this._putLocal(doc, callback);
}
}
this.bulkDocs({docs: [doc]}, opts, yankError(callback));
}));
AbstractPouchDB.prototype.putAttachment =
adapterFun('putAttachment', function (docId, attachmentId, rev,
blob, type) {
var api = this;
if (typeof type === 'function') {
type = blob;
blob = rev;
rev = null;
}
// Lets fix in https://github.com/pouchdb/pouchdb/issues/3267
/* istanbul ignore if */
if (typeof type === 'undefined') {
type = blob;
blob = rev;
rev = null;
}
function createAttachment(doc) {
var prevrevpos = '_rev' in doc ? parseInt(doc._rev, 10) : 0;
doc._attachments = doc._attachments || {};
doc._attachments[attachmentId] = {
content_type: type,
data: blob,
revpos: ++prevrevpos
};
return api.put(doc);
}
return api.get(docId).then(function (doc) {
if (doc._rev !== rev) {
throw createError(REV_CONFLICT);
}
return createAttachment(doc);
}, function (err) {
// create new doc
/* istanbul ignore else */
if (err.reason === MISSING_DOC.message) {
return createAttachment({_id: docId});
} else {
throw err;
}
});
});
AbstractPouchDB.prototype.removeAttachment =
adapterFun('removeAttachment', function (docId, attachmentId, rev,
callback) {
var self = this;
self.get(docId, function (err, obj) {
/* istanbul ignore if */
if (err) {
callback(err);
return;
}
if (obj._rev !== rev) {
callback(createError(REV_CONFLICT));
return;
}
/* istanbul ignore if */
if (!obj._attachments) {
return callback();
}
delete obj._attachments[attachmentId];
if (Object.keys(obj._attachments).length === 0) {
delete obj._attachments;
}
self.put(obj, callback);
});
});
AbstractPouchDB.prototype.remove =
adapterFun('remove', function (docOrId, optsOrRev, opts, callback) {
var doc;
if (typeof optsOrRev === 'string') {
// id, rev, opts, callback style
doc = {
_id: docOrId,
_rev: optsOrRev
};
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
} else {
// doc, opts, callback style
doc = docOrId;
if (typeof optsOrRev === 'function') {
callback = optsOrRev;
opts = {};
} else {
callback = opts;
opts = optsOrRev;
}
}
opts = opts || {};
opts.was_delete = true;
var newDoc = {_id: doc._id, _rev: (doc._rev || opts.rev)};
newDoc._deleted = true;
if (isLocalId(newDoc._id) && typeof this._removeLocal === 'function') {
return this._removeLocal(doc, callback);
}
this.bulkDocs({docs: [newDoc]}, opts, yankError(callback));
});
AbstractPouchDB.prototype.revsDiff =
adapterFun('revsDiff', function (req, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
var ids = Object.keys(req);
if (!ids.length) {
return callback(null, {});
}
var count = 0;
var missing = new pouchdbCollections.Map();
function addToMissing(id, revId) {
if (!missing.has(id)) {
missing.set(id, {missing: []});
}
missing.get(id).missing.push(revId);
}
function processDoc(id, rev_tree) {
// Is this fast enough? Maybe we should switch to a set simulated by a map
var missingForId = req[id].slice(0);
traverseRevTree(rev_tree, function (isLeaf, pos, revHash, ctx,
opts) {
var rev = pos + '-' + revHash;
var idx = missingForId.indexOf(rev);
if (idx === -1) {
return;
}
missingForId.splice(idx, 1);
/* istanbul ignore if */
if (opts.status !== 'available') {
addToMissing(id, rev);
}
});
// Traversing the tree is synchronous, so now `missingForId` contains
// revisions that were not found in the tree
missingForId.forEach(function (rev) {
addToMissing(id, rev);
});
}
ids.map(function (id) {
this._getRevisionTree(id, function (err, rev_tree) {
if (err && err.status === 404 && err.message === 'missing') {
missing.set(id, {missing: req[id]});
} else if (err) {
/* istanbul ignore next */
return callback(err);
} else {
processDoc(id, rev_tree);
}
if (++count === ids.length) {
// convert LazyMap to object
var missingObj = {};
missing.forEach(function (value, key) {
missingObj[key] = value;
});
return callback(null, missingObj);
}
});
}, this);
});
// _bulk_get API for faster replication, as described in
// https://github.com/apache/couchdb-chttpd/pull/33
// At the "abstract" level, it will just run multiple get()s in
// parallel, because this isn't much of a performance cost
// for local databases (except the cost of multiple transactions, which is
// small). The http adapter overrides this in order
// to do a more efficient single HTTP request.
AbstractPouchDB.prototype.bulkGet =
adapterFun('bulkGet', function (opts, callback) {
bulkGet(this, opts, callback);
});
// compact one document and fire callback
// by compacting we mean removing all revisions which
// are further from the leaf in revision tree than max_height
AbstractPouchDB.prototype.compactDocument =
adapterFun('compactDocument', function (docId, maxHeight, callback) {
var self = this;
this._getRevisionTree(docId, function (err, revTree) {
/* istanbul ignore if */
if (err) {
return callback(err);
}
var height = computeHeight(revTree);
var candidates = [];
var revs = [];
Object.keys(height).forEach(function (rev) {
if (height[rev] > maxHeight) {
candidates.push(rev);
}
});
traverseRevTree(revTree, function (isLeaf, pos, revHash, ctx, opts) {
var rev = pos + '-' + revHash;
if (opts.status === 'available' && candidates.indexOf(rev) !== -1) {
revs.push(rev);
}
});
self._doCompaction(docId, revs, callback);
});
});
// compact the whole database using single document
// compaction
AbstractPouchDB.prototype.compact =
adapterFun('compact', function (opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
var self = this;
opts = opts || {};
self._compactionQueue = self._compactionQueue || [];
self._compactionQueue.push({opts: opts, callback: callback});
if (self._compactionQueue.length === 1) {
doNextCompaction(self);
}
});
AbstractPouchDB.prototype._compact = function (opts, callback) {
var self = this;
var changesOpts = {
return_docs: false,
last_seq: opts.last_seq || 0
};
var promises = [];
function onChange(row) {
promises.push(self.compactDocument(row.id, 0));
}
function onComplete(resp) {
var lastSeq = resp.last_seq;
PouchPromise.all(promises).then(function () {
return upsert(self, '_local/compaction', function deltaFunc(doc) {
if (!doc.last_seq || doc.last_seq < lastSeq) {
doc.last_seq = lastSeq;
return doc;
}
return false; // somebody else got here first, don't update
});
}).then(function () {
callback(null, {ok: true});
})["catch"](callback);
}
self.changes(changesOpts)
.on('change', onChange)
.on('complete', onComplete)
.on('error', callback);
};
/* Begin api wrappers. Specific functionality to storage belongs in the
_[method] */
AbstractPouchDB.prototype.get =
adapterFun('get', function (id, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
if (typeof id !== 'string') {
return callback(createError(INVALID_ID));
}
if (isLocalId(id) && typeof this._getLocal === 'function') {
return this._getLocal(id, callback);
}
var leaves = [], self = this;
function finishOpenRevs() {
var result = [];
var count = leaves.length;
/* istanbul ignore if */
if (!count) {
return callback(null, result);
}
// order with open_revs is unspecified
leaves.forEach(function (leaf) {
self.get(id, {
rev: leaf,
revs: opts.revs,
attachments: opts.attachments
}, function (err, doc) {
if (!err) {
result.push({ok: doc});
} else {
result.push({missing: leaf});
}
count--;
if (!count) {
callback(null, result);
}
});
});
}
if (opts.open_revs) {
if (opts.open_revs === "all") {
this._getRevisionTree(id, function (err, rev_tree) {
if (err) {
return callback(err);
}
leaves = collectLeaves(rev_tree).map(function (leaf) {
return leaf.rev;
});
finishOpenRevs();
});
} else {
if (Array.isArray(opts.open_revs)) {
leaves = opts.open_revs;
for (var i = 0; i < leaves.length; i++) {
var l = leaves[i];
// looks like it's the only thing couchdb checks
if (!(typeof (l) === "string" && /^\d+-/.test(l))) {
return callback(createError(INVALID_REV));
}
}
finishOpenRevs();
} else {
return callback(createError(UNKNOWN_ERROR,
'function_clause'));
}
}
return; // open_revs does not like other options
}
return this._get(id, opts, function (err, result) {
if (err) {
return callback(err);
}
var doc = result.doc;
var metadata = result.metadata;
var ctx = result.ctx;
if (opts.conflicts) {
var conflicts = collectConflicts(metadata);
if (conflicts.length) {
doc._conflicts = conflicts;
}
}
if (isDeleted(metadata, doc._rev)) {
doc._deleted = true;
}
if (opts.revs || opts.revs_info) {
var paths = rootToLeaf(metadata.rev_tree);
var path = arrayFirst(paths, function (arr) {
return arr.ids.map(function (x) { return x.id; })
.indexOf(doc._rev.split('-')[1]) !== -1;
});
var indexOfRev = path.ids.map(function (x) {return x.id; })
.indexOf(doc._rev.split('-')[1]) + 1;
var howMany = path.ids.length - indexOfRev;
path.ids.splice(indexOfRev, howMany);
path.ids.reverse();
if (opts.revs) {
doc._revisions = {
start: (path.pos + path.ids.length) - 1,
ids: path.ids.map(function (rev) {
return rev.id;
})
};
}
if (opts.revs_info) {
var pos = path.pos + path.ids.length;
doc._revs_info = path.ids.map(function (rev) {
pos--;
return {
rev: pos + '-' + rev.id,
status: rev.opts.status
};
});
}
}
if (opts.attachments && doc._attachments) {
var attachments = doc._attachments;
var count = Object.keys(attachments).length;
if (count === 0) {
return callback(null, doc);
}
Object.keys(attachments).forEach(function (key) {
this._getAttachment(doc._id, key, attachments[key], {
// Previously the revision handling was done in adapter.js
// getAttachment, however since idb-next doesnt we need to
// pass the rev through
rev: doc._rev,
binary: opts.binary,
ctx: ctx
}, function (err, data) {
var att = doc._attachments[key];
att.data = data;
delete att.stub;
delete att.length;
if (!--count) {
callback(null, doc);
}
});
}, self);
} else {
if (doc._attachments) {
for (var key in doc._attachments) {
/* istanbul ignore else */
if (doc._attachments.hasOwnProperty(key)) {
doc._attachments[key].stub = true;
}
}
}
callback(null, doc);
}
});
});
// TODO: I dont like this, it forces an extra read for every
// attachment read and enforces a confusing api between
// adapter.js and the adapter implementation
AbstractPouchDB.prototype.getAttachment =
adapterFun('getAttachment', function (docId, attachmentId, opts,
callback) {
var self = this;
if (opts instanceof Function) {
callback = opts;
opts = {};
}
this._get(docId, opts, function (err, res) {
if (err) {
return callback(err);
}
if (res.doc._attachments && res.doc._attachments[attachmentId]) {
opts.ctx = res.ctx;
opts.binary = true;
self._getAttachment(docId, attachmentId,
res.doc._attachments[attachmentId], opts, callback);
} else {
return callback(createError(MISSING_DOC));
}
});
});
AbstractPouchDB.prototype.allDocs =
adapterFun('allDocs', function (opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
opts.skip = typeof opts.skip !== 'undefined' ? opts.skip : 0;
if (opts.start_key) {
opts.startkey = opts.start_key;
}
if (opts.end_key) {
opts.endkey = opts.end_key;
}
if ('keys' in opts) {
if (!Array.isArray(opts.keys)) {
return callback(new TypeError('options.keys must be an array'));
}
var incompatibleOpt =
['startkey', 'endkey', 'key'].filter(function (incompatibleOpt) {
return incompatibleOpt in opts;
})[0];
if (incompatibleOpt) {
callback(createError(QUERY_PARSE_ERROR,
'Query parameter `' + incompatibleOpt +
'` is not compatible with multi-get'
));
return;
}
if (this.type() !== 'http') {
return allDocsKeysQuery(this, opts, callback);
}
}
return this._allDocs(opts, callback);
});
AbstractPouchDB.prototype.changes = function (opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return new Changes(this, opts, callback);
};
AbstractPouchDB.prototype.close =
adapterFun('close', function (callback) {
this._closed = true;
return this._close(callback);
});
AbstractPouchDB.prototype.info = adapterFun('info', function (callback) {
var self = this;
this._info(function (err, info) {
if (err) {
return callback(err);
}
// assume we know better than the adapter, unless it informs us
info.db_name = info.db_name || self._db_name;
info.auto_compaction = !!(self.auto_compaction && self.type() !== 'http');
info.adapter = self.type();
callback(null, info);
});
});
AbstractPouchDB.prototype.id = adapterFun('id', function (callback) {
return this._id(callback);
});
AbstractPouchDB.prototype.type = function () {
/* istanbul ignore next */
return (typeof this._type === 'function') ? this._type() : this.adapter;
};
AbstractPouchDB.prototype.bulkDocs =
adapterFun('bulkDocs', function (req, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
opts = opts || {};
if (Array.isArray(req)) {
req = {
docs: req
};
}
if (!req || !req.docs || !Array.isArray(req.docs)) {
return callback(createError(MISSING_BULK_DOCS));
}
for (var i = 0; i < req.docs.length; ++i) {
if (typeof req.docs[i] !== 'object' || Array.isArray(req.docs[i])) {
return callback(createError(NOT_AN_OBJECT));
}
}
var attachmentError;
req.docs.forEach(function (doc) {
if (doc._attachments) {
Object.keys(doc._attachments).forEach(function (name) {
attachmentError = attachmentError || attachmentNameError(name);
});
}
});
if (attachmentError) {
return callback(createError(BAD_REQUEST, attachmentError));
}
if (!('new_edits' in opts)) {
if ('new_edits' in req) {
opts.new_edits = req.new_edits;
} else {
opts.new_edits = true;
}
}
if (!opts.new_edits && this.type() !== 'http') {
// ensure revisions of the same doc are sorted, so that
// the local adapter processes them correctly (#2935)
req.docs.sort(compareByIdThenRev);
}
cleanDocs(req.docs);
return this._bulkDocs(req, opts, function (err, res) {
if (err) {
return callback(err);
}
if (!opts.new_edits) {
// this is what couch does when new_edits is false
res = res.filter(function (x) {
return x.error;
});
}
callback(null, res);
});
});
AbstractPouchDB.prototype.registerDependentDatabase =
adapterFun('registerDependentDatabase', function (dependentDb,
callback) {
var depDB = new this.constructor(dependentDb, this.__opts);
function diffFun(doc) {
doc.dependentDbs = doc.dependentDbs || {};
if (doc.dependentDbs[dependentDb]) {
return false; // no update required
}
doc.dependentDbs[dependentDb] = true;
return doc;
}
upsert(this, '_local/_pouch_dependentDbs', diffFun)
.then(function () {
callback(null, {db: depDB});
})["catch"](callback);
});
AbstractPouchDB.prototype.destroy =
adapterFun('destroy', function (opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
var self = this;
var usePrefix = 'use_prefix' in self ? self.use_prefix : true;
function destroyDb() {
// call destroy method of the particular adaptor
self._destroy(opts, function (err, resp) {
if (err) {
return callback(err);
}
self._destroyed = true;
self.emit('destroyed');
callback(null, resp || { 'ok': true });
});
}
if (self.type() === 'http') {
// no need to check for dependent DBs if it's a remote DB
return destroyDb();
}
self.get('_local/_pouch_dependentDbs', function (err, localDoc) {
if (err) {
/* istanbul ignore if */
if (err.status !== 404) {
return callback(err);
} else { // no dependencies
return destroyDb();
}
}
var dependentDbs = localDoc.dependentDbs;
var PouchDB = self.constructor;
var deletedMap = Object.keys(dependentDbs).map(function (name) {
// use_prefix is only false in the browser
/* istanbul ignore next */
var trueName = usePrefix ?
name.replace(new RegExp('^' + PouchDB.prefix), '') : name;
return new PouchDB(trueName, self.__opts).destroy();
});
PouchPromise.all(deletedMap).then(destroyDb, callback);
});
});
function TaskQueue() {
this.isReady = false;
this.failed = false;
this.queue = [];
}
TaskQueue.prototype.execute = function () {
var fun;
if (this.failed) {
while ((fun = this.queue.shift())) {
fun(this.failed);
}
} else {
while ((fun = this.queue.shift())) {
fun();
}
}
};
TaskQueue.prototype.fail = function (err) {
this.failed = err;
this.execute();
};
TaskQueue.prototype.ready = function (db) {
this.isReady = true;
this.db = db;
this.execute();
};
TaskQueue.prototype.addTask = function (fun) {
this.queue.push(fun);
if (this.failed) {
this.execute();
}
};
function defaultCallback(err) {
/* istanbul ignore next */
if (err && global.debug) {
guardedConsole('error', err);
}
}
// OK, so here's the deal. Consider this code:
// var db1 = new PouchDB('foo');
// var db2 = new PouchDB('foo');
// db1.destroy();
// ^ these two both need to emit 'destroyed' events,
// as well as the PouchDB constructor itself.
// So we have one db object (whichever one got destroy() called on it)
// responsible for emitting the initial event, which then gets emitted
// by the constructor, which then broadcasts it to any other dbs
// that may have been created with the same name.
function prepareForDestruction(self, opts) {
var name = opts.originalName;
var ctor = self.constructor;
var destructionListeners = ctor._destructionListeners;
function onDestroyed() {
ctor.emit('destroyed', name);
}
function onConstructorDestroyed() {
self.removeListener('destroyed', onDestroyed);
self.emit('destroyed', self);
}
self.once('destroyed', onDestroyed);
// in setup.js, the constructor is primed to listen for destroy events
if (!destructionListeners.has(name)) {
destructionListeners.set(name, []);
}
destructionListeners.get(name).push(onConstructorDestroyed);
}
inherits(PouchDB, AbstractPouchDB);
function PouchDB(name, opts, callback) {
/* istanbul ignore if */
if (!(this instanceof PouchDB)) {
return new PouchDB(name, opts, callback);
}
var self = this;
if (typeof opts === 'function' || typeof opts === 'undefined') {
callback = opts;
opts = {};
}
if (name && typeof name === 'object') {
opts = name;
name = undefined;
}
if (typeof callback === 'undefined') {
callback = defaultCallback;
} else {
var oldCallback = callback;
callback = function () {
guardedConsole('warn', 'Using a callback for new PouchDB()' +
'is deprecated.');
return oldCallback.apply(null, arguments);
};
}
name = name || opts.name;
opts = clone(opts);
// if name was specified via opts, ignore for the sake of dependentDbs
delete opts.name;
this.__opts = opts;
var oldCB = callback;
self.auto_compaction = opts.auto_compaction;
self.prefix = PouchDB.prefix;
AbstractPouchDB.call(self);
self.taskqueue = new TaskQueue();
var promise = new PouchPromise(function (fulfill, reject) {
callback = function (err, resp) {
/* istanbul ignore if */
if (err) {
return reject(err);
}
delete resp.then;
fulfill(resp);
};
opts = clone(opts);
var backend, error;
(function () {
try {
if (typeof name !== 'string') {
error = new Error('Missing/invalid DB name');
error.code = 400;
throw error;
}
var prefixedName = (opts.prefix || '') + name;
backend = PouchDB.parseAdapter(prefixedName, opts);
opts.originalName = name;
opts.name = backend.name;
opts.adapter = opts.adapter || backend.adapter;
self._adapter = opts.adapter;
debug('pouchdb:adapter')('Picked adapter: ' + opts.adapter);
self._db_name = name;
if (!PouchDB.adapters[opts.adapter]) {
error = new Error('Adapter is missing');
error.code = 404;
throw error;
}
/* istanbul ignore if */
if (!PouchDB.adapters[opts.adapter].valid()) {
error = new Error('Invalid Adapter');
error.code = 404;
throw error;
}
} catch (err) {
self.taskqueue.fail(err);
}
}());
if (error) {
return reject(error); // constructor error, see above
}
self.adapter = opts.adapter;
// needs access to PouchDB;
self.replicate = {};
self.replicate.from = function (url, opts, callback) {
return self.constructor.replicate(url, self, opts, callback);
};
self.replicate.to = function (url, opts, callback) {
return self.constructor.replicate(self, url, opts, callback);
};
self.sync = function (dbName, opts, callback) {
return self.constructor.sync(self, dbName, opts, callback);
};
self.replicate.sync = self.sync;
PouchDB.adapters[opts.adapter].call(self, opts, function (err) {
/* istanbul ignore if */
if (err) {
self.taskqueue.fail(err);
callback(err);
return;
}
prepareForDestruction(self, opts);
self.emit('created', self);
PouchDB.emit('created', opts.originalName);
self.taskqueue.ready(self);
callback(null, self);
});
});
promise.then(function (resp) {
oldCB(null, resp);
}, oldCB);
self.then = promise.then.bind(promise);
self["catch"] = promise["catch"].bind(promise);
}
PouchDB.debug = debug;
PouchDB.adapters = {};
PouchDB.preferredAdapters = [];
PouchDB.prefix = '_pouch_';
var eventEmitter = new events.EventEmitter();
function setUpEventEmitter(Pouch) {
Object.keys(events.EventEmitter.prototype).forEach(function (key) {
if (typeof events.EventEmitter.prototype[key] === 'function') {
Pouch[key] = eventEmitter[key].bind(eventEmitter);
}
});
// these are created in constructor.js, and allow us to notify each DB with
// the same name that it was destroyed, via the constructor object
var destructListeners = Pouch._destructionListeners = new pouchdbCollections.Map();
Pouch.on('destroyed', function onConstructorDestroyed(name) {
destructListeners.get(name).forEach(function (callback) {
callback();
});
destructListeners["delete"](name);
});
}
setUpEventEmitter(PouchDB);
PouchDB.parseAdapter = function (name, opts) {
var match = name.match(/([a-z\-]*):\/\/(.*)/);
var adapter, adapterName;
if (match) {
// the http adapter expects the fully qualified name
name = /http(s?)/.test(match[1]) ? match[1] + '://' + match[2] : match[2];
adapter = match[1];
/* istanbul ignore if */
if (!PouchDB.adapters[adapter].valid()) {
throw 'Invalid adapter';
}
return {name: name, adapter: match[1]};
}
// check for browsers that have been upgraded from websql-only to websql+idb
var skipIdb = 'idb' in PouchDB.adapters && 'websql' in PouchDB.adapters &&
hasLocalStorage() &&
localStorage['_pouch__websqldb_' + PouchDB.prefix + name];
if (opts.adapter) {
adapterName = opts.adapter;
} else if (typeof opts !== 'undefined' && opts.db) {
adapterName = 'leveldb';
} else { // automatically determine adapter
for (var i = 0; i < PouchDB.preferredAdapters.length; ++i) {
adapterName = PouchDB.preferredAdapters[i];
if (adapterName in PouchDB.adapters) {
/* istanbul ignore if */
if (skipIdb && adapterName === 'idb') {
// log it, because this can be confusing during development
guardedConsole('log', 'PouchDB is downgrading "' + name + '" to WebSQL to' +
' avoid data loss, because it was already opened with WebSQL.');
continue; // keep using websql to avoid user data loss
}
break;
}
}
}
adapter = PouchDB.adapters[adapterName];
// if adapter is invalid, then an error will be thrown later
var usePrefix = (adapter && 'use_prefix' in adapter) ?
adapter.use_prefix : true;
return {
name: usePrefix ? (PouchDB.prefix + name) : name,
adapter: adapterName
};
};
PouchDB.adapter = function (id, obj, addToPreferredAdapters) {
if (obj.valid()) {
PouchDB.adapters[id] = obj;
if (addToPreferredAdapters) {
PouchDB.preferredAdapters.push(id);
}
}
};
PouchDB.plugin = function (obj) {
if (typeof obj === 'function') { // function style for plugins
obj(PouchDB);
} else {
Object.keys(obj).forEach(function (id) { // object style for plugins
PouchDB.prototype[id] = obj[id];
});
}
return PouchDB;
};
PouchDB.defaults = function (defaultOpts) {
function PouchAlt(name, opts, callback) {
if (!(this instanceof PouchAlt)) {
return new PouchAlt(name, opts, callback);
}
if (typeof opts === 'function' || typeof opts === 'undefined') {
callback = opts;
opts = {};
}
if (name && typeof name === 'object') {
opts = name;
name = undefined;
}
opts = jsExtend.extend({}, defaultOpts, opts);
PouchDB.call(this, name, opts, callback);
}
inherits(PouchAlt, PouchDB);
PouchAlt.preferredAdapters = PouchDB.preferredAdapters.slice();
Object.keys(PouchDB).forEach(function (key) {
if (!(key in PouchAlt)) {
PouchAlt[key] = PouchDB[key];
}
});
return PouchAlt;
};
// managed automatically by set-version.js
var version = "5.4.4";
PouchDB.version = version;
function toObject(array) {
return array.reduce(function (obj, item) {
obj[item] = true;
return obj;
}, {});
}
// List of top level reserved words for doc
var reservedWords = toObject([
'_id',
'_rev',
'_attachments',
'_deleted',
'_revisions',
'_revs_info',
'_conflicts',
'_deleted_conflicts',
'_local_seq',
'_rev_tree',
//replication documents
'_replication_id',
'_replication_state',
'_replication_state_time',
'_replication_state_reason',
'_replication_stats',
// Specific to Couchbase Sync Gateway
'_removed'
]);
// List of reserved words that should end up the document
var dataWords = toObject([
'_attachments',
//replication documents
'_replication_id',
'_replication_state',
'_replication_state_time',
'_replication_state_reason',
'_replication_stats'
]);
function parseRevisionInfo(rev) {
if (!/^\d+\-./.test(rev)) {
return createError(INVALID_REV);
}
var idx = rev.indexOf('-');
var left = rev.substring(0, idx);
var right = rev.substring(idx + 1);
return {
prefix: parseInt(left, 10),
id: right
};
}
function makeRevTreeFromRevisions(revisions, opts) {
var pos = revisions.start - revisions.ids.length + 1;
var revisionIds = revisions.ids;
var ids = [revisionIds[0], opts, []];
for (var i = 1, len = revisionIds.length; i < len; i++) {
ids = [revisionIds[i], {status: 'missing'}, [ids]];
}
return [{
pos: pos,
ids: ids
}];
}
// Preprocess documents, parse their revisions, assign an id and a
// revision for new writes that are missing them, etc
function parseDoc(doc, newEdits) {
var nRevNum;
var newRevId;
var revInfo;
var opts = {status: 'available'};
if (doc._deleted) {
opts.deleted = true;
}
if (newEdits) {
if (!doc._id) {
doc._id = uuid();
}
newRevId = uuid(32, 16).toLowerCase();
if (doc._rev) {
revInfo = parseRevisionInfo(doc._rev);
if (revInfo.error) {
return revInfo;
}
doc._rev_tree = [{
pos: revInfo.prefix,
ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
}];
nRevNum = revInfo.prefix + 1;
} else {
doc._rev_tree = [{
pos: 1,
ids : [newRevId, opts, []]
}];
nRevNum = 1;
}
} else {
if (doc._revisions) {
doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
nRevNum = doc._revisions.start;
newRevId = doc._revisions.ids[0];
}
if (!doc._rev_tree) {
revInfo = parseRevisionInfo(doc._rev);
if (revInfo.error) {
return revInfo;
}
nRevNum = revInfo.prefix;
newRevId = revInfo.id;
doc._rev_tree = [{
pos: nRevNum,
ids: [newRevId, opts, []]
}];
}
}
invalidIdError(doc._id);
doc._rev = nRevNum + '-' + newRevId;
var result = {metadata : {}, data : {}};
for (var key in doc) {
/* istanbul ignore else */
if (Object.prototype.hasOwnProperty.call(doc, key)) {
var specialKey = key[0] === '_';
if (specialKey && !reservedWords[key]) {
var error = createError(DOC_VALIDATION, key);
error.message = DOC_VALIDATION.message + ': ' + key;
throw error;
} else if (specialKey && !dataWords[key]) {
result.metadata[key.slice(1)] = doc[key];
} else {
result.data[key] = doc[key];
}
}
}
return result;
}
//Can't find original post, but this is close
//http://stackoverflow.com/questions/6965107/ (continues on next line)
//converting-between-strings-and-arraybuffers
function arrayBufferToBinaryString(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return binary;
}
var atob$1 = function (str) {
return atob(str);
};
var btoa$1 = function (str) {
return btoa(str);
};
function arrayBufferToBase64(buffer) {
return btoa$1(arrayBufferToBinaryString(buffer));
}
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor (e.g.
// old QtWebKit versions, Android < 4.4).
function createBlob(parts, properties) {
/* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== "TypeError") {
throw e;
}
var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
WebKitBlobBuilder;
var builder = new Builder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function binaryStringToArrayBuffer(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;
}
function binStringToBluffer(binString, type) {
return createBlob([binaryStringToArrayBuffer(binString)], {type: type});
}
function b64ToBluffer(b64, type) {
return binStringToBluffer(atob$1(b64), type);
}
// shim for browsers that don't support it
function readAsBinaryString(blob, callback) {
if (typeof FileReader === 'undefined') {
// fix for Firefox in a web worker
// https://bugzilla.mozilla.org/show_bug.cgi?id=901097
return callback(arrayBufferToBinaryString(
new FileReaderSync().readAsArrayBuffer(blob)));
}
var reader = new FileReader();
var hasBinaryString = typeof reader.readAsBinaryString === 'function';
reader.onloadend = function (e) {
var result = e.target.result || '';
if (hasBinaryString) {
return callback(result);
}
callback(arrayBufferToBinaryString(result));
};
if (hasBinaryString) {
reader.readAsBinaryString(blob);
} else {
reader.readAsArrayBuffer(blob);
}
}
function blobToBase64(blobOrBuffer, callback) {
readAsBinaryString(blobOrBuffer, function (bin) {
callback(btoa$1(bin));
});
}
// simplified API. universal browser support is assumed
function readAsArrayBuffer(blob, callback) {
if (typeof FileReader === 'undefined') {
// fix for Firefox in a web worker:
// https://bugzilla.mozilla.org/show_bug.cgi?id=901097
return callback(new FileReaderSync().readAsArrayBuffer(blob));
}
var reader = new FileReader();
reader.onloadend = function (e) {
var result = e.target.result || new ArrayBuffer(0);
callback(result);
};
reader.readAsArrayBuffer(blob);
}
var setImmediateShim = global.setImmediate || global.setTimeout;
var MD5_CHUNK_SIZE = 32768;
function rawToBase64(raw) {
return btoa$1(raw);
}
function appendBuffer(buffer, data, start, end) {
if (start > 0 || end < data.byteLength) {
// only create a subarray if we really need to
data = new Uint8Array(data, start,
Math.min(end, data.byteLength) - start);
}
buffer.append(data);
}
function appendString(buffer, data, start, end) {
if (start > 0 || end < data.length) {
// only create a substring if we really need to
data = data.substring(start, end);
}
buffer.appendBinary(data);
}
function binaryMd5(data, callback) {
var inputIsString = typeof data === 'string';
var len = inputIsString ? data.length : data.byteLength;
var chunkSize = Math.min(MD5_CHUNK_SIZE, len);
var chunks = Math.ceil(len / chunkSize);
var currentChunk = 0;
var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();
var append = inputIsString ? appendString : appendBuffer;
function loadNextChunk() {
var start = currentChunk * chunkSize;
var end = start + chunkSize;
currentChunk++;
if (currentChunk < chunks) {
append(buffer, data, start, end);
setImmediateShim(loadNextChunk);
} else {
append(buffer, data, start, end);
var raw = buffer.end(true);
var base64 = rawToBase64(raw);
callback(base64);
buffer.destroy();
}
}
loadNextChunk();
}
function stringMd5(string) {
return Md5.hash(string);
}
function preprocessAttachments(docInfos, blobType, callback) {
if (!docInfos.length) {
return callback();
}
var docv = 0;
function parseBase64(data) {
try {
return atob$1(data);
} catch (e) {
var err = createError(BAD_ARG,
'Attachment is not a valid base64 string');
return {error: err};
}
}
function preprocessAttachment(att, callback) {
if (att.stub) {
return callback();
}
if (typeof att.data === 'string') {
// input is assumed to be a base64 string
var asBinary = parseBase64(att.data);
if (asBinary.error) {
return callback(asBinary.error);
}
att.length = asBinary.length;
if (blobType === 'blob') {
att.data = binStringToBluffer(asBinary, att.content_type);
} else if (blobType === 'base64') {
att.data = btoa$1(asBinary);
} else { // binary
att.data = asBinary;
}
binaryMd5(asBinary, function (result) {
att.digest = 'md5-' + result;
callback();
});
} else { // input is a blob
readAsArrayBuffer(att.data, function (buff) {
if (blobType === 'binary') {
att.data = arrayBufferToBinaryString(buff);
} else if (blobType === 'base64') {
att.data = arrayBufferToBase64(buff);
}
binaryMd5(buff, function (result) {
att.digest = 'md5-' + result;
att.length = buff.byteLength;
callback();
});
});
}
}
var overallErr;
docInfos.forEach(function (docInfo) {
var attachments = docInfo.data && docInfo.data._attachments ?
Object.keys(docInfo.data._attachments) : [];
var recv = 0;
if (!attachments.length) {
return done();
}
function processedAttachment(err) {
overallErr = err;
recv++;
if (recv === attachments.length) {
done();
}
}
for (var key in docInfo.data._attachments) {
if (docInfo.data._attachments.hasOwnProperty(key)) {
preprocessAttachment(docInfo.data._attachments[key],
processedAttachment);
}
}
});
function done() {
docv++;
if (docInfos.length === docv) {
if (overallErr) {
callback(overallErr);
} else {
callback();
}
}
}
}
function updateDoc(revLimit, prev, docInfo, results,
i, cb, writeDoc, newEdits) {
if (revExists(prev.rev_tree, docInfo.metadata.rev)) {
results[i] = docInfo;
return cb();
}
// sometimes this is pre-calculated. historically not always
var previousWinningRev = prev.winningRev || winningRev(prev);
var previouslyDeleted = 'deleted' in prev ? prev.deleted :
isDeleted(prev, previousWinningRev);
var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :
isDeleted(docInfo.metadata);
var isRoot = /^1-/.test(docInfo.metadata.rev);
if (previouslyDeleted && !deleted && newEdits && isRoot) {
var newDoc = docInfo.data;
newDoc._rev = previousWinningRev;
newDoc._id = docInfo.metadata.id;
docInfo = parseDoc(newDoc, newEdits);
}
var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);
var inConflict = newEdits && (((previouslyDeleted && deleted) ||
(!previouslyDeleted && merged.conflicts !== 'new_leaf') ||
(previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));
if (inConflict) {
var err = createError(REV_CONFLICT);
results[i] = err;
return cb();
}
var newRev = docInfo.metadata.rev;
docInfo.metadata.rev_tree = merged.tree;
docInfo.stemmedRevs = merged.stemmedRevs || [];
/* istanbul ignore else */
if (prev.rev_map) {
docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb
}
// recalculate
var winningRev$$ = winningRev(docInfo.metadata);
var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$);
// calculate the total number of documents that were added/removed,
// from the perspective of total_rows/doc_count
var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :
previouslyDeleted < winningRevIsDeleted ? -1 : 1;
var newRevIsDeleted;
if (newRev === winningRev$$) {
// if the new rev is the same as the winning rev, we can reuse that value
newRevIsDeleted = winningRevIsDeleted;
} else {
// if they're not the same, then we need to recalculate
newRevIsDeleted = isDeleted(docInfo.metadata, newRev);
}
writeDoc(docInfo, winningRev$$, winningRevIsDeleted, newRevIsDeleted,
true, delta, i, cb);
}
function rootIsMissing(docInfo) {
return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';
}
function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
writeDoc, opts, overallCallback) {
// Default to 1000 locally
revLimit = revLimit || 1000;
function insertDoc(docInfo, resultsIdx, callback) {
// Cant insert new deleted documents
var winningRev$$ = winningRev(docInfo.metadata);
var deleted = isDeleted(docInfo.metadata, winningRev$$);
if ('was_delete' in opts && deleted) {
results[resultsIdx] = createError(MISSING_DOC, 'deleted');
return callback();
}
// 4712 - detect whether a new document was inserted with a _rev
var inConflict = newEdits && rootIsMissing(docInfo);
if (inConflict) {
var err = createError(REV_CONFLICT);
results[resultsIdx] = err;
return callback();
}
var delta = deleted ? 0 : 1;
writeDoc(docInfo, winningRev$$, deleted, deleted, false,
delta, resultsIdx, callback);
}
var newEdits = opts.new_edits;
var idsToDocs = new pouchdbCollections.Map();
var docsDone = 0;
var docsToDo = docInfos.length;
function checkAllDocsDone() {
if (++docsDone === docsToDo && overallCallback) {
overallCallback();
}
}
docInfos.forEach(function (currentDoc, resultsIdx) {
if (currentDoc._id && isLocalId(currentDoc._id)) {
var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';
api[fun](currentDoc, {ctx: tx}, function (err, res) {
results[resultsIdx] = err || res;
checkAllDocsDone();
});
return;
}
var id = currentDoc.metadata.id;
if (idsToDocs.has(id)) {
docsToDo--; // duplicate
idsToDocs.get(id).push([currentDoc, resultsIdx]);
} else {
idsToDocs.set(id, [[currentDoc, resultsIdx]]);
}
});
// in the case of new_edits, the user can provide multiple docs
// with the same id. these need to be processed sequentially
idsToDocs.forEach(function (docs, id) {
var numDone = 0;
function docWritten() {
if (++numDone < docs.length) {
nextDoc();
} else {
checkAllDocsDone();
}
}
function nextDoc() {
var value = docs[numDone];
var currentDoc = value[0];
var resultsIdx = value[1];
if (fetchedDocs.has(id)) {
updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,
resultsIdx, docWritten, writeDoc, newEdits);
} else {
// Ensure stemming applies to new writes as well
var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);
currentDoc.metadata.rev_tree = merged.tree;
currentDoc.stemmedRevs = merged.stemmedRevs || [];
insertDoc(currentDoc, resultsIdx, docWritten);
}
}
nextDoc();
});
}
// IndexedDB requires a versioned database structure, so we use the
// version here to manage migrations.
var ADAPTER_VERSION = 5;
// The object stores created for each database
// DOC_STORE stores the document meta data, its revision history and state
// Keyed by document id
var DOC_STORE = 'document-store';
// BY_SEQ_STORE stores a particular version of a document, keyed by its
// sequence id
var BY_SEQ_STORE = 'by-sequence';
// Where we store attachments
var ATTACH_STORE = 'attach-store';
// Where we store many-to-many relations
// between attachment digests and seqs
var ATTACH_AND_SEQ_STORE = 'attach-seq-store';
// Where we store database-wide meta data in a single record
// keyed by id: META_STORE
var META_STORE = 'meta-store';
// Where we store local documents
var LOCAL_STORE = 'local-store';
// Where we detect blob support
var DETECT_BLOB_SUPPORT_STORE = 'detect-blob-support';
function slowJsonParse(str) {
try {
return JSON.parse(str);
} catch (e) {
/* istanbul ignore next */
return vuvuzela.parse(str);
}
}
function safeJsonParse(str) {
// try/catch is deoptimized in V8, leading to slower
// times than we'd like to have. Most documents are _not_
// huge, and do not require a slower code path just to parse them.
// We can be pretty sure that a document under 50000 characters
// will not be so deeply nested as to throw a stack overflow error
// (depends on the engine and available memory, though, so this is
// just a hunch). 50000 was chosen based on the average length
// of this string in our test suite, to try to find a number that covers
// most of our test cases (26 over this size, 26378 under it).
if (str.length < 50000) {
return JSON.parse(str);
}
return slowJsonParse(str);
}
function safeJsonStringify(json) {
try {
return JSON.stringify(json);
} catch (e) {
/* istanbul ignore next */
return vuvuzela.stringify(json);
}
}
function tryCode(fun, that, args, PouchDB) {
try {
fun.apply(that, args);
} catch (err) {
// Shouldn't happen, but in some odd cases
// IndexedDB implementations might throw a sync
// error, in which case this will at least log it.
PouchDB.emit('error', err);
}
}
var taskQueue = {
running: false,
queue: []
};
function applyNext(PouchDB) {
if (taskQueue.running || !taskQueue.queue.length) {
return;
}
taskQueue.running = true;
var item = taskQueue.queue.shift();
item.action(function (err, res) {
tryCode(item.callback, this, [err, res], PouchDB);
taskQueue.running = false;
process.nextTick(function () {
applyNext(PouchDB);
});
});
}
function idbError(callback) {
return function (evt) {
var message = 'unknown_error';
if (evt.target && evt.target.error) {
message = evt.target.error.name || evt.target.error.message;
}
callback(createError(IDB_ERROR, message, evt.type));
};
}
// Unfortunately, the metadata has to be stringified
// when it is put into the database, because otherwise
// IndexedDB can throw errors for deeply-nested objects.
// Originally we just used JSON.parse/JSON.stringify; now
// we use this custom vuvuzela library that avoids recursion.
// If we could do it all over again, we'd probably use a
// format for the revision trees other than JSON.
function encodeMetadata(metadata, winningRev, deleted) {
return {
data: safeJsonStringify(metadata),
winningRev: winningRev,
deletedOrLocal: deleted ? '1' : '0',
seq: metadata.seq, // highest seq for this doc
id: metadata.id
};
}
function decodeMetadata(storedObject) {
if (!storedObject) {
return null;
}
var metadata = safeJsonParse(storedObject.data);
metadata.winningRev = storedObject.winningRev;
metadata.deleted = storedObject.deletedOrLocal === '1';
metadata.seq = storedObject.seq;
return metadata;
}
// read the doc back out from the database. we don't store the
// _id or _rev because we already have _doc_id_rev.
function decodeDoc(doc) {
if (!doc) {
return doc;
}
var idx = doc._doc_id_rev.lastIndexOf(':');
doc._id = doc._doc_id_rev.substring(0, idx - 1);
doc._rev = doc._doc_id_rev.substring(idx + 1);
delete doc._doc_id_rev;
return doc;
}
// Read a blob from the database, encoding as necessary
// and translating from base64 if the IDB doesn't support
// native Blobs
function readBlobData(body, type, asBlob, callback) {
if (asBlob) {
if (!body) {
callback(createBlob([''], {type: type}));
} else if (typeof body !== 'string') { // we have blob support
callback(body);
} else { // no blob support
callback(b64ToBluffer(body, type));
}
} else { // as base64 string
if (!body) {
callback('');
} else if (typeof body !== 'string') { // we have blob support
readAsBinaryString(body, function (binary) {
callback(btoa$1(binary));
});
} else { // no blob support
callback(body);
}
}
}
function fetchAttachmentsIfNecessary(doc, opts, txn, cb) {
var attachments = Object.keys(doc._attachments || {});
if (!attachments.length) {
return cb && cb();
}
var numDone = 0;
function checkDone() {
if (++numDone === attachments.length && cb) {
cb();
}
}
function fetchAttachment(doc, att) {
var attObj = doc._attachments[att];
var digest = attObj.digest;
var req = txn.objectStore(ATTACH_STORE).get(digest);
req.onsuccess = function (e) {
attObj.body = e.target.result.body;
checkDone();
};
}
attachments.forEach(function (att) {
if (opts.attachments && opts.include_docs) {
fetchAttachment(doc, att);
} else {
doc._attachments[att].stub = true;
checkDone();
}
});
}
// IDB-specific postprocessing necessary because
// we don't know whether we stored a true Blob or
// a base64-encoded string, and if it's a Blob it
// needs to be read outside of the transaction context
function postProcessAttachments(results, asBlob) {
return PouchPromise.all(results.map(function (row) {
if (row.doc && row.doc._attachments) {
var attNames = Object.keys(row.doc._attachments);
return PouchPromise.all(attNames.map(function (att) {
var attObj = row.doc._attachments[att];
if (!('body' in attObj)) { // already processed
return;
}
var body = attObj.body;
var type = attObj.content_type;
return new PouchPromise(function (resolve) {
readBlobData(body, type, asBlob, function (data) {
row.doc._attachments[att] = jsExtend.extend(
pick(attObj, ['digest', 'content_type']),
{data: data}
);
resolve();
});
});
}));
}
}));
}
function compactRevs(revs, docId, txn) {
var possiblyOrphanedDigests = [];
var seqStore = txn.objectStore(BY_SEQ_STORE);
var attStore = txn.objectStore(ATTACH_STORE);
var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);
var count = revs.length;
function checkDone() {
count--;
if (!count) { // done processing all revs
deleteOrphanedAttachments();
}
}
function deleteOrphanedAttachments() {
if (!possiblyOrphanedDigests.length) {
return;
}
possiblyOrphanedDigests.forEach(function (digest) {
var countReq = attAndSeqStore.index('digestSeq').count(
IDBKeyRange.bound(
digest + '::', digest + '::\uffff', false, false));
countReq.onsuccess = function (e) {
var count = e.target.result;
if (!count) {
// orphaned
attStore["delete"](digest);
}
};
});
}
revs.forEach(function (rev) {
var index = seqStore.index('_doc_id_rev');
var key = docId + "::" + rev;
index.getKey(key).onsuccess = function (e) {
var seq = e.target.result;
if (typeof seq !== 'number') {
return checkDone();
}
seqStore["delete"](seq);
var cursor = attAndSeqStore.index('seq')
.openCursor(IDBKeyRange.only(seq));
cursor.onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
var digest = cursor.value.digestSeq.split('::')[0];
possiblyOrphanedDigests.push(digest);
attAndSeqStore["delete"](cursor.primaryKey);
cursor["continue"]();
} else { // done
checkDone();
}
};
};
});
}
function openTransactionSafely(idb, stores, mode) {
try {
return {
txn: idb.transaction(stores, mode)
};
} catch (err) {
return {
error: err
};
}
}
function idbBulkDocs(dbOpts, req, opts, api, idb, idbChanges, callback) {
var docInfos = req.docs;
var txn;
var docStore;
var bySeqStore;
var attachStore;
var attachAndSeqStore;
var docInfoError;
var docCountDelta = 0;
for (var i = 0, len = docInfos.length; i < len; i++) {
var doc = docInfos[i];
if (doc._id && isLocalId(doc._id)) {
continue;
}
doc = docInfos[i] = parseDoc(doc, opts.new_edits);
if (doc.error && !docInfoError) {
docInfoError = doc;
}
}
if (docInfoError) {
return callback(docInfoError);
}
var results = new Array(docInfos.length);
var fetchedDocs = new pouchdbCollections.Map();
var preconditionErrored = false;
var blobType = api._meta.blobSupport ? 'blob' : 'base64';
preprocessAttachments(docInfos, blobType, function (err) {
if (err) {
return callback(err);
}
startTransaction();
});
function startTransaction() {
var stores = [
DOC_STORE, BY_SEQ_STORE,
ATTACH_STORE,
LOCAL_STORE, ATTACH_AND_SEQ_STORE
];
var txnResult = openTransactionSafely(idb, stores, 'readwrite');
if (txnResult.error) {
return callback(txnResult.error);
}
txn = txnResult.txn;
txn.onabort = idbError(callback);
txn.ontimeout = idbError(callback);
txn.oncomplete = complete;
docStore = txn.objectStore(DOC_STORE);
bySeqStore = txn.objectStore(BY_SEQ_STORE);
attachStore = txn.objectStore(ATTACH_STORE);
attachAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);
verifyAttachments(function (err) {
if (err) {
preconditionErrored = true;
return callback(err);
}
fetchExistingDocs();
});
}
function idbProcessDocs() {
processDocs(dbOpts.revs_limit, docInfos, api, fetchedDocs,
txn, results, writeDoc, opts);
}
function fetchExistingDocs() {
if (!docInfos.length) {
return;
}
var numFetched = 0;
function checkDone() {
if (++numFetched === docInfos.length) {
idbProcessDocs();
}
}
function readMetadata(event) {
var metadata = decodeMetadata(event.target.result);
if (metadata) {
fetchedDocs.set(metadata.id, metadata);
}
checkDone();
}
for (var i = 0, len = docInfos.length; i < len; i++) {
var docInfo = docInfos[i];
if (docInfo._id && isLocalId(docInfo._id)) {
checkDone(); // skip local docs
continue;
}
var req = docStore.get(docInfo.metadata.id);
req.onsuccess = readMetadata;
}
}
function complete() {
if (preconditionErrored) {
return;
}
idbChanges.notify(api._meta.name);
api._meta.docCount += docCountDelta;
callback(null, results);
}
function verifyAttachment(digest, callback) {
var req = attachStore.get(digest);
req.onsuccess = function (e) {
if (!e.target.result) {
var err = createError(MISSING_STUB,
'unknown stub attachment with digest ' +
digest);
err.status = 412;
callback(err);
} else {
callback();
}
};
}
function verifyAttachments(finish) {
var digests = [];
docInfos.forEach(function (docInfo) {
if (docInfo.data && docInfo.data._attachments) {
Object.keys(docInfo.data._attachments).forEach(function (filename) {
var att = docInfo.data._attachments[filename];
if (att.stub) {
digests.push(att.digest);
}
});
}
});
if (!digests.length) {
return finish();
}
var numDone = 0;
var err;
function checkDone() {
if (++numDone === digests.length) {
finish(err);
}
}
digests.forEach(function (digest) {
verifyAttachment(digest, function (attErr) {
if (attErr && !err) {
err = attErr;
}
checkDone();
});
});
}
function writeDoc(docInfo, winningRev, winningRevIsDeleted, newRevIsDeleted,
isUpdate, delta, resultsIdx, callback) {
docCountDelta += delta;
docInfo.metadata.winningRev = winningRev;
docInfo.metadata.deleted = winningRevIsDeleted;
var doc = docInfo.data;
doc._id = docInfo.metadata.id;
doc._rev = docInfo.metadata.rev;
if (newRevIsDeleted) {
doc._deleted = true;
}
var hasAttachments = doc._attachments &&
Object.keys(doc._attachments).length;
if (hasAttachments) {
return writeAttachments(docInfo, winningRev, winningRevIsDeleted,
isUpdate, resultsIdx, callback);
}
finishDoc(docInfo, winningRev, winningRevIsDeleted,
isUpdate, resultsIdx, callback);
}
function finishDoc(docInfo, winningRev, winningRevIsDeleted,
isUpdate, resultsIdx, callback) {
var doc = docInfo.data;
var metadata = docInfo.metadata;
doc._doc_id_rev = metadata.id + '::' + metadata.rev;
delete doc._id;
delete doc._rev;
function afterPutDoc(e) {
var revsToDelete = docInfo.stemmedRevs || [];
if (isUpdate && api.auto_compaction) {
revsToDelete = revsToDelete.concat(compactTree(docInfo.metadata));
}
if (revsToDelete && revsToDelete.length) {
compactRevs(revsToDelete, docInfo.metadata.id, txn);
}
metadata.seq = e.target.result;
// Current _rev is calculated from _rev_tree on read
delete metadata.rev;
var metadataToStore = encodeMetadata(metadata, winningRev,
winningRevIsDeleted);
var metaDataReq = docStore.put(metadataToStore);
metaDataReq.onsuccess = afterPutMetadata;
}
function afterPutDocError(e) {
// ConstraintError, need to update, not put (see #1638 for details)
e.preventDefault(); // avoid transaction abort
e.stopPropagation(); // avoid transaction onerror
var index = bySeqStore.index('_doc_id_rev');
var getKeyReq = index.getKey(doc._doc_id_rev);
getKeyReq.onsuccess = function (e) {
var putReq = bySeqStore.put(doc, e.target.result);
putReq.onsuccess = afterPutDoc;
};
}
function afterPutMetadata() {
results[resultsIdx] = {
ok: true,
id: metadata.id,
rev: winningRev
};
fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);
insertAttachmentMappings(docInfo, metadata.seq, callback);
}
var putReq = bySeqStore.put(doc);
putReq.onsuccess = afterPutDoc;
putReq.onerror = afterPutDocError;
}
function writeAttachments(docInfo, winningRev, winningRevIsDeleted,
isUpdate, resultsIdx, callback) {
var doc = docInfo.data;
var numDone = 0;
var attachments = Object.keys(doc._attachments);
function collectResults() {
if (numDone === attachments.length) {
finishDoc(docInfo, winningRev, winningRevIsDeleted,
isUpdate, resultsIdx, callback);
}
}
function attachmentSaved() {
numDone++;
collectResults();
}
attachments.forEach(function (key) {
var att = docInfo.data._attachments[key];
if (!att.stub) {
var data = att.data;
delete att.data;
att.revpos = parseInt(winningRev, 10);
var digest = att.digest;
saveAttachment(digest, data, attachmentSaved);
} else {
numDone++;
collectResults();
}
});
}
// map seqs to attachment digests, which
// we will need later during compaction
function insertAttachmentMappings(docInfo, seq, callback) {
var attsAdded = 0;
var attsToAdd = Object.keys(docInfo.data._attachments || {});
if (!attsToAdd.length) {
return callback();
}
function checkDone() {
if (++attsAdded === attsToAdd.length) {
callback();
}
}
function add(att) {
var digest = docInfo.data._attachments[att].digest;
var req = attachAndSeqStore.put({
seq: seq,
digestSeq: digest + '::' + seq
});
req.onsuccess = checkDone;
req.onerror = function (e) {
// this callback is for a constaint error, which we ignore
// because this docid/rev has already been associated with
// the digest (e.g. when new_edits == false)
e.preventDefault(); // avoid transaction abort
e.stopPropagation(); // avoid transaction onerror
checkDone();
};
}
for (var i = 0; i < attsToAdd.length; i++) {
add(attsToAdd[i]); // do in parallel
}
}
function saveAttachment(digest, data, callback) {
var getKeyReq = attachStore.count(digest);
getKeyReq.onsuccess = function (e) {
var count = e.target.result;
if (count) {
return callback(); // already exists
}
var newAtt = {
digest: digest,
body: data
};
var putReq = attachStore.put(newAtt);
putReq.onsuccess = callback;
};
}
}
function createKeyRange(start, end, inclusiveEnd, key, descending) {
try {
if (start && end) {
if (descending) {
return IDBKeyRange.bound(end, start, !inclusiveEnd, false);
} else {
return IDBKeyRange.bound(start, end, false, !inclusiveEnd);
}
} else if (start) {
if (descending) {
return IDBKeyRange.upperBound(start);
} else {
return IDBKeyRange.lowerBound(start);
}
} else if (end) {
if (descending) {
return IDBKeyRange.lowerBound(end, !inclusiveEnd);
} else {
return IDBKeyRange.upperBound(end, !inclusiveEnd);
}
} else if (key) {
return IDBKeyRange.only(key);
}
} catch (e) {
return {error: e};
}
return null;
}
function handleKeyRangeError(api, opts, err, callback) {
if (err.name === "DataError" && err.code === 0) {
// data error, start is less than end
return callback(null, {
total_rows: api._meta.docCount,
offset: opts.skip,
rows: []
});
}
callback(createError(IDB_ERROR, err.name, err.message));
}
function idbAllDocs(opts, api, idb, callback) {
function allDocsQuery(opts, callback) {
var start = 'startkey' in opts ? opts.startkey : false;
var end = 'endkey' in opts ? opts.endkey : false;
var key = 'key' in opts ? opts.key : false;
var skip = opts.skip || 0;
var limit = typeof opts.limit === 'number' ? opts.limit : -1;
var inclusiveEnd = opts.inclusive_end !== false;
var descending = 'descending' in opts && opts.descending ? 'prev' : null;
var keyRange = createKeyRange(start, end, inclusiveEnd, key, descending);
if (keyRange && keyRange.error) {
return handleKeyRangeError(api, opts, keyRange.error, callback);
}
var stores = [DOC_STORE, BY_SEQ_STORE];
if (opts.attachments) {
stores.push(ATTACH_STORE);
}
var txnResult = openTransactionSafely(idb, stores, 'readonly');
if (txnResult.error) {
return callback(txnResult.error);
}
var txn = txnResult.txn;
var docStore = txn.objectStore(DOC_STORE);
var seqStore = txn.objectStore(BY_SEQ_STORE);
var cursor = descending ?
docStore.openCursor(keyRange, descending) :
docStore.openCursor(keyRange);
var docIdRevIndex = seqStore.index('_doc_id_rev');
var results = [];
var docCount = 0;
// if the user specifies include_docs=true, then we don't
// want to block the main cursor while we're fetching the doc
function fetchDocAsynchronously(metadata, row, winningRev) {
var key = metadata.id + "::" + winningRev;
docIdRevIndex.get(key).onsuccess = function onGetDoc(e) {
row.doc = decodeDoc(e.target.result);
if (opts.conflicts) {
row.doc._conflicts = collectConflicts(metadata);
}
fetchAttachmentsIfNecessary(row.doc, opts, txn);
};
}
function allDocsInner(cursor, winningRev, metadata) {
var row = {
id: metadata.id,
key: metadata.id,
value: {
rev: winningRev
}
};
var deleted = metadata.deleted;
if (opts.deleted === 'ok') {
results.push(row);
// deleted docs are okay with "keys" requests
if (deleted) {
row.value.deleted = true;
row.doc = null;
} else if (opts.include_docs) {
fetchDocAsynchronously(metadata, row, winningRev);
}
} else if (!deleted && skip-- <= 0) {
results.push(row);
if (opts.include_docs) {
fetchDocAsynchronously(metadata, row, winningRev);
}
if (--limit === 0) {
return;
}
}
cursor["continue"]();
}
function onGetCursor(e) {
docCount = api._meta.docCount; // do this within the txn for consistency
var cursor = e.target.result;
if (!cursor) {
return;
}
var metadata = decodeMetadata(cursor.value);
var winningRev = metadata.winningRev;
allDocsInner(cursor, winningRev, metadata);
}
function onResultsReady() {
callback(null, {
total_rows: docCount,
offset: opts.skip,
rows: results
});
}
function onTxnComplete() {
if (opts.attachments) {
postProcessAttachments(results, opts.binary).then(onResultsReady);
} else {
onResultsReady();
}
}
txn.oncomplete = onTxnComplete;
cursor.onsuccess = onGetCursor;
}
function allDocs(opts, callback) {
if (opts.limit === 0) {
return callback(null, {
total_rows: api._meta.docCount,
offset: opts.skip,
rows: []
});
}
allDocsQuery(opts, callback);
}
allDocs(opts, callback);
}
//
// Blobs are not supported in all versions of IndexedDB, notably
// Chrome <37 and Android <5. In those versions, storing a blob will throw.
//
// Various other blob bugs exist in Chrome v37-42 (inclusive).
// Detecting them is expensive and confusing to users, and Chrome 37-42
// is at very low usage worldwide, so we do a hacky userAgent check instead.
//
// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
// 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 checkBlobSupport(txn) {
return new PouchPromise(function (resolve) {
var blob = createBlob(['']);
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
txn.onabort = function (e) {
// If the transaction aborts now its due to not being able to
// write to the database, likely due to the disk being full
e.preventDefault();
e.stopPropagation();
resolve(false);
};
txn.oncomplete = function () {
var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
var matchedEdge = navigator.userAgent.match(/Edge\//);
// MS Edge pretends to be Chrome 42:
// https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
resolve(matchedEdge || !matchedChrome ||
parseInt(matchedChrome[1], 10) >= 43);
};
})["catch"](function () {
return false; // error, so assume unsupported
});
}
var cachedDBs = new pouchdbCollections.Map();
var blobSupportPromise;
var idbChanges = new Changes$1();
var openReqList = new pouchdbCollections.Map();
function IdbPouch(opts, callback) {
var api = this;
taskQueue.queue.push({
action: function (thisCallback) {
init(api, opts, thisCallback);
},
callback: callback
});
applyNext(api.constructor);
}
function init(api, opts, callback) {
var dbName = opts.name;
var idb = null;
api._meta = null;
// called when creating a fresh new database
function createSchema(db) {
var docStore = db.createObjectStore(DOC_STORE, {keyPath : 'id'});
db.createObjectStore(BY_SEQ_STORE, {autoIncrement: true})
.createIndex('_doc_id_rev', '_doc_id_rev', {unique: true});
db.createObjectStore(ATTACH_STORE, {keyPath: 'digest'});
db.createObjectStore(META_STORE, {keyPath: 'id', autoIncrement: false});
db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
// added in v2
docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false});
// added in v3
db.createObjectStore(LOCAL_STORE, {keyPath: '_id'});
// added in v4
var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE,
{autoIncrement: true});
attAndSeqStore.createIndex('seq', 'seq');
attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true});
}
// migration to version 2
// unfortunately "deletedOrLocal" is a misnomer now that we no longer
// store local docs in the main doc-store, but whaddyagonnado
function addDeletedOrLocalIndex(txn, callback) {
var docStore = txn.objectStore(DOC_STORE);
docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false});
docStore.openCursor().onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
var metadata = cursor.value;
var deleted = isDeleted(metadata);
metadata.deletedOrLocal = deleted ? "1" : "0";
docStore.put(metadata);
cursor["continue"]();
} else {
callback();
}
};
}
// migration to version 3 (part 1)
function createLocalStoreSchema(db) {
db.createObjectStore(LOCAL_STORE, {keyPath: '_id'})
.createIndex('_doc_id_rev', '_doc_id_rev', {unique: true});
}
// migration to version 3 (part 2)
function migrateLocalStore(txn, cb) {
var localStore = txn.objectStore(LOCAL_STORE);
var docStore = txn.objectStore(DOC_STORE);
var seqStore = txn.objectStore(BY_SEQ_STORE);
var cursor = docStore.openCursor();
cursor.onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
var metadata = cursor.value;
var docId = metadata.id;
var local = isLocalId(docId);
var rev = winningRev(metadata);
if (local) {
var docIdRev = docId + "::" + rev;
// remove all seq entries
// associated with this docId
var start = docId + "::";
var end = docId + "::~";
var index = seqStore.index('_doc_id_rev');
var range = IDBKeyRange.bound(start, end, false, false);
var seqCursor = index.openCursor(range);
seqCursor.onsuccess = function (e) {
seqCursor = e.target.result;
if (!seqCursor) {
// done
docStore["delete"](cursor.primaryKey);
cursor["continue"]();
} else {
var data = seqCursor.value;
if (data._doc_id_rev === docIdRev) {
localStore.put(data);
}
seqStore["delete"](seqCursor.primaryKey);
seqCursor["continue"]();
}
};
} else {
cursor["continue"]();
}
} else if (cb) {
cb();
}
};
}
// migration to version 4 (part 1)
function addAttachAndSeqStore(db) {
var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE,
{autoIncrement: true});
attAndSeqStore.createIndex('seq', 'seq');
attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true});
}
// migration to version 4 (part 2)
function migrateAttsAndSeqs(txn, callback) {
var seqStore = txn.objectStore(BY_SEQ_STORE);
var attStore = txn.objectStore(ATTACH_STORE);
var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);
// need to actually populate the table. this is the expensive part,
// so as an optimization, check first that this database even
// contains attachments
var req = attStore.count();
req.onsuccess = function (e) {
var count = e.target.result;
if (!count) {
return callback(); // done
}
seqStore.openCursor().onsuccess = function (e) {
var cursor = e.target.result;
if (!cursor) {
return callback(); // done
}
var doc = cursor.value;
var seq = cursor.primaryKey;
var atts = Object.keys(doc._attachments || {});
var digestMap = {};
for (var j = 0; j < atts.length; j++) {
var att = doc._attachments[atts[j]];
digestMap[att.digest] = true; // uniq digests, just in case
}
var digests = Object.keys(digestMap);
for (j = 0; j < digests.length; j++) {
var digest = digests[j];
attAndSeqStore.put({
seq: seq,
digestSeq: digest + '::' + seq
});
}
cursor["continue"]();
};
};
}
// migration to version 5
// Instead of relying on on-the-fly migration of metadata,
// this brings the doc-store to its modern form:
// - metadata.winningrev
// - metadata.seq
// - stringify the metadata when storing it
function migrateMetadata(txn) {
function decodeMetadataCompat(storedObject) {
if (!storedObject.data) {
// old format, when we didn't store it stringified
storedObject.deleted = storedObject.deletedOrLocal === '1';
return storedObject;
}
return decodeMetadata(storedObject);
}
// ensure that every metadata has a winningRev and seq,
// which was previously created on-the-fly but better to migrate
var bySeqStore = txn.objectStore(BY_SEQ_STORE);
var docStore = txn.objectStore(DOC_STORE);
var cursor = docStore.openCursor();
cursor.onsuccess = function (e) {
var cursor = e.target.result;
if (!cursor) {
return; // done
}
var metadata = decodeMetadataCompat(cursor.value);
metadata.winningRev = metadata.winningRev ||
winningRev(metadata);
function fetchMetadataSeq() {
// metadata.seq was added post-3.2.0, so if it's missing,
// we need to fetch it manually
var start = metadata.id + '::';
var end = metadata.id + '::\uffff';
var req = bySeqStore.index('_doc_id_rev').openCursor(
IDBKeyRange.bound(start, end));
var metadataSeq = 0;
req.onsuccess = function (e) {
var cursor = e.target.result;
if (!cursor) {
metadata.seq = metadataSeq;
return onGetMetadataSeq();
}
var seq = cursor.primaryKey;
if (seq > metadataSeq) {
metadataSeq = seq;
}
cursor["continue"]();
};
}
function onGetMetadataSeq() {
var metadataToStore = encodeMetadata(metadata,
metadata.winningRev, metadata.deleted);
var req = docStore.put(metadataToStore);
req.onsuccess = function () {
cursor["continue"]();
};
}
if (metadata.seq) {
return onGetMetadataSeq();
}
fetchMetadataSeq();
};
}
api.type = function () {
return 'idb';
};
api._id = toPromise(function (callback) {
callback(null, api._meta.instanceId);
});
api._bulkDocs = function idb_bulkDocs(req, reqOpts, callback) {
idbBulkDocs(opts, req, reqOpts, api, idb, idbChanges, callback);
};
// First we look up the metadata in the ids database, then we fetch the
// current revision(s) from the by sequence store
api._get = function idb_get(id, opts, callback) {
var doc;
var metadata;
var err;
var txn = opts.ctx;
if (!txn) {
var txnResult = openTransactionSafely(idb,
[DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], 'readonly');
if (txnResult.error) {
return callback(txnResult.error);
}
txn = txnResult.txn;
}
function finish() {
callback(err, {doc: doc, metadata: metadata, ctx: txn});
}
txn.objectStore(DOC_STORE).get(id).onsuccess = function (e) {
metadata = decodeMetadata(e.target.result);
// we can determine the result here if:
// 1. there is no such document
// 2. the document is deleted and we don't ask about specific rev
// When we ask with opts.rev we expect the answer to be either
// doc (possibly with _deleted=true) or missing error
if (!metadata) {
err = createError(MISSING_DOC, 'missing');
return finish();
}
if (isDeleted(metadata) && !opts.rev) {
err = createError(MISSING_DOC, "deleted");
return finish();
}
var objectStore = txn.objectStore(BY_SEQ_STORE);
var rev = opts.rev || metadata.winningRev;
var key = metadata.id + '::' + rev;
objectStore.index('_doc_id_rev').get(key).onsuccess = function (e) {
doc = e.target.result;
if (doc) {
doc = decodeDoc(doc);
}
if (!doc) {
err = createError(MISSING_DOC, 'missing');
return finish();
}
finish();
};
};
};
api._getAttachment = function (docId, attachId, attachment, opts, callback) {
var txn;
if (opts.ctx) {
txn = opts.ctx;
} else {
var txnResult = openTransactionSafely(idb,
[DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], 'readonly');
if (txnResult.error) {
return callback(txnResult.error);
}
txn = txnResult.txn;
}
var digest = attachment.digest;
var type = attachment.content_type;
txn.objectStore(ATTACH_STORE).get(digest).onsuccess = function (e) {
var body = e.target.result.body;
readBlobData(body, type, opts.binary, function (blobData) {
callback(null, blobData);
});
};
};
api._info = function idb_info(callback) {
if (idb === null || !cachedDBs.has(dbName)) {
var error = new Error('db isn\'t open');
error.id = 'idbNull';
return callback(error);
}
var updateSeq;
var docCount;
var txnResult = openTransactionSafely(idb, [BY_SEQ_STORE], 'readonly');
if (txnResult.error) {
return callback(txnResult.error);
}
var txn = txnResult.txn;
var cursor = txn.objectStore(BY_SEQ_STORE).openCursor(null, 'prev');
cursor.onsuccess = function (event) {
var cursor = event.target.result;
updateSeq = cursor ? cursor.key : 0;
// count within the same txn for consistency
docCount = api._meta.docCount;
};
txn.oncomplete = function () {
callback(null, {
doc_count: docCount,
update_seq: updateSeq,
// for debugging
idb_attachment_format: (api._meta.blobSupport ? 'binary' : 'base64')
});
};
};
api._allDocs = function idb_allDocs(opts, callback) {
idbAllDocs(opts, api, idb, callback);
};
api._changes = function (opts) {
opts = clone(opts);
if (opts.continuous) {
var id = dbName + ':' + uuid();
idbChanges.addListener(dbName, id, api, opts);
idbChanges.notify(dbName);
return {
cancel: function () {
idbChanges.removeListener(dbName, id);
}
};
}
var docIds = opts.doc_ids && new pouchdbCollections.Set(opts.doc_ids);
opts.since = opts.since || 0;
var lastSeq = opts.since;
var limit = 'limit' in opts ? opts.limit : -1;
if (limit === 0) {
limit = 1; // per CouchDB _changes spec
}
var returnDocs;
if ('return_docs' in opts) {
returnDocs = opts.return_docs;
} else if ('returnDocs' in opts) {
// TODO: Remove 'returnDocs' in favor of 'return_docs' in a future release
returnDocs = opts.returnDocs;
} else {
returnDocs = true;
}
var results = [];
var numResults = 0;
var filter = filterChange(opts);
var docIdsToMetadata = new pouchdbCollections.Map();
var txn;
var bySeqStore;
var docStore;
var docIdRevIndex;
function onGetCursor(cursor) {
var doc = decodeDoc(cursor.value);
var seq = cursor.key;
if (docIds && !docIds.has(doc._id)) {
return cursor["continue"]();
}
var metadata;
function onGetMetadata() {
if (metadata.seq !== seq) {
// some other seq is later
return cursor["continue"]();
}
lastSeq = seq;
if (metadata.winningRev === doc._rev) {
return onGetWinningDoc(doc);
}
fetchWinningDoc();
}
function fetchWinningDoc() {
var docIdRev = doc._id + '::' + metadata.winningRev;
var req = docIdRevIndex.get(docIdRev);
req.onsuccess = function (e) {
onGetWinningDoc(decodeDoc(e.target.result));
};
}
function onGetWinningDoc(winningDoc) {
var change = opts.processChange(winningDoc, metadata, opts);
change.seq = metadata.seq;
var filtered = filter(change);
if (typeof filtered === 'object') {
return opts.complete(filtered);
}
if (filtered) {
numResults++;
if (returnDocs) {
results.push(change);
}
// process the attachment immediately
// for the benefit of live listeners
if (opts.attachments && opts.include_docs) {
fetchAttachmentsIfNecessary(winningDoc, opts, txn, function () {
postProcessAttachments([change], opts.binary).then(function () {
opts.onChange(change);
});
});
} else {
opts.onChange(change);
}
}
if (numResults !== limit) {
cursor["continue"]();
}
}
metadata = docIdsToMetadata.get(doc._id);
if (metadata) { // cached
return onGetMetadata();
}
// metadata not cached, have to go fetch it
docStore.get(doc._id).onsuccess = function (event) {
metadata = decodeMetadata(event.target.result);
docIdsToMetadata.set(doc._id, metadata);
onGetMetadata();
};
}
function onsuccess(event) {
var cursor = event.target.result;
if (!cursor) {
return;
}
onGetCursor(cursor);
}
function fetchChanges() {
var objectStores = [DOC_STORE, BY_SEQ_STORE];
if (opts.attachments) {
objectStores.push(ATTACH_STORE);
}
var txnResult = openTransactionSafely(idb, objectStores, 'readonly');
if (txnResult.error) {
return opts.complete(txnResult.error);
}
txn = txnResult.txn;
txn.onabort = idbError(opts.complete);
txn.oncomplete = onTxnComplete;
bySeqStore = txn.objectStore(BY_SEQ_STORE);
docStore = txn.objectStore(DOC_STORE);
docIdRevIndex = bySeqStore.index('_doc_id_rev');
var req;
if (opts.descending) {
req = bySeqStore.openCursor(null, 'prev');
} else {
req = bySeqStore.openCursor(IDBKeyRange.lowerBound(opts.since, true));
}
req.onsuccess = onsuccess;
}
fetchChanges();
function onTxnComplete() {
function finish() {
opts.complete(null, {
results: results,
last_seq: lastSeq
});
}
if (!opts.continuous && opts.attachments) {
// cannot guarantee that postProcessing was already done,
// so do it again
postProcessAttachments(results).then(finish);
} else {
finish();
}
}
};
api._close = function (callback) {
if (idb === null) {
return callback(createError(NOT_OPEN));
}
// https://developer.mozilla.org/en-US/docs/IndexedDB/IDBDatabase#close
// "Returns immediately and closes the connection in a separate thread..."
idb.close();
cachedDBs["delete"](dbName);
idb = null;
callback();
};
api._getRevisionTree = function (docId, callback) {
var txnResult = openTransactionSafely(idb, [DOC_STORE], 'readonly');
if (txnResult.error) {
return callback(txnResult.error);
}
var txn = txnResult.txn;
var req = txn.objectStore(DOC_STORE).get(docId);
req.onsuccess = function (event) {
var doc = decodeMetadata(event.target.result);
if (!doc) {
callback(createError(MISSING_DOC));
} else {
callback(null, doc.rev_tree);
}
};
};
// This function removes revisions of document docId
// which are listed in revs and sets this document
// revision to to rev_tree
api._doCompaction = function (docId, revs, callback) {
var stores = [
DOC_STORE,
BY_SEQ_STORE,
ATTACH_STORE,
ATTACH_AND_SEQ_STORE
];
var txnResult = openTransactionSafely(idb, stores, 'readwrite');
if (txnResult.error) {
return callback(txnResult.error);
}
var txn = txnResult.txn;
var docStore = txn.objectStore(DOC_STORE);
docStore.get(docId).onsuccess = function (event) {
var metadata = decodeMetadata(event.target.result);
traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
revHash, ctx, opts) {
var rev = pos + '-' + revHash;
if (revs.indexOf(rev) !== -1) {
opts.status = 'missing';
}
});
compactRevs(revs, docId, txn);
var winningRev = metadata.winningRev;
var deleted = metadata.deleted;
txn.objectStore(DOC_STORE).put(
encodeMetadata(metadata, winningRev, deleted));
};
txn.onabort = idbError(callback);
txn.oncomplete = function () {
callback();
};
};
api._getLocal = function (id, callback) {
var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readonly');
if (txnResult.error) {
return callback(txnResult.error);
}
var tx = txnResult.txn;
var req = tx.objectStore(LOCAL_STORE).get(id);
req.onerror = idbError(callback);
req.onsuccess = function (e) {
var doc = e.target.result;
if (!doc) {
callback(createError(MISSING_DOC));
} else {
delete doc['_doc_id_rev']; // for backwards compat
callback(null, doc);
}
};
};
api._putLocal = function (doc, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
delete doc._revisions; // ignore this, trust the rev
var oldRev = doc._rev;
var id = doc._id;
if (!oldRev) {
doc._rev = '0-1';
} else {
doc._rev = '0-' + (parseInt(oldRev.split('-')[1], 10) + 1);
}
var tx = opts.ctx;
var ret;
if (!tx) {
var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readwrite');
if (txnResult.error) {
return callback(txnResult.error);
}
tx = txnResult.txn;
tx.onerror = idbError(callback);
tx.oncomplete = function () {
if (ret) {
callback(null, ret);
}
};
}
var oStore = tx.objectStore(LOCAL_STORE);
var req;
if (oldRev) {
req = oStore.get(id);
req.onsuccess = function (e) {
var oldDoc = e.target.result;
if (!oldDoc || oldDoc._rev !== oldRev) {
callback(createError(REV_CONFLICT));
} else { // update
var req = oStore.put(doc);
req.onsuccess = function () {
ret = {ok: true, id: doc._id, rev: doc._rev};
if (opts.ctx) { // return immediately
callback(null, ret);
}
};
}
};
} else { // new doc
req = oStore.add(doc);
req.onerror = function (e) {
// constraint error, already exists
callback(createError(REV_CONFLICT));
e.preventDefault(); // avoid transaction abort
e.stopPropagation(); // avoid transaction onerror
};
req.onsuccess = function () {
ret = {ok: true, id: doc._id, rev: doc._rev};
if (opts.ctx) { // return immediately
callback(null, ret);
}
};
}
};
api._removeLocal = function (doc, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
var tx = opts.ctx;
if (!tx) {
var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readwrite');
if (txnResult.error) {
return callback(txnResult.error);
}
tx = txnResult.txn;
tx.oncomplete = function () {
if (ret) {
callback(null, ret);
}
};
}
var ret;
var id = doc._id;
var oStore = tx.objectStore(LOCAL_STORE);
var req = oStore.get(id);
req.onerror = idbError(callback);
req.onsuccess = function (e) {
var oldDoc = e.target.result;
if (!oldDoc || oldDoc._rev !== doc._rev) {
callback(createError(MISSING_DOC));
} else {
oStore["delete"](id);
ret = {ok: true, id: id, rev: '0-0'};
if (opts.ctx) { // return immediately
callback(null, ret);
}
}
};
};
api._destroy = function (opts, callback) {
idbChanges.removeAllListeners(dbName);
//Close open request for "dbName" database to fix ie delay.
var openReq = openReqList.get(dbName);
if (openReq && openReq.result) {
openReq.result.close();
cachedDBs["delete"](dbName);
}
var req = indexedDB.deleteDatabase(dbName);
req.onsuccess = function () {
//Remove open request from the list.
openReqList["delete"](dbName);
if (hasLocalStorage() && (dbName in localStorage)) {
delete localStorage[dbName];
}
callback(null, { 'ok': true });
};
req.onerror = idbError(callback);
};
var cached = cachedDBs.get(dbName);
if (cached) {
idb = cached.idb;
api._meta = cached.global;
process.nextTick(function () {
callback(null, api);
});
return;
}
var req;
if (opts.storage) {
req = tryStorageOption(dbName, opts.storage);
} else {
req = indexedDB.open(dbName, ADAPTER_VERSION);
}
openReqList.set(dbName, req);
req.onupgradeneeded = function (e) {
var db = e.target.result;
if (e.oldVersion < 1) {
return createSchema(db); // new db, initial schema
}
// do migrations
var txn = e.currentTarget.transaction;
// these migrations have to be done in this function, before
// control is returned to the event loop, because IndexedDB
if (e.oldVersion < 3) {
createLocalStoreSchema(db); // v2 -> v3
}
if (e.oldVersion < 4) {
addAttachAndSeqStore(db); // v3 -> v4
}
var migrations = [
addDeletedOrLocalIndex, // v1 -> v2
migrateLocalStore, // v2 -> v3
migrateAttsAndSeqs, // v3 -> v4
migrateMetadata // v4 -> v5
];
var i = e.oldVersion;
function next() {
var migration = migrations[i - 1];
i++;
if (migration) {
migration(txn, next);
}
}
next();
};
req.onsuccess = function (e) {
idb = e.target.result;
idb.onversionchange = function () {
idb.close();
cachedDBs["delete"](dbName);
};
idb.onabort = function (e) {
guardedConsole('error', 'Database has a global failure', e.target.error);
idb.close();
cachedDBs["delete"](dbName);
};
var txn = idb.transaction([
META_STORE,
DETECT_BLOB_SUPPORT_STORE,
DOC_STORE
], 'readwrite');
var req = txn.objectStore(META_STORE).get(META_STORE);
var blobSupport = null;
var docCount = null;
var instanceId = null;
req.onsuccess = function (e) {
var checkSetupComplete = function () {
if (blobSupport === null || docCount === null ||
instanceId === null) {
return;
} else {
api._meta = {
name: dbName,
instanceId: instanceId,
blobSupport: blobSupport,
docCount: docCount
};
cachedDBs.set(dbName, {
idb: idb,
global: api._meta
});
callback(null, api);
}
};
//
// fetch/store the id
//
var meta = e.target.result || {id: META_STORE};
if (dbName + '_id' in meta) {
instanceId = meta[dbName + '_id'];
checkSetupComplete();
} else {
instanceId = uuid();
meta[dbName + '_id'] = instanceId;
txn.objectStore(META_STORE).put(meta).onsuccess = function () {
checkSetupComplete();
};
}
//
// check blob support
//
if (!blobSupportPromise) {
// make sure blob support is only checked once
blobSupportPromise = checkBlobSupport(txn);
}
blobSupportPromise.then(function (val) {
blobSupport = val;
checkSetupComplete();
});
//
// count docs
//
var index = txn.objectStore(DOC_STORE).index('deletedOrLocal');
index.count(IDBKeyRange.only('0')).onsuccess = function (e) {
docCount = e.target.result;
checkSetupComplete();
};
};
};
req.onerror = function () {
var msg = 'Failed to open indexedDB, are you in private browsing mode?';
guardedConsole('error', msg);
callback(createError(IDB_ERROR, msg));
};
}
IdbPouch.valid = function () {
// Issue #2533, we finally gave up on doing bug
// detection instead of browser sniffing. Safari brought us
// to our knees.
var isSafari = typeof openDatabase !== 'undefined' &&
/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) &&
!/Chrome/.test(navigator.userAgent) &&
!/BlackBerry/.test(navigator.platform);
// some outdated implementations of IDB that appear on Samsung
// and HTC Android devices <4.4 are missing IDBKeyRange
return !isSafari && typeof indexedDB !== 'undefined' &&
typeof IDBKeyRange !== 'undefined';
};
function tryStorageOption(dbName, storage) {
try { // option only available in Firefox 26+
return indexedDB.open(dbName, {
version: ADAPTER_VERSION,
storage: storage
});
} catch(err) {
return indexedDB.open(dbName, ADAPTER_VERSION);
}
}
function IDBPouch (PouchDB) {
PouchDB.adapter('idb', IdbPouch, true);
}
//
// Parsing hex strings. Yeah.
//
// So basically we need this because of a bug in WebSQL:
// https://code.google.com/p/chromium/issues/detail?id=422690
// https://bugs.webkit.org/show_bug.cgi?id=137637
//
// UTF-8 and UTF-16 are provided as separate functions
// for meager performance improvements
//
function decodeUtf8(str) {
return decodeURIComponent(escape(str));
}
function hexToInt(charCode) {
// '0'-'9' is 48-57
// 'A'-'F' is 65-70
// SQLite will only give us uppercase hex
return charCode < 65 ? (charCode - 48) : (charCode - 55);
}
// Example:
// pragma encoding=utf8;
// select hex('A');
// returns '41'
function parseHexUtf8(str, start, end) {
var result = '';
while (start < end) {
result += String.fromCharCode(
(hexToInt(str.charCodeAt(start++)) << 4) |
hexToInt(str.charCodeAt(start++)));
}
return result;
}
// Example:
// pragma encoding=utf16;
// select hex('A');
// returns '4100'
// notice that the 00 comes after the 41 (i.e. it's swizzled)
function parseHexUtf16(str, start, end) {
var result = '';
while (start < end) {
// UTF-16, so swizzle the bytes
result += String.fromCharCode(
(hexToInt(str.charCodeAt(start + 2)) << 12) |
(hexToInt(str.charCodeAt(start + 3)) << 8) |
(hexToInt(str.charCodeAt(start)) << 4) |
hexToInt(str.charCodeAt(start + 1)));
start += 4;
}
return result;
}
function parseHexString(str, encoding) {
if (encoding === 'UTF-8') {
return decodeUtf8(parseHexUtf8(str, 0, str.length));
} else {
return parseHexUtf16(str, 0, str.length);
}
}
function quote(str) {
return "'" + str + "'";
}
var ADAPTER_VERSION$1 = 7; // used to manage migrations
// The object stores created for each database
// DOC_STORE stores the document meta data, its revision history and state
var DOC_STORE$1 = quote('document-store');
// BY_SEQ_STORE stores a particular version of a document, keyed by its
// sequence id
var BY_SEQ_STORE$1 = quote('by-sequence');
// Where we store attachments
var ATTACH_STORE$1 = quote('attach-store');
var LOCAL_STORE$1 = quote('local-store');
var META_STORE$1 = quote('metadata-store');
// where we store many-to-many relations between attachment
// digests and seqs
var ATTACH_AND_SEQ_STORE$1 = quote('attach-seq-store');
// escapeBlob and unescapeBlob are workarounds for a websql bug:
// https://code.google.com/p/chromium/issues/detail?id=422690
// https://bugs.webkit.org/show_bug.cgi?id=137637
// The goal is to never actually insert the \u0000 character
// in the database.
function escapeBlob(str) {
return str
.replace(/\u0002/g, '\u0002\u0002')
.replace(/\u0001/g, '\u0001\u0002')
.replace(/\u0000/g, '\u0001\u0001');
}
function unescapeBlob(str) {
return str
.replace(/\u0001\u0001/g, '\u0000')
.replace(/\u0001\u0002/g, '\u0001')
.replace(/\u0002\u0002/g, '\u0002');
}
function stringifyDoc(doc) {
// don't bother storing the id/rev. it uses lots of space,
// in persistent map/reduce especially
delete doc._id;
delete doc._rev;
return JSON.stringify(doc);
}
function unstringifyDoc(doc, id, rev) {
doc = JSON.parse(doc);
doc._id = id;
doc._rev = rev;
return doc;
}
// question mark groups IN queries, e.g. 3 -> '(?,?,?)'
function qMarks(num) {
var s = '(';
while (num--) {
s += '?';
if (num) {
s += ',';
}
}
return s + ')';
}
function select(selector, table, joiner, where, orderBy) {
return 'SELECT ' + selector + ' FROM ' +
(typeof table === 'string' ? table : table.join(' JOIN ')) +
(joiner ? (' ON ' + joiner) : '') +
(where ? (' WHERE ' +
(typeof where === 'string' ? where : where.join(' AND '))) : '') +
(orderBy ? (' ORDER BY ' + orderBy) : '');
}
function compactRevs$1(revs, docId, tx) {
if (!revs.length) {
return;
}
var numDone = 0;
var seqs = [];
function checkDone() {
if (++numDone === revs.length) { // done
deleteOrphans();
}
}
function deleteOrphans() {
// find orphaned attachment digests
if (!seqs.length) {
return;
}
var sql = 'SELECT DISTINCT digest AS digest FROM ' +
ATTACH_AND_SEQ_STORE$1 + ' WHERE seq IN ' + qMarks(seqs.length);
tx.executeSql(sql, seqs, function (tx, res) {
var digestsToCheck = [];
for (var i = 0; i < res.rows.length; i++) {
digestsToCheck.push(res.rows.item(i).digest);
}
if (!digestsToCheck.length) {
return;
}
var sql = 'DELETE FROM ' + ATTACH_AND_SEQ_STORE$1 +
' WHERE seq IN (' +
seqs.map(function () { return '?'; }).join(',') +
')';
tx.executeSql(sql, seqs, function (tx) {
var sql = 'SELECT digest FROM ' + ATTACH_AND_SEQ_STORE$1 +
' WHERE digest IN (' +
digestsToCheck.map(function () { return '?'; }).join(',') +
')';
tx.executeSql(sql, digestsToCheck, function (tx, res) {
var nonOrphanedDigests = new pouchdbCollections.Set();
for (var i = 0; i < res.rows.length; i++) {
nonOrphanedDigests.add(res.rows.item(i).digest);
}
digestsToCheck.forEach(function (digest) {
if (nonOrphanedDigests.has(digest)) {
return;
}
tx.executeSql(
'DELETE FROM ' + ATTACH_AND_SEQ_STORE$1 + ' WHERE digest=?',
[digest]);
tx.executeSql(
'DELETE FROM ' + ATTACH_STORE$1 + ' WHERE digest=?', [digest]);
});
});
});
});
}
// update by-seq and attach stores in parallel
revs.forEach(function (rev) {
var sql = 'SELECT seq FROM ' + BY_SEQ_STORE$1 +
' WHERE doc_id=? AND rev=?';
tx.executeSql(sql, [docId, rev], function (tx, res) {
if (!res.rows.length) { // already deleted
return checkDone();
}
var seq = res.rows.item(0).seq;
seqs.push(seq);
tx.executeSql(
'DELETE FROM ' + BY_SEQ_STORE$1 + ' WHERE seq=?', [seq], checkDone);
});
});
}
function websqlError(callback) {
return function (event) {
guardedConsole('error', 'WebSQL threw an error', event);
// event may actually be a SQLError object, so report is as such
var errorNameMatch = event && event.constructor.toString()
.match(/function ([^\(]+)/);
var errorName = (errorNameMatch && errorNameMatch[1]) || event.type;
var errorReason = event.target || event.message;
callback(createError(WSQ_ERROR, errorReason, errorName));
};
}
function getSize(opts) {
if ('size' in opts) {
// triggers immediate popup in iOS, fixes #2347
// e.g. 5000001 asks for 5 MB, 10000001 asks for 10 MB,
return opts.size * 1000000;
}
// In iOS, doesn't matter as long as it's <= 5000000.
// Except that if you request too much, our tests fail
// because of the native "do you accept?" popup.
// In Android <=4.3, this value is actually used as an
// honest-to-god ceiling for data, so we need to
// set it to a decently high number.
var isAndroid = typeof navigator !== 'undefined' &&
/Android/.test(navigator.userAgent);
return isAndroid ? 5000000 : 1; // in PhantomJS, if you use 0 it will crash
}
function websqlBulkDocs(dbOpts, req, opts, api, db, websqlChanges, callback) {
var newEdits = opts.new_edits;
var userDocs = req.docs;
// Parse the docs, give them a sequence number for the result
var docInfos = userDocs.map(function (doc) {
if (doc._id && isLocalId(doc._id)) {
return doc;
}
var newDoc = parseDoc(doc, newEdits);
return newDoc;
});
var docInfoErrors = docInfos.filter(function (docInfo) {
return docInfo.error;
});
if (docInfoErrors.length) {
return callback(docInfoErrors[0]);
}
var tx;
var results = new Array(docInfos.length);
var fetchedDocs = new pouchdbCollections.Map();
var preconditionErrored;
function complete() {
if (preconditionErrored) {
return callback(preconditionErrored);
}
websqlChanges.notify(api._name);
api._docCount = -1; // invalidate
callback(null, results);
}
function verifyAttachment(digest, callback) {
var sql = 'SELECT count(*) as cnt FROM ' + ATTACH_STORE$1 +
' WHERE digest=?';
tx.executeSql(sql, [digest], function (tx, result) {
if (result.rows.item(0).cnt === 0) {
var err = createError(MISSING_STUB,
'unknown stub attachment with digest ' +
digest);
callback(err);
} else {
callback();
}
});
}
function verifyAttachments(finish) {
var digests = [];
docInfos.forEach(function (docInfo) {
if (docInfo.data && docInfo.data._attachments) {
Object.keys(docInfo.data._attachments).forEach(function (filename) {
var att = docInfo.data._attachments[filename];
if (att.stub) {
digests.push(att.digest);
}
});
}
});
if (!digests.length) {
return finish();
}
var numDone = 0;
var err;
function checkDone() {
if (++numDone === digests.length) {
finish(err);
}
}
digests.forEach(function (digest) {
verifyAttachment(digest, function (attErr) {
if (attErr && !err) {
err = attErr;
}
checkDone();
});
});
}
function writeDoc(docInfo, winningRev, winningRevIsDeleted, newRevIsDeleted,
isUpdate, delta, resultsIdx, callback) {
function finish() {
var data = docInfo.data;
var deletedInt = newRevIsDeleted ? 1 : 0;
var id = data._id;
var rev = data._rev;
var json = stringifyDoc(data);
var sql = 'INSERT INTO ' + BY_SEQ_STORE$1 +
' (doc_id, rev, json, deleted) VALUES (?, ?, ?, ?);';
var sqlArgs = [id, rev, json, deletedInt];
// map seqs to attachment digests, which
// we will need later during compaction
function insertAttachmentMappings(seq, callback) {
var attsAdded = 0;
var attsToAdd = Object.keys(data._attachments || {});
if (!attsToAdd.length) {
return callback();
}
function checkDone() {
if (++attsAdded === attsToAdd.length) {
callback();
}
return false; // ack handling a constraint error
}
function add(att) {
var sql = 'INSERT INTO ' + ATTACH_AND_SEQ_STORE$1 +
' (digest, seq) VALUES (?,?)';
var sqlArgs = [data._attachments[att].digest, seq];
tx.executeSql(sql, sqlArgs, checkDone, checkDone);
// second callback is for a constaint error, which we ignore
// because this docid/rev has already been associated with
// the digest (e.g. when new_edits == false)
}
for (var i = 0; i < attsToAdd.length; i++) {
add(attsToAdd[i]); // do in parallel
}
}
tx.executeSql(sql, sqlArgs, function (tx, result) {
var seq = result.insertId;
insertAttachmentMappings(seq, function () {
dataWritten(tx, seq);
});
}, function () {
// constraint error, recover by updating instead (see #1638)
var fetchSql = select('seq', BY_SEQ_STORE$1, null,
'doc_id=? AND rev=?');
tx.executeSql(fetchSql, [id, rev], function (tx, res) {
var seq = res.rows.item(0).seq;
var sql = 'UPDATE ' + BY_SEQ_STORE$1 +
' SET json=?, deleted=? WHERE doc_id=? AND rev=?;';
var sqlArgs = [json, deletedInt, id, rev];
tx.executeSql(sql, sqlArgs, function (tx) {
insertAttachmentMappings(seq, function () {
dataWritten(tx, seq);
});
});
});
return false; // ack that we've handled the error
});
}
function collectResults(attachmentErr) {
if (!err) {
if (attachmentErr) {
err = attachmentErr;
callback(err);
} else if (recv === attachments.length) {
finish();
}
}
}
var err = null;
var recv = 0;
docInfo.data._id = docInfo.metadata.id;
docInfo.data._rev = docInfo.metadata.rev;
var attachments = Object.keys(docInfo.data._attachments || {});
if (newRevIsDeleted) {
docInfo.data._deleted = true;
}
function attachmentSaved(err) {
recv++;
collectResults(err);
}
attachments.forEach(function (key) {
var att = docInfo.data._attachments[key];
if (!att.stub) {
var data = att.data;
delete att.data;
att.revpos = parseInt(winningRev, 10);
var digest = att.digest;
saveAttachment(digest, data, attachmentSaved);
} else {
recv++;
collectResults();
}
});
if (!attachments.length) {
finish();
}
function dataWritten(tx, seq) {
var id = docInfo.metadata.id;
var revsToCompact = docInfo.stemmedRevs || [];
if (isUpdate && api.auto_compaction) {
revsToCompact = compactTree(docInfo.metadata).concat(revsToCompact);
}
if (revsToCompact.length) {
compactRevs$1(revsToCompact, id, tx);
}
docInfo.metadata.seq = seq;
delete docInfo.metadata.rev;
var sql = isUpdate ?
'UPDATE ' + DOC_STORE$1 +
' SET json=?, max_seq=?, winningseq=' +
'(SELECT seq FROM ' + BY_SEQ_STORE$1 +
' WHERE doc_id=' + DOC_STORE$1 + '.id AND rev=?) WHERE id=?'
: 'INSERT INTO ' + DOC_STORE$1 +
' (id, winningseq, max_seq, json) VALUES (?,?,?,?);';
var metadataStr = safeJsonStringify(docInfo.metadata);
var params = isUpdate ?
[metadataStr, seq, winningRev, id] :
[id, seq, seq, metadataStr];
tx.executeSql(sql, params, function () {
results[resultsIdx] = {
ok: true,
id: docInfo.metadata.id,
rev: winningRev
};
fetchedDocs.set(id, docInfo.metadata);
callback();
});
}
}
function websqlProcessDocs() {
processDocs(dbOpts.revs_limit, docInfos, api, fetchedDocs, tx,
results, writeDoc, opts);
}
function fetchExistingDocs(callback) {
if (!docInfos.length) {
return callback();
}
var numFetched = 0;
function checkDone() {
if (++numFetched === docInfos.length) {
callback();
}
}
docInfos.forEach(function (docInfo) {
if (docInfo._id && isLocalId(docInfo._id)) {
return checkDone(); // skip local docs
}
var id = docInfo.metadata.id;
tx.executeSql('SELECT json FROM ' + DOC_STORE$1 +
' WHERE id = ?', [id], function (tx, result) {
if (result.rows.length) {
var metadata = safeJsonParse(result.rows.item(0).json);
fetchedDocs.set(id, metadata);
}
checkDone();
});
});
}
function saveAttachment(digest, data, callback) {
var sql = 'SELECT digest FROM ' + ATTACH_STORE$1 + ' WHERE digest=?';
tx.executeSql(sql, [digest], function (tx, result) {
if (result.rows.length) { // attachment already exists
return callback();
}
// we could just insert before selecting and catch the error,
// but my hunch is that it's cheaper not to serialize the blob
// from JS to C if we don't have to (TODO: confirm this)
sql = 'INSERT INTO ' + ATTACH_STORE$1 +
' (digest, body, escaped) VALUES (?,?,1)';
tx.executeSql(sql, [digest, escapeBlob(data)], function () {
callback();
}, function () {
// ignore constaint errors, means it already exists
callback();
return false; // ack we handled the error
});
});
}
preprocessAttachments(docInfos, 'binary', function (err) {
if (err) {
return callback(err);
}
db.transaction(function (txn) {
tx = txn;
verifyAttachments(function (err) {
if (err) {
preconditionErrored = err;
} else {
fetchExistingDocs(websqlProcessDocs);
}
});
}, websqlError(callback), complete);
});
}
var cachedDatabases = new pouchdbCollections.Map();
// openDatabase passed in through opts (e.g. for node-websql)
function openDatabaseWithOpts(opts) {
return opts.websql(opts.name, opts.version, opts.description, opts.size);
}
function openDBSafely(opts) {
try {
return {
db: openDatabaseWithOpts(opts)
};
} catch (err) {
return {
error: err
};
}
}
function openDB(opts) {
var cachedResult = cachedDatabases.get(opts.name);
if (!cachedResult) {
cachedResult = openDBSafely(opts);
cachedDatabases.set(opts.name, cachedResult);
if (cachedResult.db) {
cachedResult.db._sqlitePlugin = typeof sqlitePlugin !== 'undefined';
}
}
return cachedResult;
}
var websqlChanges = new Changes$1();
function fetchAttachmentsIfNecessary$1(doc, opts, api, txn, cb) {
var attachments = Object.keys(doc._attachments || {});
if (!attachments.length) {
return cb && cb();
}
var numDone = 0;
function checkDone() {
if (++numDone === attachments.length && cb) {
cb();
}
}
function fetchAttachment(doc, att) {
var attObj = doc._attachments[att];
var attOpts = {binary: opts.binary, ctx: txn};
api._getAttachment(doc._id, att, attObj, attOpts, function (_, data) {
doc._attachments[att] = jsExtend.extend(
pick(attObj, ['digest', 'content_type']),
{ data: data }
);
checkDone();
});
}
attachments.forEach(function (att) {
if (opts.attachments && opts.include_docs) {
fetchAttachment(doc, att);
} else {
doc._attachments[att].stub = true;
checkDone();
}
});
}
var POUCH_VERSION = 1;
// these indexes cover the ground for most allDocs queries
var BY_SEQ_STORE_DELETED_INDEX_SQL =
'CREATE INDEX IF NOT EXISTS \'by-seq-deleted-idx\' ON ' +
BY_SEQ_STORE$1 + ' (seq, deleted)';
var BY_SEQ_STORE_DOC_ID_REV_INDEX_SQL =
'CREATE UNIQUE INDEX IF NOT EXISTS \'by-seq-doc-id-rev\' ON ' +
BY_SEQ_STORE$1 + ' (doc_id, rev)';
var DOC_STORE_WINNINGSEQ_INDEX_SQL =
'CREATE INDEX IF NOT EXISTS \'doc-winningseq-idx\' ON ' +
DOC_STORE$1 + ' (winningseq)';
var ATTACH_AND_SEQ_STORE_SEQ_INDEX_SQL =
'CREATE INDEX IF NOT EXISTS \'attach-seq-seq-idx\' ON ' +
ATTACH_AND_SEQ_STORE$1 + ' (seq)';
var ATTACH_AND_SEQ_STORE_ATTACH_INDEX_SQL =
'CREATE UNIQUE INDEX IF NOT EXISTS \'attach-seq-digest-idx\' ON ' +
ATTACH_AND_SEQ_STORE$1 + ' (digest, seq)';
var DOC_STORE_AND_BY_SEQ_JOINER = BY_SEQ_STORE$1 +
'.seq = ' + DOC_STORE$1 + '.winningseq';
var SELECT_DOCS = BY_SEQ_STORE$1 + '.seq AS seq, ' +
BY_SEQ_STORE$1 + '.deleted AS deleted, ' +
BY_SEQ_STORE$1 + '.json AS data, ' +
BY_SEQ_STORE$1 + '.rev AS rev, ' +
DOC_STORE$1 + '.json AS metadata';
function WebSqlPouch$1(opts, callback) {
var api = this;
var instanceId = null;
var size = getSize(opts);
var idRequests = [];
var encoding;
api._docCount = -1; // cache sqlite count(*) for performance
api._name = opts.name;
// extend the options here, because sqlite plugin has a ton of options
// and they are constantly changing, so it's more prudent to allow anything
var websqlOpts = jsExtend.extend({}, opts, {
version: POUCH_VERSION,
description: opts.name,
size: size
});
var openDBResult = openDB(websqlOpts);
if (openDBResult.error) {
return websqlError(callback)(openDBResult.error);
}
var db = openDBResult.db;
if (typeof db.readTransaction !== 'function') {
// doesn't exist in sqlite plugin
db.readTransaction = db.transaction;
}
function dbCreated() {
// note the db name in case the browser upgrades to idb
if (hasLocalStorage()) {
window.localStorage['_pouch__websqldb_' + api._name] = true;
}
callback(null, api);
}
// In this migration, we added the 'deleted' and 'local' columns to the
// by-seq and doc store tables.
// To preserve existing user data, we re-process all the existing JSON
// and add these values.
// Called migration2 because it corresponds to adapter version (db_version) #2
function runMigration2(tx, callback) {
// index used for the join in the allDocs query
tx.executeSql(DOC_STORE_WINNINGSEQ_INDEX_SQL);
tx.executeSql('ALTER TABLE ' + BY_SEQ_STORE$1 +
' ADD COLUMN deleted TINYINT(1) DEFAULT 0', [], function () {
tx.executeSql(BY_SEQ_STORE_DELETED_INDEX_SQL);
tx.executeSql('ALTER TABLE ' + DOC_STORE$1 +
' ADD COLUMN local TINYINT(1) DEFAULT 0', [], function () {
tx.executeSql('CREATE INDEX IF NOT EXISTS \'doc-store-local-idx\' ON ' +
DOC_STORE$1 + ' (local, id)');
var sql = 'SELECT ' + DOC_STORE$1 + '.winningseq AS seq, ' + DOC_STORE$1 +
'.json AS metadata FROM ' + BY_SEQ_STORE$1 + ' JOIN ' + DOC_STORE$1 +
' ON ' + BY_SEQ_STORE$1 + '.seq = ' + DOC_STORE$1 + '.winningseq';
tx.executeSql(sql, [], function (tx, result) {
var deleted = [];
var local = [];
for (var i = 0; i < result.rows.length; i++) {
var item = result.rows.item(i);
var seq = item.seq;
var metadata = JSON.parse(item.metadata);
if (isDeleted(metadata)) {
deleted.push(seq);
}
if (isLocalId(metadata.id)) {
local.push(metadata.id);
}
}
tx.executeSql('UPDATE ' + DOC_STORE$1 + 'SET local = 1 WHERE id IN ' +
qMarks(local.length), local, function () {
tx.executeSql('UPDATE ' + BY_SEQ_STORE$1 +
' SET deleted = 1 WHERE seq IN ' +
qMarks(deleted.length), deleted, callback);
});
});
});
});
}
// in this migration, we make all the local docs unversioned
function runMigration3(tx, callback) {
var local = 'CREATE TABLE IF NOT EXISTS ' + LOCAL_STORE$1 +
' (id UNIQUE, rev, json)';
tx.executeSql(local, [], function () {
var sql = 'SELECT ' + DOC_STORE$1 + '.id AS id, ' +
BY_SEQ_STORE$1 + '.json AS data ' +
'FROM ' + BY_SEQ_STORE$1 + ' JOIN ' +
DOC_STORE$1 + ' ON ' + BY_SEQ_STORE$1 + '.seq = ' +
DOC_STORE$1 + '.winningseq WHERE local = 1';
tx.executeSql(sql, [], function (tx, res) {
var rows = [];
for (var i = 0; i < res.rows.length; i++) {
rows.push(res.rows.item(i));
}
function doNext() {
if (!rows.length) {
return callback(tx);
}
var row = rows.shift();
var rev = JSON.parse(row.data)._rev;
tx.executeSql('INSERT INTO ' + LOCAL_STORE$1 +
' (id, rev, json) VALUES (?,?,?)',
[row.id, rev, row.data], function (tx) {
tx.executeSql('DELETE FROM ' + DOC_STORE$1 + ' WHERE id=?',
[row.id], function (tx) {
tx.executeSql('DELETE FROM ' + BY_SEQ_STORE$1 + ' WHERE seq=?',
[row.seq], function () {
doNext();
});
});
});
}
doNext();
});
});
}
// in this migration, we remove doc_id_rev and just use rev
function runMigration4(tx, callback) {
function updateRows(rows) {
function doNext() {
if (!rows.length) {
return callback(tx);
}
var row = rows.shift();
var doc_id_rev = parseHexString(row.hex, encoding);
var idx = doc_id_rev.lastIndexOf('::');
var doc_id = doc_id_rev.substring(0, idx);
var rev = doc_id_rev.substring(idx + 2);
var sql = 'UPDATE ' + BY_SEQ_STORE$1 +
' SET doc_id=?, rev=? WHERE doc_id_rev=?';
tx.executeSql(sql, [doc_id, rev, doc_id_rev], function () {
doNext();
});
}
doNext();
}
var sql = 'ALTER TABLE ' + BY_SEQ_STORE$1 + ' ADD COLUMN doc_id';
tx.executeSql(sql, [], function (tx) {
var sql = 'ALTER TABLE ' + BY_SEQ_STORE$1 + ' ADD COLUMN rev';
tx.executeSql(sql, [], function (tx) {
tx.executeSql(BY_SEQ_STORE_DOC_ID_REV_INDEX_SQL, [], function (tx) {
var sql = 'SELECT hex(doc_id_rev) as hex FROM ' + BY_SEQ_STORE$1;
tx.executeSql(sql, [], function (tx, res) {
var rows = [];
for (var i = 0; i < res.rows.length; i++) {
rows.push(res.rows.item(i));
}
updateRows(rows);
});
});
});
});
}
// in this migration, we add the attach_and_seq table
// for issue #2818
function runMigration5(tx, callback) {
function migrateAttsAndSeqs(tx) {
// need to actually populate the table. this is the expensive part,
// so as an optimization, check first that this database even
// contains attachments
var sql = 'SELECT COUNT(*) AS cnt FROM ' + ATTACH_STORE$1;
tx.executeSql(sql, [], function (tx, res) {
var count = res.rows.item(0).cnt;
if (!count) {
return callback(tx);
}
var offset = 0;
var pageSize = 10;
function nextPage() {
var sql = select(
SELECT_DOCS + ', ' + DOC_STORE$1 + '.id AS id',
[DOC_STORE$1, BY_SEQ_STORE$1],
DOC_STORE_AND_BY_SEQ_JOINER,
null,
DOC_STORE$1 + '.id '
);
sql += ' LIMIT ' + pageSize + ' OFFSET ' + offset;
offset += pageSize;
tx.executeSql(sql, [], function (tx, res) {
if (!res.rows.length) {
return callback(tx);
}
var digestSeqs = {};
function addDigestSeq(digest, seq) {
// uniq digest/seq pairs, just in case there are dups
var seqs = digestSeqs[digest] = (digestSeqs[digest] || []);
if (seqs.indexOf(seq) === -1) {
seqs.push(seq);
}
}
for (var i = 0; i < res.rows.length; i++) {
var row = res.rows.item(i);
var doc = unstringifyDoc(row.data, row.id, row.rev);
var atts = Object.keys(doc._attachments || {});
for (var j = 0; j < atts.length; j++) {
var att = doc._attachments[atts[j]];
addDigestSeq(att.digest, row.seq);
}
}
var digestSeqPairs = [];
Object.keys(digestSeqs).forEach(function (digest) {
var seqs = digestSeqs[digest];
seqs.forEach(function (seq) {
digestSeqPairs.push([digest, seq]);
});
});
if (!digestSeqPairs.length) {
return nextPage();
}
var numDone = 0;
digestSeqPairs.forEach(function (pair) {
var sql = 'INSERT INTO ' + ATTACH_AND_SEQ_STORE$1 +
' (digest, seq) VALUES (?,?)';
tx.executeSql(sql, pair, function () {
if (++numDone === digestSeqPairs.length) {
nextPage();
}
});
});
});
}
nextPage();
});
}
var attachAndRev = 'CREATE TABLE IF NOT EXISTS ' +
ATTACH_AND_SEQ_STORE$1 + ' (digest, seq INTEGER)';
tx.executeSql(attachAndRev, [], function (tx) {
tx.executeSql(
ATTACH_AND_SEQ_STORE_ATTACH_INDEX_SQL, [], function (tx) {
tx.executeSql(
ATTACH_AND_SEQ_STORE_SEQ_INDEX_SQL, [],
migrateAttsAndSeqs);
});
});
}
// in this migration, we use escapeBlob() and unescapeBlob()
// instead of reading out the binary as HEX, which is slow
function runMigration6(tx, callback) {
var sql = 'ALTER TABLE ' + ATTACH_STORE$1 +
' ADD COLUMN escaped TINYINT(1) DEFAULT 0';
tx.executeSql(sql, [], callback);
}
// issue #3136, in this migration we need a "latest seq" as well
// as the "winning seq" in the doc store
function runMigration7(tx, callback) {
var sql = 'ALTER TABLE ' + DOC_STORE$1 +
' ADD COLUMN max_seq INTEGER';
tx.executeSql(sql, [], function (tx) {
var sql = 'UPDATE ' + DOC_STORE$1 + ' SET max_seq=(SELECT MAX(seq) FROM ' +
BY_SEQ_STORE$1 + ' WHERE doc_id=id)';
tx.executeSql(sql, [], function (tx) {
// add unique index after filling, else we'll get a constraint
// error when we do the ALTER TABLE
var sql =
'CREATE UNIQUE INDEX IF NOT EXISTS \'doc-max-seq-idx\' ON ' +
DOC_STORE$1 + ' (max_seq)';
tx.executeSql(sql, [], callback);
});
});
}
function checkEncoding(tx, cb) {
// UTF-8 on chrome/android, UTF-16 on safari < 7.1
tx.executeSql('SELECT HEX("a") AS hex', [], function (tx, res) {
var hex = res.rows.item(0).hex;
encoding = hex.length === 2 ? 'UTF-8' : 'UTF-16';
cb();
}
);
}
function onGetInstanceId() {
while (idRequests.length > 0) {
var idCallback = idRequests.pop();
idCallback(null, instanceId);
}
}
function onGetVersion(tx, dbVersion) {
if (dbVersion === 0) {
// initial schema
var meta = 'CREATE TABLE IF NOT EXISTS ' + META_STORE$1 +
' (dbid, db_version INTEGER)';
var attach = 'CREATE TABLE IF NOT EXISTS ' + ATTACH_STORE$1 +
' (digest UNIQUE, escaped TINYINT(1), body BLOB)';
var attachAndRev = 'CREATE TABLE IF NOT EXISTS ' +
ATTACH_AND_SEQ_STORE$1 + ' (digest, seq INTEGER)';
// TODO: migrate winningseq to INTEGER
var doc = 'CREATE TABLE IF NOT EXISTS ' + DOC_STORE$1 +
' (id unique, json, winningseq, max_seq INTEGER UNIQUE)';
var seq = 'CREATE TABLE IF NOT EXISTS ' + BY_SEQ_STORE$1 +
' (seq INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ' +
'json, deleted TINYINT(1), doc_id, rev)';
var local = 'CREATE TABLE IF NOT EXISTS ' + LOCAL_STORE$1 +
' (id UNIQUE, rev, json)';
// creates
tx.executeSql(attach);
tx.executeSql(local);
tx.executeSql(attachAndRev, [], function () {
tx.executeSql(ATTACH_AND_SEQ_STORE_SEQ_INDEX_SQL);
tx.executeSql(ATTACH_AND_SEQ_STORE_ATTACH_INDEX_SQL);
});
tx.executeSql(doc, [], function () {
tx.executeSql(DOC_STORE_WINNINGSEQ_INDEX_SQL);
tx.executeSql(seq, [], function () {
tx.executeSql(BY_SEQ_STORE_DELETED_INDEX_SQL);
tx.executeSql(BY_SEQ_STORE_DOC_ID_REV_INDEX_SQL);
tx.executeSql(meta, [], function () {
// mark the db version, and new dbid
var initSeq = 'INSERT INTO ' + META_STORE$1 +
' (db_version, dbid) VALUES (?,?)';
instanceId = uuid();
var initSeqArgs = [ADAPTER_VERSION$1, instanceId];
tx.executeSql(initSeq, initSeqArgs, function () {
onGetInstanceId();
});
});
});
});
} else { // version > 0
var setupDone = function () {
var migrated = dbVersion < ADAPTER_VERSION$1;
if (migrated) {
// update the db version within this transaction
tx.executeSql('UPDATE ' + META_STORE$1 + ' SET db_version = ' +
ADAPTER_VERSION$1);
}
// notify db.id() callers
var sql = 'SELECT dbid FROM ' + META_STORE$1;
tx.executeSql(sql, [], function (tx, result) {
instanceId = result.rows.item(0).dbid;
onGetInstanceId();
});
};
// would love to use promises here, but then websql
// ends the transaction early
var tasks = [
runMigration2,
runMigration3,
runMigration4,
runMigration5,
runMigration6,
runMigration7,
setupDone
];
// run each migration sequentially
var i = dbVersion;
var nextMigration = function (tx) {
tasks[i - 1](tx, nextMigration);
i++;
};
nextMigration(tx);
}
}
function setup() {
db.transaction(function (tx) {
// first check the encoding
checkEncoding(tx, function () {
// then get the version
fetchVersion(tx);
});
}, websqlError(callback), dbCreated);
}
function fetchVersion(tx) {
var sql = 'SELECT sql FROM sqlite_master WHERE tbl_name = ' + META_STORE$1;
tx.executeSql(sql, [], function (tx, result) {
if (!result.rows.length) {
// database hasn't even been created yet (version 0)
onGetVersion(tx, 0);
} else if (!/db_version/.test(result.rows.item(0).sql)) {
// table was created, but without the new db_version column,
// so add it.
tx.executeSql('ALTER TABLE ' + META_STORE$1 +
' ADD COLUMN db_version INTEGER', [], function () {
// before version 2, this column didn't even exist
onGetVersion(tx, 1);
});
} else { // column exists, we can safely get it
tx.executeSql('SELECT db_version FROM ' + META_STORE$1,
[], function (tx, result) {
var dbVersion = result.rows.item(0).db_version;
onGetVersion(tx, dbVersion);
});
}
});
}
setup();
api.type = function () {
return 'websql';
};
api._id = toPromise(function (callback) {
callback(null, instanceId);
});
api._info = function (callback) {
db.readTransaction(function (tx) {
countDocs(tx, function (docCount) {
var sql = 'SELECT MAX(seq) AS seq FROM ' + BY_SEQ_STORE$1;
tx.executeSql(sql, [], function (tx, res) {
var updateSeq = res.rows.item(0).seq || 0;
callback(null, {
doc_count: docCount,
update_seq: updateSeq,
// for debugging
sqlite_plugin: db._sqlitePlugin,
websql_encoding: encoding
});
});
});
}, websqlError(callback));
};
api._bulkDocs = function (req, reqOpts, callback) {
websqlBulkDocs(opts, req, reqOpts, api, db, websqlChanges, callback);
};
api._get = function (id, opts, callback) {
var doc;
var metadata;
var err;
var tx = opts.ctx;
if (!tx) {
return db.readTransaction(function (txn) {
api._get(id, jsExtend.extend({ctx: txn}, opts), callback);
});
}
function finish() {
callback(err, {doc: doc, metadata: metadata, ctx: tx});
}
var sql;
var sqlArgs;
if (opts.rev) {
sql = select(
SELECT_DOCS,
[DOC_STORE$1, BY_SEQ_STORE$1],
DOC_STORE$1 + '.id=' + BY_SEQ_STORE$1 + '.doc_id',
[BY_SEQ_STORE$1 + '.doc_id=?', BY_SEQ_STORE$1 + '.rev=?']);
sqlArgs = [id, opts.rev];
} else {
sql = select(
SELECT_DOCS,
[DOC_STORE$1, BY_SEQ_STORE$1],
DOC_STORE_AND_BY_SEQ_JOINER,
DOC_STORE$1 + '.id=?');
sqlArgs = [id];
}
tx.executeSql(sql, sqlArgs, function (a, results) {
if (!results.rows.length) {
err = createError(MISSING_DOC, 'missing');
return finish();
}
var item = results.rows.item(0);
metadata = safeJsonParse(item.metadata);
if (item.deleted && !opts.rev) {
err = createError(MISSING_DOC, 'deleted');
return finish();
}
doc = unstringifyDoc(item.data, metadata.id, item.rev);
finish();
});
};
function countDocs(tx, callback) {
if (api._docCount !== -1) {
return callback(api._docCount);
}
// count the total rows
var sql = select(
'COUNT(' + DOC_STORE$1 + '.id) AS \'num\'',
[DOC_STORE$1, BY_SEQ_STORE$1],
DOC_STORE_AND_BY_SEQ_JOINER,
BY_SEQ_STORE$1 + '.deleted=0');
tx.executeSql(sql, [], function (tx, result) {
api._docCount = result.rows.item(0).num;
callback(api._docCount);
});
}
api._allDocs = function (opts, callback) {
var results = [];
var totalRows;
var start = 'startkey' in opts ? opts.startkey : false;
var end = 'endkey' in opts ? opts.endkey : false;
var key = 'key' in opts ? opts.key : false;
var descending = 'descending' in opts ? opts.descending : false;
var limit = 'limit' in opts ? opts.limit : -1;
var offset = 'skip' in opts ? opts.skip : 0;
var inclusiveEnd = opts.inclusive_end !== false;
var sqlArgs = [];
var criteria = [];
if (key !== false) {
criteria.push(DOC_STORE$1 + '.id = ?');
sqlArgs.push(key);
} else if (start !== false || end !== false) {
if (start !== false) {
criteria.push(DOC_STORE$1 + '.id ' + (descending ? '<=' : '>=') + ' ?');
sqlArgs.push(start);
}
if (end !== false) {
var comparator = descending ? '>' : '<';
if (inclusiveEnd) {
comparator += '=';
}
criteria.push(DOC_STORE$1 + '.id ' + comparator + ' ?');
sqlArgs.push(end);
}
if (key !== false) {
criteria.push(DOC_STORE$1 + '.id = ?');
sqlArgs.push(key);
}
}
if (opts.deleted !== 'ok') {
// report deleted if keys are specified
criteria.push(BY_SEQ_STORE$1 + '.deleted = 0');
}
db.readTransaction(function (tx) {
// first count up the total rows
countDocs(tx, function (count) {
totalRows = count;
if (limit === 0) {
return;
}
// then actually fetch the documents
var sql = select(
SELECT_DOCS,
[DOC_STORE$1, BY_SEQ_STORE$1],
DOC_STORE_AND_BY_SEQ_JOINER,
criteria,
DOC_STORE$1 + '.id ' + (descending ? 'DESC' : 'ASC')
);
sql += ' LIMIT ' + limit + ' OFFSET ' + offset;
tx.executeSql(sql, sqlArgs, function (tx, result) {
for (var i = 0, l = result.rows.length; i < l; i++) {
var item = result.rows.item(i);
var metadata = safeJsonParse(item.metadata);
var id = metadata.id;
var data = unstringifyDoc(item.data, id, item.rev);
var winningRev = data._rev;
var doc = {
id: id,
key: id,
value: {rev: winningRev}
};
if (opts.include_docs) {
doc.doc = data;
doc.doc._rev = winningRev;
if (opts.conflicts) {
doc.doc._conflicts = collectConflicts(metadata);
}
fetchAttachmentsIfNecessary$1(doc.doc, opts, api, tx);
}
if (item.deleted) {
if (opts.deleted === 'ok') {
doc.value.deleted = true;
doc.doc = null;
} else {
continue;
}
}
results.push(doc);
}
});
});
}, websqlError(callback), function () {
callback(null, {
total_rows: totalRows,
offset: opts.skip,
rows: results
});
});
};
api._changes = function (opts) {
opts = clone(opts);
if (opts.continuous) {
var id = api._name + ':' + uuid();
websqlChanges.addListener(api._name, id, api, opts);
websqlChanges.notify(api._name);
return {
cancel: function () {
websqlChanges.removeListener(api._name, id);
}
};
}
var descending = opts.descending;
// Ignore the `since` parameter when `descending` is true
opts.since = opts.since && !descending ? opts.since : 0;
var limit = 'limit' in opts ? opts.limit : -1;
if (limit === 0) {
limit = 1; // per CouchDB _changes spec
}
var returnDocs;
if ('return_docs' in opts) {
returnDocs = opts.return_docs;
} else if ('returnDocs' in opts) {
// TODO: Remove 'returnDocs' in favor of 'return_docs' in a future release
returnDocs = opts.returnDocs;
} else {
returnDocs = true;
}
var results = [];
var numResults = 0;
function fetchChanges() {
var selectStmt =
DOC_STORE$1 + '.json AS metadata, ' +
DOC_STORE$1 + '.max_seq AS maxSeq, ' +
BY_SEQ_STORE$1 + '.json AS winningDoc, ' +
BY_SEQ_STORE$1 + '.rev AS winningRev ';
var from = DOC_STORE$1 + ' JOIN ' + BY_SEQ_STORE$1;
var joiner = DOC_STORE$1 + '.id=' + BY_SEQ_STORE$1 + '.doc_id' +
' AND ' + DOC_STORE$1 + '.winningseq=' + BY_SEQ_STORE$1 + '.seq';
var criteria = ['maxSeq > ?'];
var sqlArgs = [opts.since];
if (opts.doc_ids) {
criteria.push(DOC_STORE$1 + '.id IN ' + qMarks(opts.doc_ids.length));
sqlArgs = sqlArgs.concat(opts.doc_ids);
}
var orderBy = 'maxSeq ' + (descending ? 'DESC' : 'ASC');
var sql = select(selectStmt, from, joiner, criteria, orderBy);
var filter = filterChange(opts);
if (!opts.view && !opts.filter) {
// we can just limit in the query
sql += ' LIMIT ' + limit;
}
var lastSeq = opts.since || 0;
db.readTransaction(function (tx) {
tx.executeSql(sql, sqlArgs, function (tx, result) {
function reportChange(change) {
return function () {
opts.onChange(change);
};
}
for (var i = 0, l = result.rows.length; i < l; i++) {
var item = result.rows.item(i);
var metadata = safeJsonParse(item.metadata);
lastSeq = item.maxSeq;
var doc = unstringifyDoc(item.winningDoc, metadata.id,
item.winningRev);
var change = opts.processChange(doc, metadata, opts);
change.seq = item.maxSeq;
var filtered = filter(change);
if (typeof filtered === 'object') {
return opts.complete(filtered);
}
if (filtered) {
numResults++;
if (returnDocs) {
results.push(change);
}
// process the attachment immediately
// for the benefit of live listeners
if (opts.attachments && opts.include_docs) {
fetchAttachmentsIfNecessary$1(doc, opts, api, tx,
reportChange(change));
} else {
reportChange(change)();
}
}
if (numResults === limit) {
break;
}
}
});
}, websqlError(opts.complete), function () {
if (!opts.continuous) {
opts.complete(null, {
results: results,
last_seq: lastSeq
});
}
});
}
fetchChanges();
};
api._close = function (callback) {
//WebSQL databases do not need to be closed
callback();
};
api._getAttachment = function (docId, attachId, attachment, opts, callback) {
var res;
var tx = opts.ctx;
var digest = attachment.digest;
var type = attachment.content_type;
var sql = 'SELECT escaped, ' +
'CASE WHEN escaped = 1 THEN body ELSE HEX(body) END AS body FROM ' +
ATTACH_STORE$1 + ' WHERE digest=?';
tx.executeSql(sql, [digest], function (tx, result) {
// websql has a bug where \u0000 causes early truncation in strings
// and blobs. to work around this, we used to use the hex() function,
// but that's not performant. after migration 6, we remove \u0000
// and add it back in afterwards
var item = result.rows.item(0);
var data = item.escaped ? unescapeBlob(item.body) :
parseHexString(item.body, encoding);
if (opts.binary) {
res = binStringToBluffer(data, type);
} else {
res = btoa$1(data);
}
callback(null, res);
});
};
api._getRevisionTree = function (docId, callback) {
db.readTransaction(function (tx) {
var sql = 'SELECT json AS metadata FROM ' + DOC_STORE$1 + ' WHERE id = ?';
tx.executeSql(sql, [docId], function (tx, result) {
if (!result.rows.length) {
callback(createError(MISSING_DOC));
} else {
var data = safeJsonParse(result.rows.item(0).metadata);
callback(null, data.rev_tree);
}
});
});
};
api._doCompaction = function (docId, revs, callback) {
if (!revs.length) {
return callback();
}
db.transaction(function (tx) {
// update doc store
var sql = 'SELECT json AS metadata FROM ' + DOC_STORE$1 + ' WHERE id = ?';
tx.executeSql(sql, [docId], function (tx, result) {
var metadata = safeJsonParse(result.rows.item(0).metadata);
traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
revHash, ctx, opts) {
var rev = pos + '-' + revHash;
if (revs.indexOf(rev) !== -1) {
opts.status = 'missing';
}
});
var sql = 'UPDATE ' + DOC_STORE$1 + ' SET json = ? WHERE id = ?';
tx.executeSql(sql, [safeJsonStringify(metadata), docId]);
});
compactRevs$1(revs, docId, tx);
}, websqlError(callback), function () {
callback();
});
};
api._getLocal = function (id, callback) {
db.readTransaction(function (tx) {
var sql = 'SELECT json, rev FROM ' + LOCAL_STORE$1 + ' WHERE id=?';
tx.executeSql(sql, [id], function (tx, res) {
if (res.rows.length) {
var item = res.rows.item(0);
var doc = unstringifyDoc(item.json, id, item.rev);
callback(null, doc);
} else {
callback(createError(MISSING_DOC));
}
});
});
};
api._putLocal = function (doc, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
delete doc._revisions; // ignore this, trust the rev
var oldRev = doc._rev;
var id = doc._id;
var newRev;
if (!oldRev) {
newRev = doc._rev = '0-1';
} else {
newRev = doc._rev = '0-' + (parseInt(oldRev.split('-')[1], 10) + 1);
}
var json = stringifyDoc(doc);
var ret;
function putLocal(tx) {
var sql;
var values;
if (oldRev) {
sql = 'UPDATE ' + LOCAL_STORE$1 + ' SET rev=?, json=? ' +
'WHERE id=? AND rev=?';
values = [newRev, json, id, oldRev];
} else {
sql = 'INSERT INTO ' + LOCAL_STORE$1 + ' (id, rev, json) VALUES (?,?,?)';
values = [id, newRev, json];
}
tx.executeSql(sql, values, function (tx, res) {
if (res.rowsAffected) {
ret = {ok: true, id: id, rev: newRev};
if (opts.ctx) { // return immediately
callback(null, ret);
}
} else {
callback(createError(REV_CONFLICT));
}
}, function () {
callback(createError(REV_CONFLICT));
return false; // ack that we handled the error
});
}
if (opts.ctx) {
putLocal(opts.ctx);
} else {
db.transaction(putLocal, websqlError(callback), function () {
if (ret) {
callback(null, ret);
}
});
}
};
api._removeLocal = function (doc, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
var ret;
function removeLocal(tx) {
var sql = 'DELETE FROM ' + LOCAL_STORE$1 + ' WHERE id=? AND rev=?';
var params = [doc._id, doc._rev];
tx.executeSql(sql, params, function (tx, res) {
if (!res.rowsAffected) {
return callback(createError(MISSING_DOC));
}
ret = {ok: true, id: doc._id, rev: '0-0'};
if (opts.ctx) { // return immediately
callback(null, ret);
}
});
}
if (opts.ctx) {
removeLocal(opts.ctx);
} else {
db.transaction(removeLocal, websqlError(callback), function () {
if (ret) {
callback(null, ret);
}
});
}
};
api._destroy = function (opts, callback) {
websqlChanges.removeAllListeners(api._name);
db.transaction(function (tx) {
var stores = [DOC_STORE$1, BY_SEQ_STORE$1, ATTACH_STORE$1, META_STORE$1,
LOCAL_STORE$1, ATTACH_AND_SEQ_STORE$1];
stores.forEach(function (store) {
tx.executeSql('DROP TABLE IF EXISTS ' + store, []);
});
}, websqlError(callback), function () {
if (hasLocalStorage()) {
delete window.localStorage['_pouch__websqldb_' + api._name];
delete window.localStorage[api._name];
}
callback(null, {'ok': true});
});
};
}
function canOpenTestDB() {
try {
openDatabase('_pouch_validate_websql', 1, '', 1);
return true;
} catch (err) {
return false;
}
}
// WKWebView had a bug where WebSQL would throw a DOM Exception 18
// (see https://bugs.webkit.org/show_bug.cgi?id=137760 and
// https://github.com/pouchdb/pouchdb/issues/5079)
// This has been fixed in latest WebKit, so we try to detect it here.
function isValidWebSQL() {
// WKWebView UA:
// Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X)
// AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13C75
// Chrome for iOS UA:
// Mozilla/5.0 (iPhone; U; CPU iPhone OS 5_1_1 like Mac OS X; en)
// AppleWebKit/534.46.0 (KHTML, like Gecko) CriOS/19.0.1084.60
// Mobile/9B206 Safari/7534.48.3
// Firefox for iOS UA:
// Mozilla/5.0 (iPhone; CPU iPhone OS 8_3 like Mac OS X) AppleWebKit/600.1.4
// (KHTML, like Gecko) FxiOS/1.0 Mobile/12F69 Safari/600.1.4
// indexedDB is null on some UIWebViews and undefined in others
// see: https://bugs.webkit.org/show_bug.cgi?id=137034
if (typeof indexedDB === 'undefined' || indexedDB === null ||
!/iP(hone|od|ad)/.test(navigator.userAgent)) {
// definitely not WKWebView, avoid creating an unnecessary database
return true;
}
// Cache the result in LocalStorage. Reason we do this is because if we
// call openDatabase() too many times, Safari craps out in SauceLabs and
// starts throwing DOM Exception 14s.
var hasLS = hasLocalStorage();
// Include user agent in the hash, so that if Safari is upgraded, we don't
// continually think it's broken.
var localStorageKey = '_pouch__websqldb_valid_' + navigator.userAgent;
if (hasLS && localStorage[localStorageKey]) {
return localStorage[localStorageKey] === '1';
}
var openedTestDB = canOpenTestDB();
if (hasLS) {
localStorage[localStorageKey] = openedTestDB ? '1' : '0';
}
return openedTestDB;
}
function valid() {
// SQLitePlugin leaks this global object, which we can use
// to detect if it's installed or not. The benefit is that it's
// declared immediately, before the 'deviceready' event has fired.
if (typeof SQLitePlugin !== 'undefined') {
return true;
}
if (typeof openDatabase === 'undefined') {
return false;
}
return isValidWebSQL();
}
function createOpenDBFunction(opts) {
return function (name, version, description, size) {
if (typeof sqlitePlugin !== 'undefined') {
// The SQLite Plugin started deviating pretty heavily from the
// standard openDatabase() function, as they started adding more features.
// It's better to just use their "new" format and pass in a big ol'
// options object. Also there are many options here that may come from
// the PouchDB constructor, so we have to grab those.
var sqlitePluginOpts = jsExtend.extend({}, opts, {
name: name,
version: version,
description: description,
size: size
});
return sqlitePlugin.openDatabase(sqlitePluginOpts);
}
// Traditional WebSQL API
return openDatabase(name, version, description, size);
};
}
function WebSQLPouch(opts, callback) {
var websql = createOpenDBFunction(opts);
var _opts = jsExtend.extend({
websql: websql
}, opts);
WebSqlPouch$1.call(this, _opts, callback);
}
WebSQLPouch.valid = valid;
WebSQLPouch.use_prefix = true;
function WebSqlPouch (PouchDB) {
PouchDB.adapter('websql', WebSQLPouch, true);
}
function wrappedFetch() {
var wrappedPromise = {};
var promise = new PouchPromise(function (resolve, reject) {
wrappedPromise.resolve = resolve;
wrappedPromise.reject = reject;
});
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
wrappedPromise.promise = promise;
PouchPromise.resolve().then(function () {
return fetch.apply(null, args);
}).then(function (response) {
wrappedPromise.resolve(response);
})["catch"](function (error) {
wrappedPromise.reject(error);
});
return wrappedPromise;
}
function fetchRequest(options, callback) {
var wrappedPromise, timer, response;
var headers = new Headers();
var fetchOptions = {
method: options.method,
credentials: 'include',
headers: headers
};
if (options.json) {
headers.set('Accept', 'application/json');
headers.set('Content-Type', options.headers['Content-Type'] ||
'application/json');
}
if (options.body && (options.body instanceof Blob)) {
readAsArrayBuffer(options.body, function (arrayBuffer) {
fetchOptions.body = arrayBuffer;
});
} else if (options.body &&
options.processData &&
typeof options.body !== 'string') {
fetchOptions.body = JSON.stringify(options.body);
} else if ('body' in options) {
fetchOptions.body = options.body;
} else {
fetchOptions.body = null;
}
Object.keys(options.headers).forEach(function (key) {
if (options.headers.hasOwnProperty(key)) {
headers.set(key, options.headers[key]);
}
});
wrappedPromise = wrappedFetch(options.url, fetchOptions);
if (options.timeout > 0) {
timer = setTimeout(function () {
wrappedPromise.reject(new Error('Load timeout for resource: ' +
options.url));
}, options.timeout);
}
wrappedPromise.promise.then(function (fetchResponse) {
response = {
statusCode: fetchResponse.status
};
if (options.timeout > 0) {
clearTimeout(timer);
}
if (response.statusCode >= 200 && response.statusCode < 300) {
return options.binary ? fetchResponse.blob() : fetchResponse.text();
}
return fetchResponse.json();
}).then(function (result) {
if (response.statusCode >= 200 && response.statusCode < 300) {
callback(null, response, result);
} else {
callback(result, response);
}
})["catch"](function (error) {
callback(error, response);
});
return {abort: wrappedPromise.reject};
}
function xhRequest(options, callback) {
var xhr, timer;
var timedout = false;
var abortReq = function () {
xhr.abort();
};
var timeoutReq = function () {
timedout = true;
xhr.abort();
};
if (options.xhr) {
xhr = new options.xhr();
} else {
xhr = new XMLHttpRequest();
}
try {
xhr.open(options.method, options.url);
} catch (exception) {
/* error code hardcoded to throw INVALID_URL */
callback(exception, {statusCode: 413});
}
xhr.withCredentials = ('withCredentials' in options) ?
options.withCredentials : true;
if (options.method === 'GET') {
delete options.headers['Content-Type'];
} else if (options.json) {
options.headers.Accept = 'application/json';
options.headers['Content-Type'] = options.headers['Content-Type'] ||
'application/json';
if (options.body &&
options.processData &&
typeof options.body !== "string") {
options.body = JSON.stringify(options.body);
}
}
if (options.binary) {
xhr.responseType = 'arraybuffer';
}
if (!('body' in options)) {
options.body = null;
}
for (var key in options.headers) {
if (options.headers.hasOwnProperty(key)) {
xhr.setRequestHeader(key, options.headers[key]);
}
}
if (options.timeout > 0) {
timer = setTimeout(timeoutReq, options.timeout);
xhr.onprogress = function () {
clearTimeout(timer);
if(xhr.readyState !== 4) {
timer = setTimeout(timeoutReq, options.timeout);
}
};
if (typeof xhr.upload !== 'undefined') { // does not exist in ie9
xhr.upload.onprogress = xhr.onprogress;
}
}
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
var response = {
statusCode: xhr.status
};
if (xhr.status >= 200 && xhr.status < 300) {
var data;
if (options.binary) {
data = createBlob([xhr.response || ''], {
type: xhr.getResponseHeader('Content-Type')
});
} else {
data = xhr.responseText;
}
callback(null, response, data);
} else {
var err = {};
if(timedout) {
err = new Error('ETIMEDOUT');
response.statusCode = 400; // for consistency with node request
} else {
try {
err = JSON.parse(xhr.response);
} catch(e) {}
}
callback(err, response);
}
};
if (options.body && (options.body instanceof Blob)) {
readAsArrayBuffer(options.body, function (arrayBuffer) {
xhr.send(arrayBuffer);
});
} else {
xhr.send(options.body);
}
return {abort: abortReq};
}
function testXhr() {
try {
new XMLHttpRequest();
return true;
} catch (err) {
return false;
}
}
var hasXhr = testXhr();
function ajax$1(options, callback) {
if (hasXhr || options.xhr) {
return xhRequest(options, callback);
} else {
return fetchRequest(options, callback);
}
}
// the blob already has a type; do nothing
var res$2 = function () {};
function defaultBody() {
return '';
}
function ajaxCore(options, callback) {
options = clone(options);
var defaultOptions = {
method : "GET",
headers: {},
json: true,
processData: true,
timeout: 10000,
cache: false
};
options = jsExtend.extend(defaultOptions, options);
function onSuccess(obj, resp, cb) {
if (!options.binary && options.json && typeof obj === 'string') {
try {
obj = JSON.parse(obj);
} catch (e) {
// Probably a malformed JSON from server
return cb(e);
}
}
if (Array.isArray(obj)) {
obj = obj.map(function (v) {
if (v.error || v.missing) {
return generateErrorFromResponse(v);
} else {
return v;
}
});
}
if (options.binary) {
res$2(obj, resp);
}
cb(null, obj, resp);
}
function onError(err, cb) {
var errParsed, errObj;
if (err.code && err.status) {
var err2 = new Error(err.message || err.code);
err2.status = err.status;
return cb(err2);
}
/* istanbul ignore if */
if (err.message && err.message === 'ETIMEDOUT') {
return cb(err);
}
// We always get code && status in node
/* istanbul ignore next */
try {
errParsed = JSON.parse(err.responseText);
//would prefer not to have a try/catch clause
errObj = generateErrorFromResponse(errParsed);
} catch (e) {
errObj = generateErrorFromResponse(err);
}
/* istanbul ignore next */
cb(errObj);
}
if (options.json) {
if (!options.binary) {
options.headers.Accept = 'application/json';
}
options.headers['Content-Type'] = options.headers['Content-Type'] ||
'application/json';
}
if (options.binary) {
options.encoding = null;
options.json = false;
}
if (!options.processData) {
options.json = false;
}
return ajax$1(options, function (err, response, body) {
if (err) {
err.status = response ? response.statusCode : 400;
return onError(err, callback);
}
var error;
var content_type = response.headers && response.headers['content-type'];
var data = body || defaultBody();
// CouchDB doesn't always return the right content-type for JSON data, so
// we check for ^{ and }$ (ignoring leading/trailing whitespace)
if (!options.binary && (options.json || !options.processData) &&
typeof data !== 'object' &&
(/json/.test(content_type) ||
(/^[\s]*\{/.test(data) && /\}[\s]*$/.test(data)))) {
try {
data = JSON.parse(data.toString());
} catch (e) {}
}
if (response.statusCode >= 200 && response.statusCode < 300) {
onSuccess(data, response, callback);
} else {
error = generateErrorFromResponse(data);
error.status = response.statusCode;
callback(error);
}
});
}
function ajax(opts, callback) {
// cache-buster, specifically designed to work around IE's aggressive caching
// see http://www.dashbay.com/2011/05/internet-explorer-caches-ajax/
// Also Safari caches POSTs, so we need to cache-bust those too.
var ua = (navigator && navigator.userAgent) ?
navigator.userAgent.toLowerCase() : '';
var isSafari = ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1;
var isIE = ua.indexOf('msie') !== -1;
var isEdge = ua.indexOf('edge') !== -1;
// it appears the new version of safari also caches GETs,
// see https://github.com/pouchdb/pouchdb/issues/5010
var shouldCacheBust = (isSafari ||
((isIE || isEdge) && opts.method === 'GET'));
var cache = 'cache' in opts ? opts.cache : true;
var isBlobUrl = /^blob:/.test(opts.url); // don't append nonces for blob URLs
if (!isBlobUrl && (shouldCacheBust || !cache)) {
var hasArgs = opts.url.indexOf('?') !== -1;
opts.url += (hasArgs ? '&' : '?') + '_nonce=' + Date.now();
}
return ajaxCore(opts, callback);
}
var CHANGES_BATCH_SIZE = 25;
var MAX_SIMULTANEOUS_REVS = 50;
var supportsBulkGetMap = {};
// according to http://stackoverflow.com/a/417184/680742,
// the de facto URL length limit is 2000 characters.
// but since most of our measurements don't take the full
// URL into account, we fudge it a bit.
// TODO: we could measure the full URL to enforce exactly 2000 chars
var MAX_URL_LENGTH = 1800;
var log$1 = debug('pouchdb:http');
function readAttachmentsAsBlobOrBuffer(row) {
var atts = row.doc && row.doc._attachments;
if (!atts) {
return;
}
Object.keys(atts).forEach(function (filename) {
var att = atts[filename];
att.data = b64ToBluffer(att.data, att.content_type);
});
}
function encodeDocId(id) {
if (/^_design/.test(id)) {
return '_design/' + encodeURIComponent(id.slice(8));
}
if (/^_local/.test(id)) {
return '_local/' + encodeURIComponent(id.slice(7));
}
return encodeURIComponent(id);
}
function preprocessAttachments$1(doc) {
if (!doc._attachments || !Object.keys(doc._attachments)) {
return PouchPromise.resolve();
}
return PouchPromise.all(Object.keys(doc._attachments).map(function (key) {
var attachment = doc._attachments[key];
if (attachment.data && typeof attachment.data !== 'string') {
return new PouchPromise(function (resolve) {
blobToBase64(attachment.data, resolve);
}).then(function (b64) {
attachment.data = b64;
});
}
}));
}
// Get all the information you possibly can about the URI given by name and
// return it as a suitable object.
function getHost(name) {
// Prase the URI into all its little bits
var uri = parseUri(name);
// Store the user and password as a separate auth object
if (uri.user || uri.password) {
uri.auth = {username: uri.user, password: uri.password};
}
// Split the path part of the URI into parts using '/' as the delimiter
// after removing any leading '/' and any trailing '/'
var parts = uri.path.replace(/(^\/|\/$)/g, '').split('/');
// Store the first part as the database name and remove it from the parts
// array
uri.db = parts.pop();
// Prevent double encoding of URI component
if (uri.db.indexOf('%') === -1) {
uri.db = encodeURIComponent(uri.db);
}
// Restore the path by joining all the remaining parts (all the parts
// except for the database name) with '/'s
uri.path = parts.join('/');
return uri;
}
// Generate a URL with the host data given by opts and the given path
function genDBUrl(opts, path) {
return genUrl(opts, opts.db + '/' + path);
}
// Generate a URL with the host data given by opts and the given path
function genUrl(opts, path) {
// If the host already has a path, then we need to have a path delimiter
// Otherwise, the path delimiter is the empty string
var pathDel = !opts.path ? '' : '/';
// If the host already has a path, then we need to have a path delimiter
// Otherwise, the path delimiter is the empty string
return opts.protocol + '://' + opts.host +
(opts.port ? (':' + opts.port) : '') +
'/' + opts.path + pathDel + path;
}
function paramsToStr(params) {
return '?' + Object.keys(params).map(function (k) {
return k + '=' + encodeURIComponent(params[k]);
}).join('&');
}
// Implements the PouchDB API for dealing with CouchDB instances over HTTP
function HttpPouch(opts, callback) {
// The functions that will be publicly available for HttpPouch
var api = this;
// Parse the URI given by opts.name into an easy-to-use object
var getHostFun = getHost;
// TODO: this seems to only be used by yarong for the Thali project.
// Verify whether or not it's still needed.
/* istanbul ignore if */
if (opts.getHost) {
getHostFun = opts.getHost;
}
var host = getHostFun(opts.name, opts);
var dbUrl = genDBUrl(host, '');
opts = clone(opts);
var ajaxOpts = opts.ajax || {};
api.getUrl = function () { return dbUrl; };
api.getHeaders = function () { return ajaxOpts.headers || {}; };
if (opts.auth || host.auth) {
var nAuth = opts.auth || host.auth;
var str = nAuth.username + ':' + nAuth.password;
var token = btoa$1(unescape(encodeURIComponent(str)));
ajaxOpts.headers = ajaxOpts.headers || {};
ajaxOpts.headers.Authorization = 'Basic ' + token;
}
// Not strictly necessary, but we do this because numerous tests
// rely on swapping ajax in and out.
api._ajax = ajax;
function ajax$$(userOpts, options, callback) {
var reqAjax = userOpts.ajax || {};
var reqOpts = jsExtend.extend(clone(ajaxOpts), reqAjax, options);
log$1(reqOpts.method + ' ' + reqOpts.url);
return api._ajax(reqOpts, callback);
}
function ajaxPromise(userOpts, opts) {
return new PouchPromise(function (resolve, reject) {
ajax$$(userOpts, opts, function (err, res) {
if (err) {
return reject(err);
}
resolve(res);
});
});
}
function adapterFun$$(name, fun) {
return adapterFun(name, getArguments(function (args) {
setup().then(function () {
return fun.apply(this, args);
})["catch"](function (e) {
var callback = args.pop();
callback(e);
});
}));
}
var setupPromise;
function setup() {
// TODO: Remove `skipSetup` in favor of `skip_setup` in a future release
if (opts.skipSetup || opts.skip_setup) {
return PouchPromise.resolve();
}
// If there is a setup in process or previous successful setup
// done then we will use that
// If previous setups have been rejected we will try again
if (setupPromise) {
return setupPromise;
}
var checkExists = {method: 'GET', url: dbUrl};
setupPromise = ajaxPromise({}, checkExists)["catch"](function (err) {
if (err && err.status && err.status === 404) {
// Doesnt exist, create it
explainError(404, 'PouchDB is just detecting if the remote exists.');
return ajaxPromise({}, {method: 'PUT', url: dbUrl});
} else {
return PouchPromise.reject(err);
}
})["catch"](function (err) {
// If we try to create a database that already exists, skipped in
// istanbul since its catching a race condition.
/* istanbul ignore if */
if (err && err.status && err.status === 412) {
return true;
}
return PouchPromise.reject(err);
});
setupPromise["catch"](function () {
setupPromise = null;
});
return setupPromise;
}
setTimeout(function () {
callback(null, api);
});
api.type = function () {
return 'http';
};
api.id = adapterFun$$('id', function (callback) {
ajax$$({}, {method: 'GET', url: genUrl(host, '')}, function (err, result) {
var uuid = (result && result.uuid) ?
(result.uuid + host.db) : genDBUrl(host, '');
callback(null, uuid);
});
});
api.request = adapterFun$$('request', function (options, callback) {
options.url = genDBUrl(host, options.url);
ajax$$({}, options, callback);
});
// Sends a POST request to the host calling the couchdb _compact function
// version: The version of CouchDB it is running
api.compact = adapterFun$$('compact', function (opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
opts = clone(opts);
ajax$$(opts, {
url: genDBUrl(host, '_compact'),
method: 'POST'
}, function () {
function ping() {
api.info(function (err, res) {
if (res && !res.compact_running) {
callback(null, {ok: true});
} else {
setTimeout(ping, opts.interval || 200);
}
});
}
// Ping the http if it's finished compaction
ping();
});
});
api.bulkGet = adapterFun('bulkGet', function (opts, callback) {
var self = this;
function doBulkGet(cb) {
var params = {};
if (opts.revs) {
params.revs = true;
}
if (opts.attachments) {
/* istanbul ignore next */
params.attachments = true;
}
ajax$$({}, {
url: genDBUrl(host, '_bulk_get' + paramsToStr(params)),
method: 'POST',
body: { docs: opts.docs}
}, cb);
}
function doBulkGetShim() {
// avoid "url too long error" by splitting up into multiple requests
var batchSize = MAX_SIMULTANEOUS_REVS;
var numBatches = Math.ceil(opts.docs.length / batchSize);
var numDone = 0;
var results = new Array(numBatches);
function onResult(batchNum) {
return function (err, res) {
// err is impossible because shim returns a list of errs in that case
results[batchNum] = res.results;
if (++numDone === numBatches) {
callback(null, {results: flatten(results)});
}
};
}
for (var i = 0; i < numBatches; i++) {
var subOpts = pick(opts, ['revs', 'attachments']);
subOpts.ajax = ajaxOpts;
subOpts.docs = opts.docs.slice(i * batchSize,
Math.min(opts.docs.length, (i + 1) * batchSize));
bulkGet(self, subOpts, onResult(i));
}
}
// mark the whole database as either supporting or not supporting _bulk_get
var dbUrl = genUrl(host, '');
var supportsBulkGet = supportsBulkGetMap[dbUrl];
if (typeof supportsBulkGet !== 'boolean') {
// check if this database supports _bulk_get
doBulkGet(function (err, res) {
/* istanbul ignore else */
if (err) {
var status = Math.floor(err.status / 100);
/* istanbul ignore else */
if (status === 4 || status === 5) { // 40x or 50x
supportsBulkGetMap[dbUrl] = false;
explainError(
err.status,
'PouchDB is just detecting if the remote ' +
'supports the _bulk_get API.'
);
doBulkGetShim();
} else {
callback(err);
}
} else {
supportsBulkGetMap[dbUrl] = true;
callback(null, res);
}
});
} else if (supportsBulkGet) {
/* istanbul ignore next */
doBulkGet(callback);
} else {
doBulkGetShim();
}
});
// Calls GET on the host, which gets back a JSON string containing
// couchdb: A welcome string
// version: The version of CouchDB it is running
api._info = function (callback) {
setup().then(function () {
ajax$$({}, {
method: 'GET',
url: genDBUrl(host, '')
}, function (err, res) {
/* istanbul ignore next */
if (err) {
return callback(err);
}
res.host = genDBUrl(host, '');
callback(null, res);
});
})["catch"](callback);
};
// Get the document with the given id from the database given by host.
// The id could be solely the _id in the database, or it may be a
// _design/ID or _local/ID path
api.get = adapterFun$$('get', function (id, opts, callback) {
// If no options were given, set the callback to the second parameter
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
opts = clone(opts);
// List of parameters to add to the GET request
var params = {};
if (opts.revs) {
params.revs = true;
}
if (opts.revs_info) {
params.revs_info = true;
}
if (opts.open_revs) {
if (opts.open_revs !== "all") {
opts.open_revs = JSON.stringify(opts.open_revs);
}
params.open_revs = opts.open_revs;
}
if (opts.rev) {
params.rev = opts.rev;
}
if (opts.conflicts) {
params.conflicts = opts.conflicts;
}
id = encodeDocId(id);
// Set the options for the ajax call
var options = {
method: 'GET',
url: genDBUrl(host, id + paramsToStr(params))
};
function fetchAttachments(doc) {
var atts = doc._attachments;
var filenames = atts && Object.keys(atts);
if (!atts || !filenames.length) {
return;
}
// we fetch these manually in separate XHRs, because
// Sync Gateway would normally send it back as multipart/mixed,
// which we cannot parse. Also, this is more efficient than
// receiving attachments as base64-encoded strings.
return PouchPromise.all(filenames.map(function (filename) {
var att = atts[filename];
var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +
'?rev=' + doc._rev;
return ajaxPromise(opts, {
method: 'GET',
url: genDBUrl(host, path),
binary: true
}).then(function (blob) {
if (opts.binary) {
return blob;
}
return new PouchPromise(function (resolve) {
blobToBase64(blob, resolve);
});
}).then(function (data) {
delete att.stub;
delete att.length;
att.data = data;
});
}));
}
function fetchAllAttachments(docOrDocs) {
if (Array.isArray(docOrDocs)) {
return PouchPromise.all(docOrDocs.map(function (doc) {
if (doc.ok) {
return fetchAttachments(doc.ok);
}
}));
}
return fetchAttachments(docOrDocs);
}
ajaxPromise(opts, options).then(function (res) {
return PouchPromise.resolve().then(function () {
if (opts.attachments) {
return fetchAllAttachments(res);
}
}).then(function () {
callback(null, res);
});
})["catch"](callback);
});
// Delete the document given by doc from the database given by host.
api.remove = adapterFun$$('remove',
function (docOrId, optsOrRev, opts, callback) {
var doc;
if (typeof optsOrRev === 'string') {
// id, rev, opts, callback style
doc = {
_id: docOrId,
_rev: optsOrRev
};
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
} else {
// doc, opts, callback style
doc = docOrId;
if (typeof optsOrRev === 'function') {
callback = optsOrRev;
opts = {};
} else {
callback = opts;
opts = optsOrRev;
}
}
var rev = (doc._rev || opts.rev);
// Delete the document
ajax$$(opts, {
method: 'DELETE',
url: genDBUrl(host, encodeDocId(doc._id)) + '?rev=' + rev
}, callback);
});
function encodeAttachmentId(attachmentId) {
return attachmentId.split("/").map(encodeURIComponent).join("/");
}
// Get the attachment
api.getAttachment =
adapterFun$$('getAttachment', function (docId, attachmentId, opts,
callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
var params = opts.rev ? ('?rev=' + opts.rev) : '';
var url = genDBUrl(host, encodeDocId(docId)) + '/' +
encodeAttachmentId(attachmentId) + params;
ajax$$(opts, {
method: 'GET',
url: url,
binary: true
}, callback);
});
// Remove the attachment given by the id and rev
api.removeAttachment =
adapterFun$$('removeAttachment', function (docId, attachmentId, rev,
callback) {
var url = genDBUrl(host, encodeDocId(docId) + '/' +
encodeAttachmentId(attachmentId)) + '?rev=' + rev;
ajax$$({}, {
method: 'DELETE',
url: url
}, callback);
});
// Add the attachment given by blob and its contentType property
// to the document with the given id, the revision given by rev, and
// add it to the database given by host.
api.putAttachment =
adapterFun$$('putAttachment', function (docId, attachmentId, rev, blob,
type, callback) {
if (typeof type === 'function') {
callback = type;
type = blob;
blob = rev;
rev = null;
}
var id = encodeDocId(docId) + '/' + encodeAttachmentId(attachmentId);
var url = genDBUrl(host, id);
if (rev) {
url += '?rev=' + rev;
}
if (typeof blob === 'string') {
// input is assumed to be a base64 string
var binary;
try {
binary = atob$1(blob);
} catch (err) {
return callback(createError(BAD_ARG,
'Attachment is not a valid base64 string'));
}
blob = binary ? binStringToBluffer(binary, type) : '';
}
var opts = {
headers: {'Content-Type': type},
method: 'PUT',
url: url,
processData: false,
body: blob,
timeout: ajaxOpts.timeout || 60000
};
// Add the attachment
ajax$$({}, opts, callback);
});
// Update/create multiple documents given by req in the database
// given by host.
api._bulkDocs = function (req, opts, callback) {
// If new_edits=false then it prevents the database from creating
// new revision numbers for the documents. Instead it just uses
// the old ones. This is used in database replication.
req.new_edits = opts.new_edits;
setup().then(function () {
return PouchPromise.all(req.docs.map(preprocessAttachments$1));
}).then(function () {
// Update/create the documents
ajax$$(opts, {
method: 'POST',
url: genDBUrl(host, '_bulk_docs'),
body: req
}, function (err, results) {
if (err) {
return callback(err);
}
results.forEach(function (result) {
result.ok = true; // smooths out cloudant not adding this
});
callback(null, results);
});
})["catch"](callback);
};
// Get a listing of the documents in the database given
// by host and ordered by increasing id.
api.allDocs = adapterFun$$('allDocs', function (opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
opts = clone(opts);
// List of parameters to add to the GET request
var params = {};
var body;
var method = 'GET';
if (opts.conflicts) {
params.conflicts = true;
}
if (opts.descending) {
params.descending = true;
}
if (opts.include_docs) {
params.include_docs = true;
}
// added in CouchDB 1.6.0
if (opts.attachments) {
params.attachments = true;
}
if (opts.key) {
params.key = JSON.stringify(opts.key);
}
if (opts.start_key) {
opts.startkey = opts.start_key;
}
if (opts.startkey) {
params.startkey = JSON.stringify(opts.startkey);
}
if (opts.end_key) {
opts.endkey = opts.end_key;
}
if (opts.endkey) {
params.endkey = JSON.stringify(opts.endkey);
}
if (typeof opts.inclusive_end !== 'undefined') {
params.inclusive_end = !!opts.inclusive_end;
}
if (typeof opts.limit !== 'undefined') {
params.limit = opts.limit;
}
if (typeof opts.skip !== 'undefined') {
params.skip = opts.skip;
}
var paramStr = paramsToStr(params);
if (typeof opts.keys !== 'undefined') {
var keysAsString =
'keys=' + encodeURIComponent(JSON.stringify(opts.keys));
if (keysAsString.length + paramStr.length + 1 <= MAX_URL_LENGTH) {
// If the keys are short enough, do a GET. we do this to work around
// Safari not understanding 304s on POSTs (see issue #1239)
paramStr += '&' + keysAsString;
} else {
// If keys are too long, issue a POST request to circumvent GET
// query string limits
// see http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options
method = 'POST';
body = {keys: opts.keys};
}
}
// Get the document listing
ajaxPromise(opts, {
method: method,
url: genDBUrl(host, '_all_docs' + paramStr),
body: body
}).then(function (res) {
if (opts.include_docs && opts.attachments && opts.binary) {
res.rows.forEach(readAttachmentsAsBlobOrBuffer);
}
callback(null, res);
})["catch"](callback);
});
// Get a list of changes made to documents in the database given by host.
// TODO According to the README, there should be two other methods here,
// api.changes.addListener and api.changes.removeListener.
api._changes = function (opts) {
// We internally page the results of a changes request, this means
// if there is a large set of changes to be returned we can start
// processing them quicker instead of waiting on the entire
// set of changes to return and attempting to process them at once
var batchSize = 'batch_size' in opts ? opts.batch_size : CHANGES_BATCH_SIZE;
opts = clone(opts);
opts.timeout = ('timeout' in opts) ? opts.timeout :
('timeout' in ajaxOpts) ? ajaxOpts.timeout :
30 * 1000;
// We give a 5 second buffer for CouchDB changes to respond with
// an ok timeout (if a timeout it set)
var params = opts.timeout ? {timeout: opts.timeout - (5 * 1000)} : {};
var limit = (typeof opts.limit !== 'undefined') ? opts.limit : false;
var returnDocs;
if ('return_docs' in opts) {
returnDocs = opts.return_docs;
} else if ('returnDocs' in opts) {
// TODO: Remove 'returnDocs' in favor of 'return_docs' in a future release
returnDocs = opts.returnDocs;
} else {
returnDocs = true;
}
//
var leftToFetch = limit;
if (opts.style) {
params.style = opts.style;
}
if (opts.include_docs || opts.filter && typeof opts.filter === 'function') {
params.include_docs = true;
}
if (opts.attachments) {
params.attachments = true;
}
if (opts.continuous) {
params.feed = 'longpoll';
}
if (opts.conflicts) {
params.conflicts = true;
}
if (opts.descending) {
params.descending = true;
}
if ('heartbeat' in opts) {
// If the heartbeat value is false, it disables the default heartbeat
if (opts.heartbeat) {
params.heartbeat = opts.heartbeat;
}
} else {
// Default heartbeat to 10 seconds
params.heartbeat = 10000;
}
if (opts.filter && typeof opts.filter === 'string') {
params.filter = opts.filter;
}
if (opts.view && typeof opts.view === 'string') {
params.filter = '_view';
params.view = opts.view;
}
// If opts.query_params exists, pass it through to the changes request.
// These parameters may be used by the filter on the source database.
if (opts.query_params && typeof opts.query_params === 'object') {
for (var param_name in opts.query_params) {
/* istanbul ignore else */
if (opts.query_params.hasOwnProperty(param_name)) {
params[param_name] = opts.query_params[param_name];
}
}
}
var method = 'GET';
var body;
if (opts.doc_ids) {
// set this automagically for the user; it's annoying that couchdb
// requires both a "filter" and a "doc_ids" param.
params.filter = '_doc_ids';
var docIdsJson = JSON.stringify(opts.doc_ids);
if (docIdsJson.length < MAX_URL_LENGTH) {
params.doc_ids = docIdsJson;
} else {
// anything greater than ~2000 is unsafe for gets, so
// use POST instead
method = 'POST';
body = {doc_ids: opts.doc_ids };
}
}
var xhr;
var lastFetchedSeq;
// Get all the changes starting wtih the one immediately after the
// sequence number given by since.
var fetch = function (since, callback) {
if (opts.aborted) {
return;
}
params.since = since;
// "since" can be any kind of json object in Coudant/CouchDB 2.x
/* istanbul ignore next */
if (typeof params.since === "object") {
params.since = JSON.stringify(params.since);
}
if (opts.descending) {
if (limit) {
params.limit = leftToFetch;
}
} else {
params.limit = (!limit || leftToFetch > batchSize) ?
batchSize : leftToFetch;
}
// Set the options for the ajax call
var xhrOpts = {
method: method,
url: genDBUrl(host, '_changes' + paramsToStr(params)),
timeout: opts.timeout,
body: body
};
lastFetchedSeq = since;
/* istanbul ignore if */
if (opts.aborted) {
return;
}
// Get the changes
setup().then(function () {
xhr = ajax$$(opts, xhrOpts, callback);
})["catch"](callback);
};
// If opts.since exists, get all the changes from the sequence
// number given by opts.since. Otherwise, get all the changes
// from the sequence number 0.
var results = {results: []};
var fetched = function (err, res) {
if (opts.aborted) {
return;
}
var raw_results_length = 0;
// If the result of the ajax call (res) contains changes (res.results)
if (res && res.results) {
raw_results_length = res.results.length;
results.last_seq = res.last_seq;
// For each change
var req = {};
req.query = opts.query_params;
res.results = res.results.filter(function (c) {
leftToFetch--;
var ret = filterChange(opts)(c);
if (ret) {
if (opts.include_docs && opts.attachments && opts.binary) {
readAttachmentsAsBlobOrBuffer(c);
}
if (returnDocs) {
results.results.push(c);
}
opts.onChange(c);
}
return ret;
});
} else if (err) {
// In case of an error, stop listening for changes and call
// opts.complete
opts.aborted = true;
opts.complete(err);
return;
}
// The changes feed may have timed out with no results
// if so reuse last update sequence
if (res && res.last_seq) {
lastFetchedSeq = res.last_seq;
}
var finished = (limit && leftToFetch <= 0) ||
(res && raw_results_length < batchSize) ||
(opts.descending);
if ((opts.continuous && !(limit && leftToFetch <= 0)) || !finished) {
// Queue a call to fetch again with the newest sequence number
setTimeout(function () { fetch(lastFetchedSeq, fetched); }, 0);
} else {
// We're done, call the callback
opts.complete(null, results);
}
};
fetch(opts.since || 0, fetched);
// Return a method to cancel this method from processing any more
return {
cancel: function () {
opts.aborted = true;
if (xhr) {
xhr.abort();
}
}
};
};
// Given a set of document/revision IDs (given by req), tets the subset of
// those that do NOT correspond to revisions stored in the database.
// See http://wiki.apache.org/couchdb/HttpPostRevsDiff
api.revsDiff = adapterFun$$('revsDiff', function (req, opts, callback) {
// If no options were given, set the callback to be the second parameter
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
// Get the missing document/revision IDs
ajax$$(opts, {
method: 'POST',
url: genDBUrl(host, '_revs_diff'),
body: req
}, callback);
});
api._close = function (callback) {
callback();
};
api._destroy = function (options, callback) {
ajax$$(options, {
url: genDBUrl(host, ''),
method: 'DELETE'
}, function (err, resp) {
if (err && err.status && err.status !== 404) {
return callback(err);
}
callback(null, resp);
});
};
}
// HttpPouch is a valid adapter.
HttpPouch.valid = function () {
return true;
};
function HttpPouch$1 (PouchDB) {
PouchDB.adapter('http', HttpPouch, false);
PouchDB.adapter('https', HttpPouch, false);
}
function TaskQueue$1() {
this.promise = new PouchPromise(function (fulfill) {fulfill(); });
}
TaskQueue$1.prototype.add = function (promiseFactory) {
this.promise = this.promise["catch"](function () {
// just recover
}).then(function () {
return promiseFactory();
});
return this.promise;
};
TaskQueue$1.prototype.finish = function () {
return this.promise;
};
function createView(opts) {
var sourceDB = opts.db;
var viewName = opts.viewName;
var mapFun = opts.map;
var reduceFun = opts.reduce;
var temporary = opts.temporary;
// the "undefined" part is for backwards compatibility
var viewSignature = mapFun.toString() + (reduceFun && reduceFun.toString()) +
'undefined';
if (!temporary && sourceDB._cachedViews) {
var cachedView = sourceDB._cachedViews[viewSignature];
if (cachedView) {
return PouchPromise.resolve(cachedView);
}
}
return sourceDB.info().then(function (info) {
var depDbName = info.db_name + '-mrview-' +
(temporary ? 'temp' : stringMd5(viewSignature));
// save the view name in the source db so it can be cleaned up if necessary
// (e.g. when the _design doc is deleted, remove all associated view data)
function diffFunction(doc) {
doc.views = doc.views || {};
var fullViewName = viewName;
if (fullViewName.indexOf('/') === -1) {
fullViewName = viewName + '/' + viewName;
}
var depDbs = doc.views[fullViewName] = doc.views[fullViewName] || {};
/* istanbul ignore if */
if (depDbs[depDbName]) {
return; // no update necessary
}
depDbs[depDbName] = true;
return doc;
}
return upsert(sourceDB, '_local/mrviews', diffFunction).then(function () {
return sourceDB.registerDependentDatabase(depDbName).then(function (res) {
var db = res.db;
db.auto_compaction = true;
var view = {
name: depDbName,
db: db,
sourceDB: sourceDB,
adapter: sourceDB.adapter,
mapFun: mapFun,
reduceFun: reduceFun
};
return view.db.get('_local/lastSeq')["catch"](function (err) {
/* istanbul ignore if */
if (err.status !== 404) {
throw err;
}
}).then(function (lastSeqDoc) {
view.seq = lastSeqDoc ? lastSeqDoc.seq : 0;
if (!temporary) {
sourceDB._cachedViews = sourceDB._cachedViews || {};
sourceDB._cachedViews[viewSignature] = view;
view.db.once('destroyed', function () {
delete sourceDB._cachedViews[viewSignature];
});
}
return view;
});
});
});
});
}
function evalfunc(func, emit, sum, log, isArray, toJSON) {
return scopedEval(
"return (" + func.replace(/;\s*$/, "") + ");",
{
emit: emit,
sum: sum,
log: log,
isArray: isArray,
toJSON: toJSON
}
);
}
var promisedCallback = function (promise, callback) {
if (callback) {
promise.then(function (res) {
process.nextTick(function () {
callback(null, res);
});
}, function (reason) {
process.nextTick(function () {
callback(reason);
});
});
}
return promise;
};
var callbackify = function (fun) {
return getArguments(function (args) {
var cb = args.pop();
var promise = fun.apply(this, args);
if (typeof cb === 'function') {
promisedCallback(promise, cb);
}
return promise;
});
};
// Promise finally util similar to Q.finally
var fin = function (promise, finalPromiseFactory) {
return promise.then(function (res) {
return finalPromiseFactory().then(function () {
return res;
});
}, function (reason) {
return finalPromiseFactory().then(function () {
throw reason;
});
});
};
var sequentialize = function (queue, promiseFactory) {
return function () {
var args = arguments;
var that = this;
return queue.add(function () {
return promiseFactory.apply(that, args);
});
};
};
// uniq an array of strings, order not guaranteed
// similar to underscore/lodash _.uniq
var uniq = function (arr) {
var map = {};
for (var i = 0, len = arr.length; i < len; i++) {
map['$' + arr[i]] = true;
}
var keys = Object.keys(map);
var output = new Array(keys.length);
for (i = 0, len = keys.length; i < len; i++) {
output[i] = keys[i].substring(1);
}
return output;
};
var persistentQueues = {};
var tempViewQueue = new TaskQueue$1();
var CHANGES_BATCH_SIZE$1 = 50;
var log$2 = guardedConsole.bind(null, 'log');
function parseViewName(name) {
// can be either 'ddocname/viewname' or just 'viewname'
// (where the ddoc name is the same)
return name.indexOf('/') === -1 ? [name, name] : name.split('/');
}
function isGenOne(changes) {
// only return true if the current change is 1-
// and there are no other leafs
return changes.length === 1 && /^1-/.test(changes[0].rev);
}
function emitError(db, e) {
try {
db.emit('error', e);
} catch (err) {
guardedConsole('error',
'The user\'s map/reduce function threw an uncaught error.\n' +
'You can debug this error by doing:\n' +
'myDatabase.on(\'error\', function (err) { debugger; });\n' +
'Please double-check your map/reduce function.');
guardedConsole('error', e);
}
}
function tryCode$1(db, fun, args) {
// emit an event if there was an error thrown by a map/reduce function.
// putting try/catches in a single function also avoids deoptimizations.
try {
return {
output : fun.apply(null, args)
};
} catch (e) {
emitError(db, e);
return {error: e};
}
}
function sortByKeyThenValue(x, y) {
var keyCompare = pouchdbCollate.collate(x.key, y.key);
return keyCompare !== 0 ? keyCompare : pouchdbCollate.collate(x.value, y.value);
}
function sliceResults(results, limit, skip) {
skip = skip || 0;
if (typeof limit === 'number') {
return results.slice(skip, limit + skip);
} else if (skip > 0) {
return results.slice(skip);
}
return results;
}
function rowToDocId(row) {
var val = row.value;
// Users can explicitly specify a joined doc _id, or it
// defaults to the doc _id that emitted the key/value.
var docId = (val && typeof val === 'object' && val._id) || row.id;
return docId;
}
function readAttachmentsAsBlobOrBuffer$1(res) {
res.rows.forEach(function (row) {
var atts = row.doc && row.doc._attachments;
if (!atts) {
return;
}
Object.keys(atts).forEach(function (filename) {
var att = atts[filename];
atts[filename].data = b64ToBluffer(att.data, att.content_type);
});
});
}
function postprocessAttachments(opts) {
return function (res) {
if (opts.include_docs && opts.attachments && opts.binary) {
readAttachmentsAsBlobOrBuffer$1(res);
}
return res;
};
}
function createBuiltInError(name) {
var message = 'builtin ' + name +
' function requires map values to be numbers' +
' or number arrays';
return new BuiltInError(message);
}
function sum(values) {
var result = 0;
for (var i = 0, len = values.length; i < len; i++) {
var num = values[i];
if (typeof num !== 'number') {
if (Array.isArray(num)) {
// lists of numbers are also allowed, sum them separately
result = typeof result === 'number' ? [result] : result;
for (var j = 0, jLen = num.length; j < jLen; j++) {
var jNum = num[j];
if (typeof jNum !== 'number') {
throw createBuiltInError('_sum');
} else if (typeof result[j] === 'undefined') {
result.push(jNum);
} else {
result[j] += jNum;
}
}
} else { // not array/number
throw createBuiltInError('_sum');
}
} else if (typeof result === 'number') {
result += num;
} else { // add number to array
result[0] += num;
}
}
return result;
}
var builtInReduce = {
_sum: function (keys, values) {
return sum(values);
},
_count: function (keys, values) {
return values.length;
},
_stats: function (keys, values) {
// no need to implement rereduce=true, because Pouch
// will never call it
function sumsqr(values) {
var _sumsqr = 0;
for (var i = 0, len = values.length; i < len; i++) {
var num = values[i];
_sumsqr += (num * num);
}
return _sumsqr;
}
return {
sum : sum(values),
min : Math.min.apply(null, values),
max : Math.max.apply(null, values),
count : values.length,
sumsqr : sumsqr(values)
};
}
};
function addHttpParam(paramName, opts, params, asJson) {
// add an http param from opts to params, optionally json-encoded
var val = opts[paramName];
if (typeof val !== 'undefined') {
if (asJson) {
val = encodeURIComponent(JSON.stringify(val));
}
params.push(paramName + '=' + val);
}
}
function coerceInteger(integerCandidate) {
if (typeof integerCandidate !== 'undefined') {
var asNumber = Number(integerCandidate);
// prevents e.g. '1foo' or '1.1' being coerced to 1
if (!isNaN(asNumber) && asNumber === parseInt(integerCandidate, 10)) {
return asNumber;
} else {
return integerCandidate;
}
}
}
function coerceOptions(opts) {
opts.group_level = coerceInteger(opts.group_level);
opts.limit = coerceInteger(opts.limit);
opts.skip = coerceInteger(opts.skip);
return opts;
}
function checkPositiveInteger(number) {
if (number) {
if (typeof number !== 'number') {
return new QueryParseError('Invalid value for integer: "' +
number + '"');
}
if (number < 0) {
return new QueryParseError('Invalid value for positive integer: ' +
'"' + number + '"');
}
}
}
function checkQueryParseError(options, fun) {
var startkeyName = options.descending ? 'endkey' : 'startkey';
var endkeyName = options.descending ? 'startkey' : 'endkey';
if (typeof options[startkeyName] !== 'undefined' &&
typeof options[endkeyName] !== 'undefined' &&
pouchdbCollate.collate(options[startkeyName], options[endkeyName]) > 0) {
throw new QueryParseError('No rows can match your key range, ' +
'reverse your start_key and end_key or set {descending : true}');
} else if (fun.reduce && options.reduce !== false) {
if (options.include_docs) {
throw new QueryParseError('{include_docs:true} is invalid for reduce');
} else if (options.keys && options.keys.length > 1 &&
!options.group && !options.group_level) {
throw new QueryParseError('Multi-key fetches for reduce views must use ' +
'{group: true}');
}
}
['group_level', 'limit', 'skip'].forEach(function (optionName) {
var error = checkPositiveInteger(options[optionName]);
if (error) {
throw error;
}
});
}
function httpQuery(db, fun, opts) {
// List of parameters to add to the PUT request
var params = [];
var body;
var method = 'GET';
// If opts.reduce exists and is defined, then add it to the list
// of parameters.
// If reduce=false then the results are that of only the map function
// not the final result of map and reduce.
addHttpParam('reduce', opts, params);
addHttpParam('include_docs', opts, params);
addHttpParam('attachments', opts, params);
addHttpParam('limit', opts, params);
addHttpParam('descending', opts, params);
addHttpParam('group', opts, params);
addHttpParam('group_level', opts, params);
addHttpParam('skip', opts, params);
addHttpParam('stale', opts, params);
addHttpParam('conflicts', opts, params);
addHttpParam('startkey', opts, params, true);
addHttpParam('start_key', opts, params, true);
addHttpParam('endkey', opts, params, true);
addHttpParam('end_key', opts, params, true);
addHttpParam('inclusive_end', opts, params);
addHttpParam('key', opts, params, true);
// Format the list of parameters into a valid URI query string
params = params.join('&');
params = params === '' ? '' : '?' + params;
// If keys are supplied, issue a POST to circumvent GET query string limits
// see http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options
if (typeof opts.keys !== 'undefined') {
var MAX_URL_LENGTH = 2000;
// according to http://stackoverflow.com/a/417184/680742,
// the de facto URL length limit is 2000 characters
var keysAsString =
'keys=' + encodeURIComponent(JSON.stringify(opts.keys));
if (keysAsString.length + params.length + 1 <= MAX_URL_LENGTH) {
// If the keys are short enough, do a GET. we do this to work around
// Safari not understanding 304s on POSTs (see pouchdb/pouchdb#1239)
params += (params[0] === '?' ? '&' : '?') + keysAsString;
} else {
method = 'POST';
if (typeof fun === 'string') {
body = {keys: opts.keys};
} else { // fun is {map : mapfun}, so append to this
fun.keys = opts.keys;
}
}
}
// We are referencing a query defined in the design doc
if (typeof fun === 'string') {
var parts = parseViewName(fun);
return db.request({
method: method,
url: '_design/' + parts[0] + '/_view/' + parts[1] + params,
body: body
}).then(postprocessAttachments(opts));
}
// We are using a temporary view, terrible for performance, good for testing
body = body || {};
Object.keys(fun).forEach(function (key) {
if (Array.isArray(fun[key])) {
body[key] = fun[key];
} else {
body[key] = fun[key].toString();
}
});
return db.request({
method: 'POST',
url: '_temp_view' + params,
body: body
}).then(postprocessAttachments(opts));
}
// custom adapters can define their own api._query
// and override the default behavior
/* istanbul ignore next */
function customQuery(db, fun, opts) {
return new PouchPromise(function (resolve, reject) {
db._query(fun, opts, function (err, res) {
if (err) {
return reject(err);
}
resolve(res);
});
});
}
// custom adapters can define their own api._viewCleanup
// and override the default behavior
/* istanbul ignore next */
function customViewCleanup(db) {
return new PouchPromise(function (resolve, reject) {
db._viewCleanup(function (err, res) {
if (err) {
return reject(err);
}
resolve(res);
});
});
}
function defaultsTo(value) {
return function (reason) {
/* istanbul ignore else */
if (reason.status === 404) {
return value;
} else {
throw reason;
}
};
}
// returns a promise for a list of docs to update, based on the input docId.
// the order doesn't matter, because post-3.2.0, bulkDocs
// is an atomic operation in all three adapters.
function getDocsToPersist(docId, view, docIdsToChangesAndEmits) {
var metaDocId = '_local/doc_' + docId;
var defaultMetaDoc = {_id: metaDocId, keys: []};
var docData = docIdsToChangesAndEmits[docId];
var indexableKeysToKeyValues = docData.indexableKeysToKeyValues;
var changes = docData.changes;
function getMetaDoc() {
if (isGenOne(changes)) {
// generation 1, so we can safely assume initial state
// for performance reasons (avoids unnecessary GETs)
return PouchPromise.resolve(defaultMetaDoc);
}
return view.db.get(metaDocId)["catch"](defaultsTo(defaultMetaDoc));
}
function getKeyValueDocs(metaDoc) {
if (!metaDoc.keys.length) {
// no keys, no need for a lookup
return PouchPromise.resolve({rows: []});
}
return view.db.allDocs({
keys: metaDoc.keys,
include_docs: true
});
}
function processKvDocs(metaDoc, kvDocsRes) {
var kvDocs = [];
var oldKeysMap = {};
for (var i = 0, len = kvDocsRes.rows.length; i < len; i++) {
var row = kvDocsRes.rows[i];
var doc = row.doc;
if (!doc) { // deleted
continue;
}
kvDocs.push(doc);
oldKeysMap[doc._id] = true;
doc._deleted = !indexableKeysToKeyValues[doc._id];
if (!doc._deleted) {
var keyValue = indexableKeysToKeyValues[doc._id];
if ('value' in keyValue) {
doc.value = keyValue.value;
}
}
}
var newKeys = Object.keys(indexableKeysToKeyValues);
newKeys.forEach(function (key) {
if (!oldKeysMap[key]) {
// new doc
var kvDoc = {
_id: key
};
var keyValue = indexableKeysToKeyValues[key];
if ('value' in keyValue) {
kvDoc.value = keyValue.value;
}
kvDocs.push(kvDoc);
}
});
metaDoc.keys = uniq(newKeys.concat(metaDoc.keys));
kvDocs.push(metaDoc);
return kvDocs;
}
return getMetaDoc().then(function (metaDoc) {
return getKeyValueDocs(metaDoc).then(function (kvDocsRes) {
return processKvDocs(metaDoc, kvDocsRes);
});
});
}
// updates all emitted key/value docs and metaDocs in the mrview database
// for the given batch of documents from the source database
function saveKeyValues(view, docIdsToChangesAndEmits, seq) {
var seqDocId = '_local/lastSeq';
return view.db.get(seqDocId)[
"catch"](defaultsTo({_id: seqDocId, seq: 0}))
.then(function (lastSeqDoc) {
var docIds = Object.keys(docIdsToChangesAndEmits);
return PouchPromise.all(docIds.map(function (docId) {
return getDocsToPersist(docId, view, docIdsToChangesAndEmits);
})).then(function (listOfDocsToPersist) {
var docsToPersist = flatten(listOfDocsToPersist);
lastSeqDoc.seq = seq;
docsToPersist.push(lastSeqDoc);
// write all docs in a single operation, update the seq once
return view.db.bulkDocs({docs : docsToPersist});
});
});
}
function getQueue(view) {
var viewName = typeof view === 'string' ? view : view.name;
var queue = persistentQueues[viewName];
if (!queue) {
queue = persistentQueues[viewName] = new TaskQueue$1();
}
return queue;
}
function updateView(view) {
return sequentialize(getQueue(view), function () {
return updateViewInQueue(view);
})();
}
function updateViewInQueue(view) {
// bind the emit function once
var mapResults;
var doc;
function emit(key, value) {
var output = {id: doc._id, key: pouchdbCollate.normalizeKey(key)};
// Don't explicitly store the value unless it's defined and non-null.
// This saves on storage space, because often people don't use it.
if (typeof value !== 'undefined' && value !== null) {
output.value = pouchdbCollate.normalizeKey(value);
}
mapResults.push(output);
}
var mapFun;
// for temp_views one can use emit(doc, emit), see #38
if (typeof view.mapFun === "function" && view.mapFun.length === 2) {
var origMap = view.mapFun;
mapFun = function (doc) {
return origMap(doc, emit);
};
} else {
mapFun = evalfunc(view.mapFun.toString(), emit, sum, log$2, Array.isArray,
JSON.parse);
}
var currentSeq = view.seq || 0;
function processChange(docIdsToChangesAndEmits, seq) {
return function () {
return saveKeyValues(view, docIdsToChangesAndEmits, seq);
};
}
var queue = new TaskQueue$1();
// TODO(neojski): https://github.com/daleharvey/pouchdb/issues/1521
return new PouchPromise(function (resolve, reject) {
function complete() {
queue.finish().then(function () {
view.seq = currentSeq;
resolve();
});
}
function processNextBatch() {
view.sourceDB.changes({
conflicts: true,
include_docs: true,
style: 'all_docs',
since: currentSeq,
limit: CHANGES_BATCH_SIZE$1
}).on('complete', function (response) {
var results = response.results;
if (!results.length) {
return complete();
}
var docIdsToChangesAndEmits = {};
for (var i = 0, l = results.length; i < l; i++) {
var change = results[i];
if (change.doc._id[0] !== '_') {
mapResults = [];
doc = change.doc;
if (!doc._deleted) {
tryCode$1(view.sourceDB, mapFun, [doc]);
}
mapResults.sort(sortByKeyThenValue);
var indexableKeysToKeyValues = {};
var lastKey;
for (var j = 0, jl = mapResults.length; j < jl; j++) {
var obj = mapResults[j];
var complexKey = [obj.key, obj.id];
if (pouchdbCollate.collate(obj.key, lastKey) === 0) {
complexKey.push(j); // dup key+id, so make it unique
}
var indexableKey = pouchdbCollate.toIndexableString(complexKey);
indexableKeysToKeyValues[indexableKey] = obj;
lastKey = obj.key;
}
docIdsToChangesAndEmits[change.doc._id] = {
indexableKeysToKeyValues: indexableKeysToKeyValues,
changes: change.changes
};
}
currentSeq = change.seq;
}
queue.add(processChange(docIdsToChangesAndEmits, currentSeq));
if (results.length < CHANGES_BATCH_SIZE$1) {
return complete();
}
return processNextBatch();
}).on('error', onError);
/* istanbul ignore next */
function onError(err) {
reject(err);
}
}
processNextBatch();
});
}
function reduceView(view, results, options) {
if (options.group_level === 0) {
delete options.group_level;
}
var shouldGroup = options.group || options.group_level;
var reduceFun;
if (builtInReduce[view.reduceFun]) {
reduceFun = builtInReduce[view.reduceFun];
} else {
reduceFun = evalfunc(
view.reduceFun.toString(), null, sum, log$2, Array.isArray, JSON.parse);
}
var groups = [];
var lvl = isNaN(options.group_level) ? Number.POSITIVE_INFINITY :
options.group_level;
results.forEach(function (e) {
var last = groups[groups.length - 1];
var groupKey = shouldGroup ? e.key : null;
// only set group_level for array keys
if (shouldGroup && Array.isArray(groupKey)) {
groupKey = groupKey.slice(0, lvl);
}
if (last && pouchdbCollate.collate(last.groupKey, groupKey) === 0) {
last.keys.push([e.key, e.id]);
last.values.push(e.value);
return;
}
groups.push({
keys: [[e.key, e.id]],
values: [e.value],
groupKey: groupKey
});
});
results = [];
for (var i = 0, len = groups.length; i < len; i++) {
var e = groups[i];
var reduceTry = tryCode$1(view.sourceDB, reduceFun,
[e.keys, e.values, false]);
if (reduceTry.error && reduceTry.error instanceof BuiltInError) {
// CouchDB returns an error if a built-in errors out
throw reduceTry.error;
}
results.push({
// CouchDB just sets the value to null if a non-built-in errors out
value: reduceTry.error ? null : reduceTry.output,
key: e.groupKey
});
}
// no total_rows/offset when reducing
return {rows: sliceResults(results, options.limit, options.skip)};
}
function queryView(view, opts) {
return sequentialize(getQueue(view), function () {
return queryViewInQueue(view, opts);
})();
}
function queryViewInQueue(view, opts) {
var totalRows;
var shouldReduce = view.reduceFun && opts.reduce !== false;
var skip = opts.skip || 0;
if (typeof opts.keys !== 'undefined' && !opts.keys.length) {
// equivalent query
opts.limit = 0;
delete opts.keys;
}
function fetchFromView(viewOpts) {
viewOpts.include_docs = true;
return view.db.allDocs(viewOpts).then(function (res) {
totalRows = res.total_rows;
return res.rows.map(function (result) {
// implicit migration - in older versions of PouchDB,
// we explicitly stored the doc as {id: ..., key: ..., value: ...}
// this is tested in a migration test
/* istanbul ignore next */
if ('value' in result.doc && typeof result.doc.value === 'object' &&
result.doc.value !== null) {
var keys = Object.keys(result.doc.value).sort();
// this detection method is not perfect, but it's unlikely the user
// emitted a value which was an object with these 3 exact keys
var expectedKeys = ['id', 'key', 'value'];
if (!(keys < expectedKeys || keys > expectedKeys)) {
return result.doc.value;
}
}
var parsedKeyAndDocId = pouchdbCollate.parseIndexableString(result.doc._id);
return {
key: parsedKeyAndDocId[0],
id: parsedKeyAndDocId[1],
value: ('value' in result.doc ? result.doc.value : null)
};
});
});
}
function onMapResultsReady(rows) {
var finalResults;
if (shouldReduce) {
finalResults = reduceView(view, rows, opts);
} else {
finalResults = {
total_rows: totalRows,
offset: skip,
rows: rows
};
}
if (opts.include_docs) {
var docIds = uniq(rows.map(rowToDocId));
return view.sourceDB.allDocs({
keys: docIds,
include_docs: true,
conflicts: opts.conflicts,
attachments: opts.attachments,
binary: opts.binary
}).then(function (allDocsRes) {
var docIdsToDocs = {};
allDocsRes.rows.forEach(function (row) {
if (row.doc) {
docIdsToDocs['$' + row.id] = row.doc;
}
});
rows.forEach(function (row) {
var docId = rowToDocId(row);
var doc = docIdsToDocs['$' + docId];
if (doc) {
row.doc = doc;
}
});
return finalResults;
});
} else {
return finalResults;
}
}
if (typeof opts.keys !== 'undefined') {
var keys = opts.keys;
var fetchPromises = keys.map(function (key) {
var viewOpts = {
startkey : pouchdbCollate.toIndexableString([key]),
endkey : pouchdbCollate.toIndexableString([key, {}])
};
return fetchFromView(viewOpts);
});
return PouchPromise.all(fetchPromises).then(flatten).then(onMapResultsReady);
} else { // normal query, no 'keys'
var viewOpts = {
descending : opts.descending
};
if (opts.start_key) {
opts.startkey = opts.start_key;
}
if (opts.end_key) {
opts.endkey = opts.end_key;
}
if (typeof opts.startkey !== 'undefined') {
viewOpts.startkey = opts.descending ?
pouchdbCollate.toIndexableString([opts.startkey, {}]) :
pouchdbCollate.toIndexableString([opts.startkey]);
}
if (typeof opts.endkey !== 'undefined') {
var inclusiveEnd = opts.inclusive_end !== false;
if (opts.descending) {
inclusiveEnd = !inclusiveEnd;
}
viewOpts.endkey = pouchdbCollate.toIndexableString(
inclusiveEnd ? [opts.endkey, {}] : [opts.endkey]);
}
if (typeof opts.key !== 'undefined') {
var keyStart = pouchdbCollate.toIndexableString([opts.key]);
var keyEnd = pouchdbCollate.toIndexableString([opts.key, {}]);
if (viewOpts.descending) {
viewOpts.endkey = keyStart;
viewOpts.startkey = keyEnd;
} else {
viewOpts.startkey = keyStart;
viewOpts.endkey = keyEnd;
}
}
if (!shouldReduce) {
if (typeof opts.limit === 'number') {
viewOpts.limit = opts.limit;
}
viewOpts.skip = skip;
}
return fetchFromView(viewOpts).then(onMapResultsReady);
}
}
function httpViewCleanup(db) {
return db.request({
method: 'POST',
url: '_view_cleanup'
});
}
function localViewCleanup(db) {
return db.get('_local/mrviews').then(function (metaDoc) {
var docsToViews = {};
Object.keys(metaDoc.views).forEach(function (fullViewName) {
var parts = parseViewName(fullViewName);
var designDocName = '_design/' + parts[0];
var viewName = parts[1];
docsToViews[designDocName] = docsToViews[designDocName] || {};
docsToViews[designDocName][viewName] = true;
});
var opts = {
keys : Object.keys(docsToViews),
include_docs : true
};
return db.allDocs(opts).then(function (res) {
var viewsToStatus = {};
res.rows.forEach(function (row) {
var ddocName = row.key.substring(8);
Object.keys(docsToViews[row.key]).forEach(function (viewName) {
var fullViewName = ddocName + '/' + viewName;
/* istanbul ignore if */
if (!metaDoc.views[fullViewName]) {
// new format, without slashes, to support PouchDB 2.2.0
// migration test in pouchdb's browser.migration.js verifies this
fullViewName = viewName;
}
var viewDBNames = Object.keys(metaDoc.views[fullViewName]);
// design doc deleted, or view function nonexistent
var statusIsGood = row.doc && row.doc.views &&
row.doc.views[viewName];
viewDBNames.forEach(function (viewDBName) {
viewsToStatus[viewDBName] =
viewsToStatus[viewDBName] || statusIsGood;
});
});
});
var dbsToDelete = Object.keys(viewsToStatus).filter(
function (viewDBName) { return !viewsToStatus[viewDBName]; });
var destroyPromises = dbsToDelete.map(function (viewDBName) {
return sequentialize(getQueue(viewDBName), function () {
return new db.constructor(viewDBName, db.__opts).destroy();
})();
});
return PouchPromise.all(destroyPromises).then(function () {
return {ok: true};
});
});
}, defaultsTo({ok: true}));
}
var viewCleanup = callbackify(function () {
var db = this;
if (db.type() === 'http') {
return httpViewCleanup(db);
}
/* istanbul ignore next */
if (typeof db._viewCleanup === 'function') {
return customViewCleanup(db);
}
return localViewCleanup(db);
});
function queryPromised(db, fun, opts) {
if (db.type() === 'http') {
return httpQuery(db, fun, opts);
}
/* istanbul ignore next */
if (typeof db._query === 'function') {
return customQuery(db, fun, opts);
}
if (typeof fun !== 'string') {
// temp_view
checkQueryParseError(opts, fun);
var createViewOpts = {
db : db,
viewName : 'temp_view/temp_view',
map : fun.map,
reduce : fun.reduce,
temporary : true
};
tempViewQueue.add(function () {
return createView(createViewOpts).then(function (view) {
function cleanup() {
return view.db.destroy();
}
return fin(updateView(view).then(function () {
return queryView(view, opts);
}), cleanup);
});
});
return tempViewQueue.finish();
} else {
// persistent view
var fullViewName = fun;
var parts = parseViewName(fullViewName);
var designDocName = parts[0];
var viewName = parts[1];
return db.get('_design/' + designDocName).then(function (doc) {
var fun = doc.views && doc.views[viewName];
if (!fun || typeof fun.map !== 'string') {
throw new NotFoundError('ddoc ' + designDocName +
' has no view named ' + viewName);
}
checkQueryParseError(opts, fun);
var createViewOpts = {
db : db,
viewName : fullViewName,
map : fun.map,
reduce : fun.reduce
};
return createView(createViewOpts).then(function (view) {
if (opts.stale === 'ok' || opts.stale === 'update_after') {
if (opts.stale === 'update_after') {
process.nextTick(function () {
updateView(view);
});
}
return queryView(view, opts);
} else { // stale not ok
return updateView(view).then(function () {
return queryView(view, opts);
});
}
});
});
}
}
var query = function (fun, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
opts = opts ? coerceOptions(opts) : {};
if (typeof fun === 'function') {
fun = {map : fun};
}
var db = this;
var promise = PouchPromise.resolve().then(function () {
return queryPromised(db, fun, opts);
});
promisedCallback(promise, callback);
return promise;
};
function QueryParseError(message) {
this.status = 400;
this.name = 'query_parse_error';
this.message = message;
this.error = true;
try {
Error.captureStackTrace(this, QueryParseError);
} catch (e) {}
}
inherits(QueryParseError, Error);
function NotFoundError(message) {
this.status = 404;
this.name = 'not_found';
this.message = message;
this.error = true;
try {
Error.captureStackTrace(this, NotFoundError);
} catch (e) {}
}
inherits(NotFoundError, Error);
function BuiltInError(message) {
this.status = 500;
this.name = 'invalid_value';
this.message = message;
this.error = true;
try {
Error.captureStackTrace(this, BuiltInError);
} catch (e) {}
}
inherits(BuiltInError, Error);
var mapreduce = {
query: query,
viewCleanup: viewCleanup
};
function isGenOne$1(rev) {
return /^1-/.test(rev);
}
function fileHasChanged(localDoc, remoteDoc, filename) {
return !localDoc._attachments ||
!localDoc._attachments[filename] ||
localDoc._attachments[filename].digest !== remoteDoc._attachments[filename].digest;
}
function getDocAttachments(db, doc) {
var filenames = Object.keys(doc._attachments);
return PouchPromise.all(filenames.map(function (filename) {
return db.getAttachment(doc._id, filename, {rev: doc._rev});
}));
}
function getDocAttachmentsFromTargetOrSource(target, src, doc) {
var doCheckForLocalAttachments = src.type() === 'http' && target.type() !== 'http';
var filenames = Object.keys(doc._attachments);
if (!doCheckForLocalAttachments) {
return getDocAttachments(src, doc);
}
return target.get(doc._id).then(function (localDoc) {
return PouchPromise.all(filenames.map(function (filename) {
if (fileHasChanged(localDoc, doc, filename)) {
return src.getAttachment(doc._id, filename);
}
return target.getAttachment(localDoc._id, filename);
}));
})["catch"](function (error) {
/* istanbul ignore if */
if (error.status !== 404) {
throw error;
}
return getDocAttachments(src, doc);
});
}
function createBulkGetOpts(diffs) {
var requests = [];
Object.keys(diffs).forEach(function (id) {
var missingRevs = diffs[id].missing;
missingRevs.forEach(function (missingRev) {
requests.push({
id: id,
rev: missingRev
});
});
});
return {
docs: requests,
revs: true
};
}
//
// Fetch all the documents from the src as described in the "diffs",
// which is a mapping of docs IDs to revisions. If the state ever
// changes to "cancelled", then the returned promise will be rejected.
// Else it will be resolved with a list of fetched documents.
//
function getDocs(src, target, diffs, state) {
diffs = clone(diffs); // we do not need to modify this
var resultDocs = [],
ok = true;
function getAllDocs() {
var bulkGetOpts = createBulkGetOpts(diffs);
if (!bulkGetOpts.docs.length) { // optimization: skip empty requests
return;
}
return src.bulkGet(bulkGetOpts).then(function (bulkGetResponse) {
/* istanbul ignore if */
if (state.cancelled) {
throw new Error('cancelled');
}
return PouchPromise.all(bulkGetResponse.results.map(function (bulkGetInfo) {
return PouchPromise.all(bulkGetInfo.docs.map(function (doc) {
var remoteDoc = doc.ok;
if (doc.error) {
// when AUTO_COMPACTION is set, docs can be returned which look
// like this: {"missing":"1-7c3ac256b693c462af8442f992b83696"}
ok = false;
}
if (!remoteDoc || !remoteDoc._attachments) {
return remoteDoc;
}
return getDocAttachmentsFromTargetOrSource(target, src, remoteDoc).then(function (attachments) {
var filenames = Object.keys(remoteDoc._attachments);
attachments.forEach(function (attachment, i) {
var att = remoteDoc._attachments[filenames[i]];
delete att.stub;
delete att.length;
att.data = attachment;
});
return remoteDoc;
});
}));
}))
.then(function (results) {
resultDocs = resultDocs.concat(flatten(results).filter(Boolean));
});
});
}
function hasAttachments(doc) {
return doc._attachments && Object.keys(doc._attachments).length > 0;
}
function fetchRevisionOneDocs(ids) {
// Optimization: fetch gen-1 docs and attachments in
// a single request using _all_docs
return src.allDocs({
keys: ids,
include_docs: true
}).then(function (res) {
if (state.cancelled) {
throw new Error('cancelled');
}
res.rows.forEach(function (row) {
if (row.deleted || !row.doc || !isGenOne$1(row.value.rev) ||
hasAttachments(row.doc)) {
// if any of these conditions apply, we need to fetch using get()
return;
}
// the doc we got back from allDocs() is sufficient
resultDocs.push(row.doc);
delete diffs[row.id];
});
});
}
function getRevisionOneDocs() {
// filter out the generation 1 docs and get them
// leaving the non-generation one docs to be got otherwise
var ids = Object.keys(diffs).filter(function (id) {
var missing = diffs[id].missing;
return missing.length === 1 && isGenOne$1(missing[0]);
});
if (ids.length > 0) {
return fetchRevisionOneDocs(ids);
}
}
function returnResult() {
return { ok:ok, docs:resultDocs };
}
return PouchPromise.resolve()
.then(getRevisionOneDocs)
.then(getAllDocs)
.then(returnResult);
}
var CHECKPOINT_VERSION = 1;
var REPLICATOR = "pouchdb";
// This is an arbitrary number to limit the
// amount of replication history we save in the checkpoint.
// If we save too much, the checkpoing docs will become very big,
// if we save fewer, we'll run a greater risk of having to
// read all the changes from 0 when checkpoint PUTs fail
// CouchDB 2.0 has a more involved history pruning,
// but let's go for the simple version for now.
var CHECKPOINT_HISTORY_SIZE = 5;
var LOWEST_SEQ = 0;
function updateCheckpoint(db, id, checkpoint, session, returnValue) {
return db.get(id)["catch"](function (err) {
if (err.status === 404) {
if (db.type() === 'http') {
explainError(
404, 'PouchDB is just checking if a remote checkpoint exists.'
);
}
return {
session_id: session,
_id: id,
history: [],
replicator: REPLICATOR,
version: CHECKPOINT_VERSION
};
}
throw err;
}).then(function (doc) {
if (returnValue.cancelled) {
return;
}
// Filter out current entry for this replication
doc.history = (doc.history || []).filter(function (item) {
return item.session_id !== session;
});
// Add the latest checkpoint to history
doc.history.unshift({
last_seq: checkpoint,
session_id: session
});
// Just take the last pieces in history, to
// avoid really big checkpoint docs.
// see comment on history size above
doc.history = doc.history.slice(0, CHECKPOINT_HISTORY_SIZE);
doc.version = CHECKPOINT_VERSION;
doc.replicator = REPLICATOR;
doc.session_id = session;
doc.last_seq = checkpoint;
return db.put(doc)["catch"](function (err) {
if (err.status === 409) {
// retry; someone is trying to write a checkpoint simultaneously
return updateCheckpoint(db, id, checkpoint, session, returnValue);
}
throw err;
});
});
}
function Checkpointer(src, target, id, returnValue) {
this.src = src;
this.target = target;
this.id = id;
this.returnValue = returnValue;
}
Checkpointer.prototype.writeCheckpoint = function (checkpoint, session) {
var self = this;
return this.updateTarget(checkpoint, session).then(function () {
return self.updateSource(checkpoint, session);
});
};
Checkpointer.prototype.updateTarget = function (checkpoint, session) {
return updateCheckpoint(this.target, this.id, checkpoint,
session, this.returnValue);
};
Checkpointer.prototype.updateSource = function (checkpoint, session) {
var self = this;
if (this.readOnlySource) {
return PouchPromise.resolve(true);
}
return updateCheckpoint(this.src, this.id, checkpoint,
session, this.returnValue)[
"catch"](function (err) {
if (isForbiddenError(err)) {
self.readOnlySource = true;
return true;
}
throw err;
});
};
var comparisons = {
"undefined": function (targetDoc, sourceDoc) {
// This is the previous comparison function
if (pouchdbCollate.collate(targetDoc.last_seq, sourceDoc.last_seq) === 0) {
return sourceDoc.last_seq;
}
/* istanbul ignore next */
return 0;
},
"1": function (targetDoc, sourceDoc) {
// This is the comparison function ported from CouchDB
return compareReplicationLogs(sourceDoc, targetDoc).last_seq;
}
};
Checkpointer.prototype.getCheckpoint = function () {
var self = this;
return self.target.get(self.id).then(function (targetDoc) {
if (self.readOnlySource) {
return PouchPromise.resolve(targetDoc.last_seq);
}
return self.src.get(self.id).then(function (sourceDoc) {
// Since we can't migrate an old version doc to a new one
// (no session id), we just go with the lowest seq in this case
/* istanbul ignore if */
if (targetDoc.version !== sourceDoc.version) {
return LOWEST_SEQ;
}
var version;
if (targetDoc.version) {
version = targetDoc.version.toString();
} else {
version = "undefined";
}
if (version in comparisons) {
return comparisons[version](targetDoc, sourceDoc);
}
/* istanbul ignore next */
return LOWEST_SEQ;
}, function (err) {
if (err.status === 404 && targetDoc.last_seq) {
return self.src.put({
_id: self.id,
last_seq: LOWEST_SEQ
}).then(function () {
return LOWEST_SEQ;
}, function (err) {
if (isForbiddenError(err)) {
self.readOnlySource = true;
return targetDoc.last_seq;
}
/* istanbul ignore next */
return LOWEST_SEQ;
});
}
throw err;
});
})["catch"](function (err) {
if (err.status !== 404) {
throw err;
}
return LOWEST_SEQ;
});
};
// This checkpoint comparison is ported from CouchDBs source
// they come from here:
// https://github.com/apache/couchdb-couch-replicator/blob/master/src/couch_replicator.erl#L863-L906
function compareReplicationLogs(srcDoc, tgtDoc) {
if (srcDoc.session_id === tgtDoc.session_id) {
return {
last_seq: srcDoc.last_seq,
history: srcDoc.history
};
}
return compareReplicationHistory(srcDoc.history, tgtDoc.history);
}
function compareReplicationHistory(sourceHistory, targetHistory) {
// the erlang loop via function arguments is not so easy to repeat in JS
// therefore, doing this as recursion
var S = sourceHistory[0];
var sourceRest = sourceHistory.slice(1);
var T = targetHistory[0];
var targetRest = targetHistory.slice(1);
if (!S || targetHistory.length === 0) {
return {
last_seq: LOWEST_SEQ,
history: []
};
}
var sourceId = S.session_id;
/* istanbul ignore if */
if (hasSessionId(sourceId, targetHistory)) {
return {
last_seq: S.last_seq,
history: sourceHistory
};
}
var targetId = T.session_id;
if (hasSessionId(targetId, sourceRest)) {
return {
last_seq: T.last_seq,
history: targetRest
};
}
return compareReplicationHistory(sourceRest, targetRest);
}
function hasSessionId(sessionId, history) {
var props = history[0];
var rest = history.slice(1);
if (!sessionId || history.length === 0) {
return false;
}
if (sessionId === props.session_id) {
return true;
}
return hasSessionId(sessionId, rest);
}
function isForbiddenError(err) {
return typeof err.status === 'number' && Math.floor(err.status / 100) === 4;
}
var STARTING_BACK_OFF = 0;
function backOff(opts, returnValue, error, callback) {
if (opts.retry === false) {
returnValue.emit('error', error);
returnValue.removeAllListeners();
return;
}
if (typeof opts.back_off_function !== 'function') {
opts.back_off_function = defaultBackOff;
}
returnValue.emit('requestError', error);
if (returnValue.state === 'active' || returnValue.state === 'pending') {
returnValue.emit('paused', error);
returnValue.state = 'stopped';
returnValue.once('active', function () {
opts.current_back_off = STARTING_BACK_OFF;
});
}
opts.current_back_off = opts.current_back_off || STARTING_BACK_OFF;
opts.current_back_off = opts.back_off_function(opts.current_back_off);
setTimeout(callback, opts.current_back_off);
}
function sortObjectPropertiesByKey(queryParams) {
return Object.keys(queryParams).sort(pouchdbCollate.collate).reduce(function (result, key) {
result[key] = queryParams[key];
return result;
}, {});
}
// Generate a unique id particular to this replication.
// Not guaranteed to align perfectly with CouchDB's rep ids.
function generateReplicationId(src, target, opts) {
var docIds = opts.doc_ids ? opts.doc_ids.sort(pouchdbCollate.collate) : '';
var filterFun = opts.filter ? opts.filter.toString() : '';
var queryParams = '';
var filterViewName = '';
if (opts.filter && opts.query_params) {
queryParams = JSON.stringify(sortObjectPropertiesByKey(opts.query_params));
}
if (opts.filter && opts.filter === '_view') {
filterViewName = opts.view.toString();
}
return PouchPromise.all([src.id(), target.id()]).then(function (res) {
var queryData = res[0] + res[1] + filterFun + filterViewName +
queryParams + docIds;
return new PouchPromise(function (resolve) {
binaryMd5(queryData, resolve);
});
}).then(function (md5sum) {
// can't use straight-up md5 alphabet, because
// the char '/' is interpreted as being for attachments,
// and + is also not url-safe
md5sum = md5sum.replace(/\//g, '.').replace(/\+/g, '_');
return '_local/' + md5sum;
});
}
function replicate$1(src, target, opts, returnValue, result) {
var batches = []; // list of batches to be processed
var currentBatch; // the batch currently being processed
var pendingBatch = {
seq: 0,
changes: [],
docs: []
}; // next batch, not yet ready to be processed
var writingCheckpoint = false; // true while checkpoint is being written
var changesCompleted = false; // true when all changes received
var replicationCompleted = false; // true when replication has completed
var last_seq = 0;
var continuous = opts.continuous || opts.live || false;
var batch_size = opts.batch_size || 100;
var batches_limit = opts.batches_limit || 10;
var changesPending = false; // true while src.changes is running
var doc_ids = opts.doc_ids;
var repId;
var checkpointer;
var allErrors = [];
var changedDocs = [];
// Like couchdb, every replication gets a unique session id
var session = uuid();
result = result || {
ok: true,
start_time: new Date(),
docs_read: 0,
docs_written: 0,
doc_write_failures: 0,
errors: []
};
var changesOpts = {};
returnValue.ready(src, target);
function initCheckpointer() {
if (checkpointer) {
return PouchPromise.resolve();
}
return generateReplicationId(src, target, opts).then(function (res) {
repId = res;
checkpointer = new Checkpointer(src, target, repId, returnValue);
});
}
function writeDocs() {
changedDocs = [];
if (currentBatch.docs.length === 0) {
return;
}
var docs = currentBatch.docs;
return target.bulkDocs({docs: docs, new_edits: false}).then(function (res) {
/* istanbul ignore if */
if (returnValue.cancelled) {
completeReplication();
throw new Error('cancelled');
}
var errors = [];
var errorsById = {};
res.forEach(function (res) {
if (res.error) {
result.doc_write_failures++;
errors.push(res);
errorsById[res.id] = res;
}
});
allErrors = allErrors.concat(errors);
result.docs_written += currentBatch.docs.length - errors.length;
var non403s = errors.filter(function (error) {
return error.name !== 'unauthorized' && error.name !== 'forbidden';
});
docs.forEach(function (doc) {
var error = errorsById[doc._id];
if (error) {
returnValue.emit('denied', clone(error));
} else {
changedDocs.push(doc);
}
});
if (non403s.length > 0) {
var error = new Error('bulkDocs error');
error.other_errors = errors;
abortReplication('target.bulkDocs failed to write docs', error);
throw new Error('bulkWrite partial failure');
}
}, function (err) {
result.doc_write_failures += docs.length;
throw err;
});
}
function finishBatch() {
if (currentBatch.error) {
throw new Error('There was a problem getting docs.');
}
result.last_seq = last_seq = currentBatch.seq;
var outResult = clone(result);
if (changedDocs.length) {
outResult.docs = changedDocs;
returnValue.emit('change', outResult);
}
writingCheckpoint = true;
return checkpointer.writeCheckpoint(currentBatch.seq,
session).then(function () {
writingCheckpoint = false;
/* istanbul ignore if */
if (returnValue.cancelled) {
completeReplication();
throw new Error('cancelled');
}
currentBatch = undefined;
getChanges();
})["catch"](onCheckpointError);
}
function getDiffs() {
var diff = {};
currentBatch.changes.forEach(function (change) {
// Couchbase Sync Gateway emits these, but we can ignore them
/* istanbul ignore if */
if (change.id === "_user/") {
return;
}
diff[change.id] = change.changes.map(function (x) {
return x.rev;
});
});
return target.revsDiff(diff).then(function (diffs) {
/* istanbul ignore if */
if (returnValue.cancelled) {
completeReplication();
throw new Error('cancelled');
}
// currentBatch.diffs elements are deleted as the documents are written
currentBatch.diffs = diffs;
});
}
function getBatchDocs() {
return getDocs(src, target, currentBatch.diffs, returnValue).then(function (got) {
currentBatch.error = !got.ok;
got.docs.forEach(function (doc) {
delete currentBatch.diffs[doc._id];
result.docs_read++;
currentBatch.docs.push(doc);
});
});
}
function startNextBatch() {
if (returnValue.cancelled || currentBatch) {
return;
}
if (batches.length === 0) {
processPendingBatch(true);
return;
}
currentBatch = batches.shift();
getDiffs()
.then(getBatchDocs)
.then(writeDocs)
.then(finishBatch)
.then(startNextBatch)[
"catch"](function (err) {
abortReplication('batch processing terminated with error', err);
});
}
function processPendingBatch(immediate) {
if (pendingBatch.changes.length === 0) {
if (batches.length === 0 && !currentBatch) {
if ((continuous && changesOpts.live) || changesCompleted) {
returnValue.state = 'pending';
returnValue.emit('paused');
}
if (changesCompleted) {
completeReplication();
}
}
return;
}
if (
immediate ||
changesCompleted ||
pendingBatch.changes.length >= batch_size
) {
batches.push(pendingBatch);
pendingBatch = {
seq: 0,
changes: [],
docs: []
};
if (returnValue.state === 'pending' || returnValue.state === 'stopped') {
returnValue.state = 'active';
returnValue.emit('active');
}
startNextBatch();
}
}
function abortReplication(reason, err) {
if (replicationCompleted) {
return;
}
if (!err.message) {
err.message = reason;
}
result.ok = false;
result.status = 'aborting';
result.errors.push(err);
allErrors = allErrors.concat(err);
batches = [];
pendingBatch = {
seq: 0,
changes: [],
docs: []
};
completeReplication();
}
function completeReplication() {
if (replicationCompleted) {
return;
}
/* istanbul ignore if */
if (returnValue.cancelled) {
result.status = 'cancelled';
if (writingCheckpoint) {
return;
}
}
result.status = result.status || 'complete';
result.end_time = new Date();
result.last_seq = last_seq;
replicationCompleted = true;
var non403s = allErrors.filter(function (error) {
return error.name !== 'unauthorized' && error.name !== 'forbidden';
});
if (non403s.length > 0) {
var error = allErrors.pop();
if (allErrors.length > 0) {
error.other_errors = allErrors;
}
error.result = result;
backOff(opts, returnValue, error, function () {
replicate$1(src, target, opts, returnValue);
});
} else {
result.errors = allErrors;
returnValue.emit('complete', result);
returnValue.removeAllListeners();
}
}
function onChange(change) {
/* istanbul ignore if */
if (returnValue.cancelled) {
return completeReplication();
}
var filter = filterChange(opts)(change);
if (!filter) {
return;
}
pendingBatch.seq = change.seq;
pendingBatch.changes.push(change);
processPendingBatch(batches.length === 0 && changesOpts.live);
}
function onChangesComplete(changes) {
changesPending = false;
/* istanbul ignore if */
if (returnValue.cancelled) {
return completeReplication();
}
// if no results were returned then we're done,
// else fetch more
if (changes.results.length > 0) {
changesOpts.since = changes.last_seq;
getChanges();
processPendingBatch(true);
} else {
var complete = function () {
if (continuous) {
changesOpts.live = true;
getChanges();
} else {
changesCompleted = true;
}
processPendingBatch(true);
};
// update the checkpoint so we start from the right seq next time
if (!currentBatch && changes.results.length === 0) {
writingCheckpoint = true;
checkpointer.writeCheckpoint(changes.last_seq,
session).then(function () {
writingCheckpoint = false;
result.last_seq = last_seq = changes.last_seq;
complete();
})[
"catch"](onCheckpointError);
} else {
complete();
}
}
}
function onChangesError(err) {
changesPending = false;
/* istanbul ignore if */
if (returnValue.cancelled) {
return completeReplication();
}
abortReplication('changes rejected', err);
}
function getChanges() {
if (!(
!changesPending &&
!changesCompleted &&
batches.length < batches_limit
)) {
return;
}
changesPending = true;
function abortChanges() {
changes.cancel();
}
function removeListener() {
returnValue.removeListener('cancel', abortChanges);
}
if (returnValue._changes) { // remove old changes() and listeners
returnValue.removeListener('cancel', returnValue._abortChanges);
returnValue._changes.cancel();
}
returnValue.once('cancel', abortChanges);
var changes = src.changes(changesOpts)
.on('change', onChange);
changes.then(removeListener, removeListener);
changes.then(onChangesComplete)[
"catch"](onChangesError);
if (opts.retry) {
// save for later so we can cancel if necessary
returnValue._changes = changes;
returnValue._abortChanges = abortChanges;
}
}
function startChanges() {
initCheckpointer().then(function () {
/* istanbul ignore if */
if (returnValue.cancelled) {
completeReplication();
return;
}
return checkpointer.getCheckpoint().then(function (checkpoint) {
last_seq = checkpoint;
changesOpts = {
since: last_seq,
limit: batch_size,
batch_size: batch_size,
style: 'all_docs',
doc_ids: doc_ids,
return_docs: true // required so we know when we're done
};
if (opts.filter) {
if (typeof opts.filter !== 'string') {
// required for the client-side filter in onChange
changesOpts.include_docs = true;
} else { // ddoc filter
changesOpts.filter = opts.filter;
}
}
if ('heartbeat' in opts) {
changesOpts.heartbeat = opts.heartbeat;
}
if ('timeout' in opts) {
changesOpts.timeout = opts.timeout;
}
if (opts.query_params) {
changesOpts.query_params = opts.query_params;
}
if (opts.view) {
changesOpts.view = opts.view;
}
getChanges();
});
})["catch"](function (err) {
abortReplication('getCheckpoint rejected with ', err);
});
}
/* istanbul ignore next */
function onCheckpointError(err) {
writingCheckpoint = false;
abortReplication('writeCheckpoint completed with error', err);
throw err;
}
/* istanbul ignore if */
if (returnValue.cancelled) { // cancelled immediately
completeReplication();
return;
}
if (!returnValue._addedListeners) {
returnValue.once('cancel', completeReplication);
if (typeof opts.complete === 'function') {
returnValue.once('error', opts.complete);
returnValue.once('complete', function (result) {
opts.complete(null, result);
});
}
returnValue._addedListeners = true;
}
if (typeof opts.since === 'undefined') {
startChanges();
} else {
initCheckpointer().then(function () {
writingCheckpoint = true;
return checkpointer.writeCheckpoint(opts.since, session);
}).then(function () {
writingCheckpoint = false;
/* istanbul ignore if */
if (returnValue.cancelled) {
completeReplication();
return;
}
last_seq = opts.since;
startChanges();
})["catch"](onCheckpointError);
}
}
// We create a basic promise so the caller can cancel the replication possibly
// before we have actually started listening to changes etc
inherits(Replication, events.EventEmitter);
function Replication() {
events.EventEmitter.call(this);
this.cancelled = false;
this.state = 'pending';
var self = this;
var promise = new PouchPromise(function (fulfill, reject) {
self.once('complete', fulfill);
self.once('error', reject);
});
self.then = function (resolve, reject) {
return promise.then(resolve, reject);
};
self["catch"] = function (reject) {
return promise["catch"](reject);
};
// As we allow error handling via "error" event as well,
// put a stub in here so that rejecting never throws UnhandledError.
self["catch"](function () {});
}
Replication.prototype.cancel = function () {
this.cancelled = true;
this.state = 'cancelled';
this.emit('cancel');
};
Replication.prototype.ready = function (src, target) {
var self = this;
if (self._readyCalled) {
return;
}
self._readyCalled = true;
function onDestroy() {
self.cancel();
}
src.once('destroyed', onDestroy);
target.once('destroyed', onDestroy);
function cleanup() {
src.removeListener('destroyed', onDestroy);
target.removeListener('destroyed', onDestroy);
}
self.once('complete', cleanup);
};
function toPouch(db, opts) {
var PouchConstructor = opts.PouchConstructor;
if (typeof db === 'string') {
return new PouchConstructor(db, opts);
} else {
return db;
}
}
function replicate(src, target, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
if (typeof opts === 'undefined') {
opts = {};
}
if (opts.doc_ids && !Array.isArray(opts.doc_ids)) {
throw createError(BAD_REQUEST,
"`doc_ids` filter parameter is not a list.");
}
opts.complete = callback;
opts = clone(opts);
opts.continuous = opts.continuous || opts.live;
opts.retry = ('retry' in opts) ? opts.retry : false;
/*jshint validthis:true */
opts.PouchConstructor = opts.PouchConstructor || this;
var replicateRet = new Replication(opts);
var srcPouch = toPouch(src, opts);
var targetPouch = toPouch(target, opts);
replicate$1(srcPouch, targetPouch, opts, replicateRet);
return replicateRet;
}
inherits(Sync, events.EventEmitter);
function sync(src, target, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
if (typeof opts === 'undefined') {
opts = {};
}
opts = clone(opts);
/*jshint validthis:true */
opts.PouchConstructor = opts.PouchConstructor || this;
src = toPouch(src, opts);
target = toPouch(target, opts);
return new Sync(src, target, opts, callback);
}
function Sync(src, target, opts, callback) {
var self = this;
this.canceled = false;
var optsPush = opts.push ? jsExtend.extend({}, opts, opts.push) : opts;
var optsPull = opts.pull ? jsExtend.extend({}, opts, opts.pull) : opts;
this.push = replicate(src, target, optsPush);
this.pull = replicate(target, src, optsPull);
this.pushPaused = true;
this.pullPaused = true;
function pullChange(change) {
self.emit('change', {
direction: 'pull',
change: change
});
}
function pushChange(change) {
self.emit('change', {
direction: 'push',
change: change
});
}
function pushDenied(doc) {
self.emit('denied', {
direction: 'push',
doc: doc
});
}
function pullDenied(doc) {
self.emit('denied', {
direction: 'pull',
doc: doc
});
}
function pushPaused() {
self.pushPaused = true;
/* istanbul ignore if */
if (self.pullPaused) {
self.emit('paused');
}
}
function pullPaused() {
self.pullPaused = true;
/* istanbul ignore if */
if (self.pushPaused) {
self.emit('paused');
}
}
function pushActive() {
self.pushPaused = false;
/* istanbul ignore if */
if (self.pullPaused) {
self.emit('active', {
direction: 'push'
});
}
}
function pullActive() {
self.pullPaused = false;
/* istanbul ignore if */
if (self.pushPaused) {
self.emit('active', {
direction: 'pull'
});
}
}
var removed = {};
function removeAll(type) { // type is 'push' or 'pull'
return function (event, func) {
var isChange = event === 'change' &&
(func === pullChange || func === pushChange);
var isDenied = event === 'denied' &&
(func === pullDenied || func === pushDenied);
var isPaused = event === 'paused' &&
(func === pullPaused || func === pushPaused);
var isActive = event === 'active' &&
(func === pullActive || func === pushActive);
if (isChange || isDenied || isPaused || isActive) {
if (!(event in removed)) {
removed[event] = {};
}
removed[event][type] = true;
if (Object.keys(removed[event]).length === 2) {
// both push and pull have asked to be removed
self.removeAllListeners(event);
}
}
};
}
if (opts.live) {
this.push.on('complete', self.pull.cancel.bind(self.pull));
this.pull.on('complete', self.push.cancel.bind(self.push));
}
this.on('newListener', function (event) {
if (event === 'change') {
self.pull.on('change', pullChange);
self.push.on('change', pushChange);
} else if (event === 'denied') {
self.pull.on('denied', pullDenied);
self.push.on('denied', pushDenied);
} else if (event === 'active') {
self.pull.on('active', pullActive);
self.push.on('active', pushActive);
} else if (event === 'paused') {
self.pull.on('paused', pullPaused);
self.push.on('paused', pushPaused);
}
});
this.on('removeListener', function (event) {
if (event === 'change') {
self.pull.removeListener('change', pullChange);
self.push.removeListener('change', pushChange);
} else if (event === 'denied') {
self.pull.removeListener('denied', pullDenied);
self.push.removeListener('denied', pushDenied);
} else if (event === 'active') {
self.pull.removeListener('active', pullActive);
self.push.removeListener('active', pushActive);
} else if (event === 'paused') {
self.pull.removeListener('paused', pullPaused);
self.push.removeListener('paused', pushPaused);
}
});
this.pull.on('removeListener', removeAll('pull'));
this.push.on('removeListener', removeAll('push'));
var promise = PouchPromise.all([
this.push,
this.pull
]).then(function (resp) {
var out = {
push: resp[0],
pull: resp[1]
};
self.emit('complete', out);
if (callback) {
callback(null, out);
}
self.removeAllListeners();
return out;
}, function (err) {
self.cancel();
if (callback) {
// if there's a callback, then the callback can receive
// the error event
callback(err);
} else {
// if there's no callback, then we're safe to emit an error
// event, which would otherwise throw an unhandled error
// due to 'error' being a special event in EventEmitters
self.emit('error', err);
}
self.removeAllListeners();
if (callback) {
// no sense throwing if we're already emitting an 'error' event
throw err;
}
});
this.then = function (success, err) {
return promise.then(success, err);
};
this["catch"] = function (err) {
return promise["catch"](err);
};
}
Sync.prototype.cancel = function () {
if (!this.canceled) {
this.canceled = true;
this.push.cancel();
this.pull.cancel();
}
};
function replication(PouchDB) {
PouchDB.replicate = replicate;
PouchDB.sync = sync;
}
PouchDB.plugin(IDBPouch)
.plugin(WebSqlPouch)
.plugin(HttpPouch$1)
.plugin(mapreduce)
.plugin(replication);
module.exports = PouchDB;
}).call(this,_dereq_(2),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"1":1,"10":10,"12":12,"14":14,"15":15,"16":16,"17":17,"2":2,"4":4,"5":5,"8":8,"9":9}],4:[function(_dereq_,module,exports){
'use strict';
module.exports = argsArray;
function argsArray(fun) {
return function () {
var len = arguments.length;
if (len) {
var args = [];
var i = -1;
while (++i < len) {
args[i] = arguments[i];
}
return fun.call(this, args);
} else {
return fun.call(this, []);
}
};
}
},{}],5:[function(_dereq_,module,exports){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = _dereq_(6);
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// is webkit? http://stackoverflow.com/a/16459606/376773
return ('WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
return JSON.stringify(v);
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs() {
var args = arguments;
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return args;
var c = 'color: ' + this.color;
args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
return args;
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage(){
try {
return window.localStorage;
} catch (e) {}
}
},{"6":6}],6:[function(_dereq_,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = _dereq_(11);
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lowercased letter, i.e. "n".
*/
exports.formatters = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function selectColor() {
return exports.colors[prevColor++ % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function debug(namespace) {
// define the `disabled` version
function disabled() {
}
disabled.enabled = false;
// define the `enabled` version
function enabled() {
var self = enabled;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// add the `color` if not set
if (null == self.useColors) self.useColors = exports.useColors();
if (null == self.color && self.useColors) self.color = selectColor();
var args = Array.prototype.slice.call(arguments);
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %o
args = ['%o'].concat(args);
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
if ('function' === typeof exports.formatArgs) {
args = exports.formatArgs.apply(self, args);
}
var logFn = enabled.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
enabled.enabled = true;
var fn = exports.enabled(namespace) ? enabled : disabled;
fn.namespace = namespace;
return fn;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
},{"11":11}],7:[function(_dereq_,module,exports){
(function (global){
'use strict';
var Mutation = global.MutationObserver || global.WebKitMutationObserver;
var scheduleDrain;
{
if (Mutation) {
var called = 0;
var observer = new Mutation(nextTick);
var element = global.document.createTextNode('');
observer.observe(element, {
characterData: true
});
scheduleDrain = function () {
element.data = (called = ++called % 2);
};
} else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
var channel = new global.MessageChannel();
channel.port1.onmessage = nextTick;
scheduleDrain = function () {
channel.port2.postMessage(0);
};
} else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
scheduleDrain = function () {
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
var scriptEl = global.document.createElement('script');
scriptEl.onreadystatechange = function () {
nextTick();
scriptEl.onreadystatechange = null;
scriptEl.parentNode.removeChild(scriptEl);
scriptEl = null;
};
global.document.documentElement.appendChild(scriptEl);
};
} else {
scheduleDrain = function () {
setTimeout(nextTick, 0);
};
}
}
var draining;
var queue = [];
//named nextTick for less confusing stack traces
function nextTick() {
draining = true;
var i, oldQueue;
var len = queue.length;
while (len) {
oldQueue = queue;
queue = [];
i = -1;
while (++i < len) {
oldQueue[i]();
}
len = queue.length;
}
draining = false;
}
module.exports = immediate;
function immediate(task) {
if (queue.push(task) === 1 && !draining) {
scheduleDrain();
}
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],8:[function(_dereq_,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],9:[function(_dereq_,module,exports){
(function() {
var slice = Array.prototype.slice,
each = Array.prototype.forEach;
var extend = function(obj) {
if(typeof obj !== 'object') throw obj + ' is not an object' ;
var sources = slice.call(arguments, 1);
each.call(sources, function(source) {
if(source) {
for(var prop in source) {
if(typeof source[prop] === 'object' && obj[prop]) {
extend.call(obj, obj[prop], source[prop]);
} else {
obj[prop] = source[prop];
}
}
}
});
return obj;
}
this.extend = extend;
}).call(this);
},{}],10:[function(_dereq_,module,exports){
'use strict';
var immediate = _dereq_(7);
/* istanbul ignore next */
function INTERNAL() {}
var handlers = {};
var REJECTED = ['REJECTED'];
var FULFILLED = ['FULFILLED'];
var PENDING = ['PENDING'];
module.exports = Promise;
function Promise(resolver) {
if (typeof resolver !== 'function') {
throw new TypeError('resolver must be a function');
}
this.state = PENDING;
this.queue = [];
this.outcome = void 0;
if (resolver !== INTERNAL) {
safelyResolveThenable(this, resolver);
}
}
Promise.prototype["catch"] = function (onRejected) {
return this.then(null, onRejected);
};
Promise.prototype.then = function (onFulfilled, onRejected) {
if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
typeof onRejected !== 'function' && this.state === REJECTED) {
return this;
}
var promise = new this.constructor(INTERNAL);
if (this.state !== PENDING) {
var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
unwrap(promise, resolver, this.outcome);
} else {
this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
}
return promise;
};
function QueueItem(promise, onFulfilled, onRejected) {
this.promise = promise;
if (typeof onFulfilled === 'function') {
this.onFulfilled = onFulfilled;
this.callFulfilled = this.otherCallFulfilled;
}
if (typeof onRejected === 'function') {
this.onRejected = onRejected;
this.callRejected = this.otherCallRejected;
}
}
QueueItem.prototype.callFulfilled = function (value) {
handlers.resolve(this.promise, value);
};
QueueItem.prototype.otherCallFulfilled = function (value) {
unwrap(this.promise, this.onFulfilled, value);
};
QueueItem.prototype.callRejected = function (value) {
handlers.reject(this.promise, value);
};
QueueItem.prototype.otherCallRejected = function (value) {
unwrap(this.promise, this.onRejected, value);
};
function unwrap(promise, func, value) {
immediate(function () {
var returnValue;
try {
returnValue = func(value);
} catch (e) {
return handlers.reject(promise, e);
}
if (returnValue === promise) {
handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
} else {
handlers.resolve(promise, returnValue);
}
});
}
handlers.resolve = function (self, value) {
var result = tryCatch(getThen, value);
if (result.status === 'error') {
return handlers.reject(self, result.value);
}
var thenable = result.value;
if (thenable) {
safelyResolveThenable(self, thenable);
} else {
self.state = FULFILLED;
self.outcome = value;
var i = -1;
var len = self.queue.length;
while (++i < len) {
self.queue[i].callFulfilled(value);
}
}
return self;
};
handlers.reject = function (self, error) {
self.state = REJECTED;
self.outcome = error;
var i = -1;
var len = self.queue.length;
while (++i < len) {
self.queue[i].callRejected(error);
}
return self;
};
function getThen(obj) {
// Make sure we only access the accessor once as required by the spec
var then = obj && obj.then;
if (obj && typeof obj === 'object' && typeof then === 'function') {
return function appyThen() {
then.apply(obj, arguments);
};
}
}
function safelyResolveThenable(self, thenable) {
// Either fulfill, reject or reject with error
var called = false;
function onError(value) {
if (called) {
return;
}
called = true;
handlers.reject(self, value);
}
function onSuccess(value) {
if (called) {
return;
}
called = true;
handlers.resolve(self, value);
}
function tryToUnwrap() {
thenable(onSuccess, onError);
}
var result = tryCatch(tryToUnwrap);
if (result.status === 'error') {
onError(result.value);
}
}
function tryCatch(func, value) {
var out = {};
try {
out.value = func(value);
out.status = 'success';
} catch (e) {
out.status = 'error';
out.value = e;
}
return out;
}
Promise.resolve = resolve;
function resolve(value) {
if (value instanceof this) {
return value;
}
return handlers.resolve(new this(INTERNAL), value);
}
Promise.reject = reject;
function reject(reason) {
var promise = new this(INTERNAL);
return handlers.reject(promise, reason);
}
Promise.all = all;
function all(iterable) {
var self = this;
if (Object.prototype.toString.call(iterable) !== '[object Array]') {
return this.reject(new TypeError('must be an array'));
}
var len = iterable.length;
var called = false;
if (!len) {
return this.resolve([]);
}
var values = new Array(len);
var resolved = 0;
var i = -1;
var promise = new this(INTERNAL);
while (++i < len) {
allResolver(iterable[i], i);
}
return promise;
function allResolver(value, i) {
self.resolve(value).then(resolveFromAll, function (error) {
if (!called) {
called = true;
handlers.reject(promise, error);
}
});
function resolveFromAll(outValue) {
values[i] = outValue;
if (++resolved === len && !called) {
called = true;
handlers.resolve(promise, values);
}
}
}
}
Promise.race = race;
function race(iterable) {
var self = this;
if (Object.prototype.toString.call(iterable) !== '[object Array]') {
return this.reject(new TypeError('must be an array'));
}
var len = iterable.length;
var called = false;
if (!len) {
return this.resolve([]);
}
var i = -1;
var promise = new this(INTERNAL);
while (++i < len) {
resolver(iterable[i]);
}
return promise;
function resolver(value) {
self.resolve(value).then(function (response) {
if (!called) {
called = true;
handlers.resolve(promise, response);
}
}, function (error) {
if (!called) {
called = true;
handlers.reject(promise, error);
}
});
}
}
},{"7":7}],11:[function(_dereq_,module,exports){
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} options
* @return {String|Number}
* @api public
*/
module.exports = function(val, options){
options = options || {};
if ('string' == typeof val) return parse(val);
return options.long
? long(val)
: short(val);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = '' + str;
if (str.length > 10000) return;
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
if (!match) return;
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function short(ms) {
if (ms >= d) return Math.round(ms / d) + 'd';
if (ms >= h) return Math.round(ms / h) + 'h';
if (ms >= m) return Math.round(ms / m) + 'm';
if (ms >= s) return Math.round(ms / s) + 's';
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function long(ms) {
return plural(ms, d, 'day')
|| plural(ms, h, 'hour')
|| plural(ms, m, 'minute')
|| plural(ms, s, 'second')
|| ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) return;
if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
return Math.ceil(ms / n) + ' ' + name + 's';
}
},{}],12:[function(_dereq_,module,exports){
'use strict';
var MIN_MAGNITUDE = -324; // verified by -Number.MIN_VALUE
var MAGNITUDE_DIGITS = 3; // ditto
var SEP = ''; // set to '_' for easier debugging
var utils = _dereq_(13);
exports.collate = function (a, b) {
if (a === b) {
return 0;
}
a = exports.normalizeKey(a);
b = exports.normalizeKey(b);
var ai = collationIndex(a);
var bi = collationIndex(b);
if ((ai - bi) !== 0) {
return ai - bi;
}
if (a === null) {
return 0;
}
switch (typeof a) {
case 'number':
return a - b;
case 'boolean':
return a === b ? 0 : (a < b ? -1 : 1);
case 'string':
return stringCollate(a, b);
}
return Array.isArray(a) ? arrayCollate(a, b) : objectCollate(a, b);
};
// couch considers null/NaN/Infinity/-Infinity === undefined,
// for the purposes of mapreduce indexes. also, dates get stringified.
exports.normalizeKey = function (key) {
switch (typeof key) {
case 'undefined':
return null;
case 'number':
if (key === Infinity || key === -Infinity || isNaN(key)) {
return null;
}
return key;
case 'object':
var origKey = key;
if (Array.isArray(key)) {
var len = key.length;
key = new Array(len);
for (var i = 0; i < len; i++) {
key[i] = exports.normalizeKey(origKey[i]);
}
} else if (key instanceof Date) {
return key.toJSON();
} else if (key !== null) { // generic object
key = {};
for (var k in origKey) {
if (origKey.hasOwnProperty(k)) {
var val = origKey[k];
if (typeof val !== 'undefined') {
key[k] = exports.normalizeKey(val);
}
}
}
}
}
return key;
};
function indexify(key) {
if (key !== null) {
switch (typeof key) {
case 'boolean':
return key ? 1 : 0;
case 'number':
return numToIndexableString(key);
case 'string':
// We've to be sure that key does not contain \u0000
// Do order-preserving replacements:
// 0 -> 1, 1
// 1 -> 1, 2
// 2 -> 2, 2
return key
.replace(/\u0002/g, '\u0002\u0002')
.replace(/\u0001/g, '\u0001\u0002')
.replace(/\u0000/g, '\u0001\u0001');
case 'object':
var isArray = Array.isArray(key);
var arr = isArray ? key : Object.keys(key);
var i = -1;
var len = arr.length;
var result = '';
if (isArray) {
while (++i < len) {
result += exports.toIndexableString(arr[i]);
}
} else {
while (++i < len) {
var objKey = arr[i];
result += exports.toIndexableString(objKey) +
exports.toIndexableString(key[objKey]);
}
}
return result;
}
}
return '';
}
// convert the given key to a string that would be appropriate
// for lexical sorting, e.g. within a database, where the
// sorting is the same given by the collate() function.
exports.toIndexableString = function (key) {
var zero = '\u0000';
key = exports.normalizeKey(key);
return collationIndex(key) + SEP + indexify(key) + zero;
};
function parseNumber(str, i) {
var originalIdx = i;
var num;
var zero = str[i] === '1';
if (zero) {
num = 0;
i++;
} else {
var neg = str[i] === '0';
i++;
var numAsString = '';
var magAsString = str.substring(i, i + MAGNITUDE_DIGITS);
var magnitude = parseInt(magAsString, 10) + MIN_MAGNITUDE;
if (neg) {
magnitude = -magnitude;
}
i += MAGNITUDE_DIGITS;
while (true) {
var ch = str[i];
if (ch === '\u0000') {
break;
} else {
numAsString += ch;
}
i++;
}
numAsString = numAsString.split('.');
if (numAsString.length === 1) {
num = parseInt(numAsString, 10);
} else {
num = parseFloat(numAsString[0] + '.' + numAsString[1]);
}
if (neg) {
num = num - 10;
}
if (magnitude !== 0) {
// parseFloat is more reliable than pow due to rounding errors
// e.g. Number.MAX_VALUE would return Infinity if we did
// num * Math.pow(10, magnitude);
num = parseFloat(num + 'e' + magnitude);
}
}
return {num: num, length : i - originalIdx};
}
// move up the stack while parsing
// this function moved outside of parseIndexableString for performance
function pop(stack, metaStack) {
var obj = stack.pop();
if (metaStack.length) {
var lastMetaElement = metaStack[metaStack.length - 1];
if (obj === lastMetaElement.element) {
// popping a meta-element, e.g. an object whose value is another object
metaStack.pop();
lastMetaElement = metaStack[metaStack.length - 1];
}
var element = lastMetaElement.element;
var lastElementIndex = lastMetaElement.index;
if (Array.isArray(element)) {
element.push(obj);
} else if (lastElementIndex === stack.length - 2) { // obj with key+value
var key = stack.pop();
element[key] = obj;
} else {
stack.push(obj); // obj with key only
}
}
}
exports.parseIndexableString = function (str) {
var stack = [];
var metaStack = []; // stack for arrays and objects
var i = 0;
while (true) {
var collationIndex = str[i++];
if (collationIndex === '\u0000') {
if (stack.length === 1) {
return stack.pop();
} else {
pop(stack, metaStack);
continue;
}
}
switch (collationIndex) {
case '1':
stack.push(null);
break;
case '2':
stack.push(str[i] === '1');
i++;
break;
case '3':
var parsedNum = parseNumber(str, i);
stack.push(parsedNum.num);
i += parsedNum.length;
break;
case '4':
var parsedStr = '';
while (true) {
var ch = str[i];
if (ch === '\u0000') {
break;
}
parsedStr += ch;
i++;
}
// perform the reverse of the order-preserving replacement
// algorithm (see above)
parsedStr = parsedStr.replace(/\u0001\u0001/g, '\u0000')
.replace(/\u0001\u0002/g, '\u0001')
.replace(/\u0002\u0002/g, '\u0002');
stack.push(parsedStr);
break;
case '5':
var arrayElement = { element: [], index: stack.length };
stack.push(arrayElement.element);
metaStack.push(arrayElement);
break;
case '6':
var objElement = { element: {}, index: stack.length };
stack.push(objElement.element);
metaStack.push(objElement);
break;
default:
throw new Error(
'bad collationIndex or unexpectedly reached end of input: ' + collationIndex);
}
}
};
function arrayCollate(a, b) {
var len = Math.min(a.length, b.length);
for (var i = 0; i < len; i++) {
var sort = exports.collate(a[i], b[i]);
if (sort !== 0) {
return sort;
}
}
return (a.length === b.length) ? 0 :
(a.length > b.length) ? 1 : -1;
}
function stringCollate(a, b) {
// See: https://github.com/daleharvey/pouchdb/issues/40
// This is incompatible with the CouchDB implementation, but its the
// best we can do for now
return (a === b) ? 0 : ((a > b) ? 1 : -1);
}
function objectCollate(a, b) {
var ak = Object.keys(a), bk = Object.keys(b);
var len = Math.min(ak.length, bk.length);
for (var i = 0; i < len; i++) {
// First sort the keys
var sort = exports.collate(ak[i], bk[i]);
if (sort !== 0) {
return sort;
}
// if the keys are equal sort the values
sort = exports.collate(a[ak[i]], b[bk[i]]);
if (sort !== 0) {
return sort;
}
}
return (ak.length === bk.length) ? 0 :
(ak.length > bk.length) ? 1 : -1;
}
// The collation is defined by erlangs ordered terms
// the atoms null, true, false come first, then numbers, strings,
// arrays, then objects
// null/undefined/NaN/Infinity/-Infinity are all considered null
function collationIndex(x) {
var id = ['boolean', 'number', 'string', 'object'];
var idx = id.indexOf(typeof x);
//false if -1 otherwise true, but fast!!!!1
if (~idx) {
if (x === null) {
return 1;
}
if (Array.isArray(x)) {
return 5;
}
return idx < 3 ? (idx + 2) : (idx + 3);
}
if (Array.isArray(x)) {
return 5;
}
}
// conversion:
// x yyy zz...zz
// x = 0 for negative, 1 for 0, 2 for positive
// y = exponent (for negative numbers negated) moved so that it's >= 0
// z = mantisse
function numToIndexableString(num) {
if (num === 0) {
return '1';
}
// convert number to exponential format for easier and
// more succinct string sorting
var expFormat = num.toExponential().split(/e\+?/);
var magnitude = parseInt(expFormat[1], 10);
var neg = num < 0;
var result = neg ? '0' : '2';
// first sort by magnitude
// it's easier if all magnitudes are positive
var magForComparison = ((neg ? -magnitude : magnitude) - MIN_MAGNITUDE);
var magString = utils.padLeft((magForComparison).toString(), '0', MAGNITUDE_DIGITS);
result += SEP + magString;
// then sort by the factor
var factor = Math.abs(parseFloat(expFormat[0])); // [1..10)
if (neg) { // for negative reverse ordering
factor = 10 - factor;
}
var factorStr = factor.toFixed(20);
// strip zeros from the end
factorStr = factorStr.replace(/\.?0+$/, '');
result += SEP + factorStr;
return result;
}
},{"13":13}],13:[function(_dereq_,module,exports){
'use strict';
function pad(str, padWith, upToLength) {
var padding = '';
var targetLength = upToLength - str.length;
while (padding.length < targetLength) {
padding += padWith;
}
return padding;
}
exports.padLeft = function (str, padWith, upToLength) {
var padding = pad(str, padWith, upToLength);
return padding + str;
};
exports.padRight = function (str, padWith, upToLength) {
var padding = pad(str, padWith, upToLength);
return str + padding;
};
exports.stringLexCompare = function (a, b) {
var aLen = a.length;
var bLen = b.length;
var i;
for (i = 0; i < aLen; i++) {
if (i === bLen) {
// b is shorter substring of a
return 1;
}
var aChar = a.charAt(i);
var bChar = b.charAt(i);
if (aChar !== bChar) {
return aChar < bChar ? -1 : 1;
}
}
if (aLen < bLen) {
// a is shorter substring of b
return -1;
}
return 0;
};
/*
* returns the decimal form for the given integer, i.e. writes
* out all the digits (in base-10) instead of using scientific notation
*/
exports.intToDecimalForm = function (int) {
var isNeg = int < 0;
var result = '';
do {
var remainder = isNeg ? -Math.ceil(int % 10) : Math.floor(int % 10);
result = remainder + result;
int = isNeg ? Math.ceil(int / 10) : Math.floor(int / 10);
} while (int);
if (isNeg && result !== '0') {
result = '-' + result;
}
return result;
};
},{}],14:[function(_dereq_,module,exports){
'use strict';
exports.Map = LazyMap; // TODO: use ES6 map
exports.Set = LazySet; // TODO: use ES6 set
// based on https://github.com/montagejs/collections
function LazyMap() {
this.store = {};
}
LazyMap.prototype.mangle = function (key) {
if (typeof key !== "string") {
throw new TypeError("key must be a string but Got " + key);
}
return '$' + key;
};
LazyMap.prototype.unmangle = function (key) {
return key.substring(1);
};
LazyMap.prototype.get = function (key) {
var mangled = this.mangle(key);
if (mangled in this.store) {
return this.store[mangled];
}
return void 0;
};
LazyMap.prototype.set = function (key, value) {
var mangled = this.mangle(key);
this.store[mangled] = value;
return true;
};
LazyMap.prototype.has = function (key) {
var mangled = this.mangle(key);
return mangled in this.store;
};
LazyMap.prototype.delete = function (key) {
var mangled = this.mangle(key);
if (mangled in this.store) {
delete this.store[mangled];
return true;
}
return false;
};
LazyMap.prototype.forEach = function (cb) {
var keys = Object.keys(this.store);
for (var i = 0, len = keys.length; i < len; i++) {
var key = keys[i];
var value = this.store[key];
key = this.unmangle(key);
cb(value, key);
}
};
function LazySet(array) {
this.store = new LazyMap();
// init with an array
if (array && Array.isArray(array)) {
for (var i = 0, len = array.length; i < len; i++) {
this.add(array[i]);
}
}
}
LazySet.prototype.add = function (key) {
return this.store.set(key, true);
};
LazySet.prototype.has = function (key) {
return this.store.has(key);
};
LazySet.prototype.delete = function (key) {
return this.store.delete(key);
};
},{}],15:[function(_dereq_,module,exports){
// Generated by CoffeeScript 1.9.2
(function() {
var hasProp = {}.hasOwnProperty,
slice = [].slice;
module.exports = function(source, scope) {
var key, keys, value, values;
keys = [];
values = [];
for (key in scope) {
if (!hasProp.call(scope, key)) continue;
value = scope[key];
if (key === 'this') {
continue;
}
keys.push(key);
values.push(value);
}
return Function.apply(null, slice.call(keys).concat([source])).apply(scope["this"], values);
};
}).call(this);
},{}],16:[function(_dereq_,module,exports){
(function (factory) {
if (typeof exports === 'object') {
// Node/CommonJS
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
// AMD
define(factory);
} else {
// Browser globals (with support for web workers)
var glob;
try {
glob = window;
} catch (e) {
glob = self;
}
glob.SparkMD5 = factory();
}
}(function (undefined) {
'use strict';
/*
* Fastest md5 implementation around (JKM md5).
* Credits: Joseph Myers
*
* @see http://www.myersdaily.org/joseph/javascript/md5-text.html
* @see http://jsperf.com/md5-shootout/7
*/
/* this function is much faster,
so if possible we use it. Some IEs
are the only ones I know of that
need the idiotic second function,
generated by an if clause. */
var add32 = function (a, b) {
return (a + b) & 0xFFFFFFFF;
},
hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
function cmn(q, a, b, x, s, t) {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
}
function ff(a, b, c, d, x, s, t) {
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function gg(a, b, c, d, x, s, t) {
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function hh(a, b, c, d, x, s, t) {
return cmn(b ^ c ^ d, a, b, x, s, t);
}
function ii(a, b, c, d, x, s, t) {
return cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function md5cycle(x, k) {
var a = x[0],
b = x[1],
c = x[2],
d = x[3];
a = ff(a, b, c, d, k[0], 7, -680876936);
d = ff(d, a, b, c, k[1], 12, -389564586);
c = ff(c, d, a, b, k[2], 17, 606105819);
b = ff(b, c, d, a, k[3], 22, -1044525330);
a = ff(a, b, c, d, k[4], 7, -176418897);
d = ff(d, a, b, c, k[5], 12, 1200080426);
c = ff(c, d, a, b, k[6], 17, -1473231341);
b = ff(b, c, d, a, k[7], 22, -45705983);
a = ff(a, b, c, d, k[8], 7, 1770035416);
d = ff(d, a, b, c, k[9], 12, -1958414417);
c = ff(c, d, a, b, k[10], 17, -42063);
b = ff(b, c, d, a, k[11], 22, -1990404162);
a = ff(a, b, c, d, k[12], 7, 1804603682);
d = ff(d, a, b, c, k[13], 12, -40341101);
c = ff(c, d, a, b, k[14], 17, -1502002290);
b = ff(b, c, d, a, k[15], 22, 1236535329);
a = gg(a, b, c, d, k[1], 5, -165796510);
d = gg(d, a, b, c, k[6], 9, -1069501632);
c = gg(c, d, a, b, k[11], 14, 643717713);
b = gg(b, c, d, a, k[0], 20, -373897302);
a = gg(a, b, c, d, k[5], 5, -701558691);
d = gg(d, a, b, c, k[10], 9, 38016083);
c = gg(c, d, a, b, k[15], 14, -660478335);
b = gg(b, c, d, a, k[4], 20, -405537848);
a = gg(a, b, c, d, k[9], 5, 568446438);
d = gg(d, a, b, c, k[14], 9, -1019803690);
c = gg(c, d, a, b, k[3], 14, -187363961);
b = gg(b, c, d, a, k[8], 20, 1163531501);
a = gg(a, b, c, d, k[13], 5, -1444681467);
d = gg(d, a, b, c, k[2], 9, -51403784);
c = gg(c, d, a, b, k[7], 14, 1735328473);
b = gg(b, c, d, a, k[12], 20, -1926607734);
a = hh(a, b, c, d, k[5], 4, -378558);
d = hh(d, a, b, c, k[8], 11, -2022574463);
c = hh(c, d, a, b, k[11], 16, 1839030562);
b = hh(b, c, d, a, k[14], 23, -35309556);
a = hh(a, b, c, d, k[1], 4, -1530992060);
d = hh(d, a, b, c, k[4], 11, 1272893353);
c = hh(c, d, a, b, k[7], 16, -155497632);
b = hh(b, c, d, a, k[10], 23, -1094730640);
a = hh(a, b, c, d, k[13], 4, 681279174);
d = hh(d, a, b, c, k[0], 11, -358537222);
c = hh(c, d, a, b, k[3], 16, -722521979);
b = hh(b, c, d, a, k[6], 23, 76029189);
a = hh(a, b, c, d, k[9], 4, -640364487);
d = hh(d, a, b, c, k[12], 11, -421815835);
c = hh(c, d, a, b, k[15], 16, 530742520);
b = hh(b, c, d, a, k[2], 23, -995338651);
a = ii(a, b, c, d, k[0], 6, -198630844);
d = ii(d, a, b, c, k[7], 10, 1126891415);
c = ii(c, d, a, b, k[14], 15, -1416354905);
b = ii(b, c, d, a, k[5], 21, -57434055);
a = ii(a, b, c, d, k[12], 6, 1700485571);
d = ii(d, a, b, c, k[3], 10, -1894986606);
c = ii(c, d, a, b, k[10], 15, -1051523);
b = ii(b, c, d, a, k[1], 21, -2054922799);
a = ii(a, b, c, d, k[8], 6, 1873313359);
d = ii(d, a, b, c, k[15], 10, -30611744);
c = ii(c, d, a, b, k[6], 15, -1560198380);
b = ii(b, c, d, a, k[13], 21, 1309151649);
a = ii(a, b, c, d, k[4], 6, -145523070);
d = ii(d, a, b, c, k[11], 10, -1120210379);
c = ii(c, d, a, b, k[2], 15, 718787259);
b = ii(b, c, d, a, k[9], 21, -343485551);
x[0] = add32(a, x[0]);
x[1] = add32(b, x[1]);
x[2] = add32(c, x[2]);
x[3] = add32(d, x[3]);
}
function md5blk(s) {
var md5blks = [],
i; /* Andy King said do it this way. */
for (i = 0; i < 64; i += 4) {
md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
}
return md5blks;
}
function md5blk_array(a) {
var md5blks = [],
i; /* Andy King said do it this way. */
for (i = 0; i < 64; i += 4) {
md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
}
return md5blks;
}
function md51(s) {
var n = s.length,
state = [1732584193, -271733879, -1732584194, 271733878],
i,
length,
tail,
tmp,
lo,
hi;
for (i = 64; i <= n; i += 64) {
md5cycle(state, md5blk(s.substring(i - 64, i)));
}
s = s.substring(i - 64);
length = s.length;
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
}
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Beware that the final length might not fit in 32 bits so we take care of that
tmp = n * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(state, tail);
return state;
}
function md51_array(a) {
var n = a.length,
state = [1732584193, -271733879, -1732584194, 271733878],
i,
length,
tail,
tmp,
lo,
hi;
for (i = 64; i <= n; i += 64) {
md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
}
// Not sure if it is a bug, however IE10 will always produce a sub array of length 1
// containing the last element of the parent array if the sub array specified starts
// beyond the length of the parent array - weird.
// https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
length = a.length;
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= a[i] << ((i % 4) << 3);
}
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Beware that the final length might not fit in 32 bits so we take care of that
tmp = n * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(state, tail);
return state;
}
function rhex(n) {
var s = '',
j;
for (j = 0; j < 4; j += 1) {
s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
}
return s;
}
function hex(x) {
var i;
for (i = 0; i < x.length; i += 1) {
x[i] = rhex(x[i]);
}
return x.join('');
}
// In some cases the fast add32 function cannot be used..
if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
add32 = function (x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
};
}
// ---------------------------------------------------
/**
* ArrayBuffer slice polyfill.
*
* @see https://github.com/ttaubert/node-arraybuffer-slice
*/
if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
(function () {
function clamp(val, length) {
val = (val | 0) || 0;
if (val < 0) {
return Math.max(val + length, 0);
}
return Math.min(val, length);
}
ArrayBuffer.prototype.slice = function (from, to) {
var length = this.byteLength,
begin = clamp(from, length),
end = length,
num,
target,
targetArray,
sourceArray;
if (to !== undefined) {
end = clamp(to, length);
}
if (begin > end) {
return new ArrayBuffer(0);
}
num = end - begin;
target = new ArrayBuffer(num);
targetArray = new Uint8Array(target);
sourceArray = new Uint8Array(this, begin, num);
targetArray.set(sourceArray);
return target;
};
})();
}
// ---------------------------------------------------
/**
* Helpers.
*/
function toUtf8(str) {
if (/[\u0080-\uFFFF]/.test(str)) {
str = unescape(encodeURIComponent(str));
}
return str;
}
function utf8Str2ArrayBuffer(str, returnUInt8Array) {
var length = str.length,
buff = new ArrayBuffer(length),
arr = new Uint8Array(buff),
i;
for (i = 0; i < length; i += 1) {
arr[i] = str.charCodeAt(i);
}
return returnUInt8Array ? arr : buff;
}
function arrayBuffer2Utf8Str(buff) {
return String.fromCharCode.apply(null, new Uint8Array(buff));
}
function concatenateArrayBuffers(first, second, returnUInt8Array) {
var result = new Uint8Array(first.byteLength + second.byteLength);
result.set(new Uint8Array(first));
result.set(new Uint8Array(second), first.byteLength);
return returnUInt8Array ? result : result.buffer;
}
function hexToBinaryString(hex) {
var bytes = [],
length = hex.length,
x;
for (x = 0; x < length - 1; x += 2) {
bytes.push(parseInt(hex.substr(x, 2), 16));
}
return String.fromCharCode.apply(String, bytes);
}
// ---------------------------------------------------
/**
* SparkMD5 OOP implementation.
*
* Use this class to perform an incremental md5, otherwise use the
* static methods instead.
*/
function SparkMD5() {
// call reset to init the instance
this.reset();
}
/**
* Appends a string.
* A conversion will be applied if an utf8 string is detected.
*
* @param {String} str The string to be appended
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.append = function (str) {
// Converts the string to utf8 bytes if necessary
// Then append as binary
this.appendBinary(toUtf8(str));
return this;
};
/**
* Appends a binary string.
*
* @param {String} contents The binary string to be appended
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.appendBinary = function (contents) {
this._buff += contents;
this._length += contents.length;
var length = this._buff.length,
i;
for (i = 64; i <= length; i += 64) {
md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
}
this._buff = this._buff.substring(i - 64);
return this;
};
/**
* Finishes the incremental computation, reseting the internal state and
* returning the result.
*
* @param {Boolean} raw True to get the raw string, false to get the hex string
*
* @return {String} The result
*/
SparkMD5.prototype.end = function (raw) {
var buff = this._buff,
length = buff.length,
i,
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
ret;
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
}
this._finish(tail, length);
ret = hex(this._hash);
if (raw) {
ret = hexToBinaryString(ret);
}
this.reset();
return ret;
};
/**
* Resets the internal state of the computation.
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.reset = function () {
this._buff = '';
this._length = 0;
this._hash = [1732584193, -271733879, -1732584194, 271733878];
return this;
};
/**
* Gets the internal state of the computation.
*
* @return {Object} The state
*/
SparkMD5.prototype.getState = function () {
return {
buff: this._buff,
length: this._length,
hash: this._hash
};
};
/**
* Gets the internal state of the computation.
*
* @param {Object} state The state
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.setState = function (state) {
this._buff = state.buff;
this._length = state.length;
this._hash = state.hash;
return this;
};
/**
* Releases memory used by the incremental buffer and other additional
* resources. If you plan to use the instance again, use reset instead.
*/
SparkMD5.prototype.destroy = function () {
delete this._hash;
delete this._buff;
delete this._length;
};
/**
* Finish the final calculation based on the tail.
*
* @param {Array} tail The tail (will be modified)
* @param {Number} length The length of the remaining buffer
*/
SparkMD5.prototype._finish = function (tail, length) {
var i = length,
tmp,
lo,
hi;
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(this._hash, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Do the final computation based on the tail and length
// Beware that the final length may not fit in 32 bits so we take care of that
tmp = this._length * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(this._hash, tail);
};
/**
* Performs the md5 hash on a string.
* A conversion will be applied if utf8 string is detected.
*
* @param {String} str The string
* @param {Boolean} raw True to get the raw string, false to get the hex string
*
* @return {String} The result
*/
SparkMD5.hash = function (str, raw) {
// Converts the string to utf8 bytes if necessary
// Then compute it using the binary function
return SparkMD5.hashBinary(toUtf8(str), raw);
};
/**
* Performs the md5 hash on a binary string.
*
* @param {String} content The binary string
* @param {Boolean} raw True to get the raw string, false to get the hex string
*
* @return {String} The result
*/
SparkMD5.hashBinary = function (content, raw) {
var hash = md51(content),
ret = hex(hash);
return raw ? hexToBinaryString(ret) : ret;
};
// ---------------------------------------------------
/**
* SparkMD5 OOP implementation for array buffers.
*
* Use this class to perform an incremental md5 ONLY for array buffers.
*/
SparkMD5.ArrayBuffer = function () {
// call reset to init the instance
this.reset();
};
/**
* Appends an array buffer.
*
* @param {ArrayBuffer} arr The array to be appended
*
* @return {SparkMD5.ArrayBuffer} The instance itself
*/
SparkMD5.ArrayBuffer.prototype.append = function (arr) {
var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
length = buff.length,
i;
this._length += arr.byteLength;
for (i = 64; i <= length; i += 64) {
md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
}
this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
return this;
};
/**
* Finishes the incremental computation, reseting the internal state and
* returning the result.
*
* @param {Boolean} raw True to get the raw string, false to get the hex string
*
* @return {String} The result
*/
SparkMD5.ArrayBuffer.prototype.end = function (raw) {
var buff = this._buff,
length = buff.length,
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
i,
ret;
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= buff[i] << ((i % 4) << 3);
}
this._finish(tail, length);
ret = hex(this._hash);
if (raw) {
ret = hexToBinaryString(ret);
}
this.reset();
return ret;
};
/**
* Resets the internal state of the computation.
*
* @return {SparkMD5.ArrayBuffer} The instance itself
*/
SparkMD5.ArrayBuffer.prototype.reset = function () {
this._buff = new Uint8Array(0);
this._length = 0;
this._hash = [1732584193, -271733879, -1732584194, 271733878];
return this;
};
/**
* Gets the internal state of the computation.
*
* @return {Object} The state
*/
SparkMD5.ArrayBuffer.prototype.getState = function () {
var state = SparkMD5.prototype.getState.call(this);
// Convert buffer to a string
state.buff = arrayBuffer2Utf8Str(state.buff);
return state;
};
/**
* Gets the internal state of the computation.
*
* @param {Object} state The state
*
* @return {SparkMD5.ArrayBuffer} The instance itself
*/
SparkMD5.ArrayBuffer.prototype.setState = function (state) {
// Convert string to buffer
state.buff = utf8Str2ArrayBuffer(state.buff, true);
return SparkMD5.prototype.setState.call(this, state);
};
SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
/**
* Performs the md5 hash on an array buffer.
*
* @param {ArrayBuffer} arr The array buffer
* @param {Boolean} raw True to get the raw string, false to get the hex one
*
* @return {String} The result
*/
SparkMD5.ArrayBuffer.hash = function (arr, raw) {
var hash = md51_array(new Uint8Array(arr)),
ret = hex(hash);
return raw ? hexToBinaryString(ret) : ret;
};
return SparkMD5;
}));
},{}],17:[function(_dereq_,module,exports){
'use strict';
/**
* Stringify/parse functions that don't operate
* recursively, so they avoid call stack exceeded
* errors.
*/
exports.stringify = function stringify(input) {
var queue = [];
queue.push({obj: input});
var res = '';
var next, obj, prefix, val, i, arrayPrefix, keys, k, key, value, objPrefix;
while ((next = queue.pop())) {
obj = next.obj;
prefix = next.prefix || '';
val = next.val || '';
res += prefix;
if (val) {
res += val;
} else if (typeof obj !== 'object') {
res += typeof obj === 'undefined' ? null : JSON.stringify(obj);
} else if (obj === null) {
res += 'null';
} else if (Array.isArray(obj)) {
queue.push({val: ']'});
for (i = obj.length - 1; i >= 0; i--) {
arrayPrefix = i === 0 ? '' : ',';
queue.push({obj: obj[i], prefix: arrayPrefix});
}
queue.push({val: '['});
} else { // object
keys = [];
for (k in obj) {
if (obj.hasOwnProperty(k)) {
keys.push(k);
}
}
queue.push({val: '}'});
for (i = keys.length - 1; i >= 0; i--) {
key = keys[i];
value = obj[key];
objPrefix = (i > 0 ? ',' : '');
objPrefix += JSON.stringify(key) + ':';
queue.push({obj: value, prefix: objPrefix});
}
queue.push({val: '{'});
}
}
return res;
};
// Convenience function for the parse function.
// This pop function is basically copied from
// pouchCollate.parseIndexableString
function pop(obj, stack, metaStack) {
var lastMetaElement = metaStack[metaStack.length - 1];
if (obj === lastMetaElement.element) {
// popping a meta-element, e.g. an object whose value is another object
metaStack.pop();
lastMetaElement = metaStack[metaStack.length - 1];
}
var element = lastMetaElement.element;
var lastElementIndex = lastMetaElement.index;
if (Array.isArray(element)) {
element.push(obj);
} else if (lastElementIndex === stack.length - 2) { // obj with key+value
var key = stack.pop();
element[key] = obj;
} else {
stack.push(obj); // obj with key only
}
}
exports.parse = function (str) {
var stack = [];
var metaStack = []; // stack for arrays and objects
var i = 0;
var collationIndex,parsedNum,numChar;
var parsedString,lastCh,numConsecutiveSlashes,ch;
var arrayElement, objElement;
while (true) {
collationIndex = str[i++];
if (collationIndex === '}' ||
collationIndex === ']' ||
typeof collationIndex === 'undefined') {
if (stack.length === 1) {
return stack.pop();
} else {
pop(stack.pop(), stack, metaStack);
continue;
}
}
switch (collationIndex) {
case ' ':
case '\t':
case '\n':
case ':':
case ',':
break;
case 'n':
i += 3; // 'ull'
pop(null, stack, metaStack);
break;
case 't':
i += 3; // 'rue'
pop(true, stack, metaStack);
break;
case 'f':
i += 4; // 'alse'
pop(false, stack, metaStack);
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
parsedNum = '';
i--;
while (true) {
numChar = str[i++];
if (/[\d\.\-e\+]/.test(numChar)) {
parsedNum += numChar;
} else {
i--;
break;
}
}
pop(parseFloat(parsedNum), stack, metaStack);
break;
case '"':
parsedString = '';
lastCh = void 0;
numConsecutiveSlashes = 0;
while (true) {
ch = str[i++];
if (ch !== '"' || (lastCh === '\\' &&
numConsecutiveSlashes % 2 === 1)) {
parsedString += ch;
lastCh = ch;
if (lastCh === '\\') {
numConsecutiveSlashes++;
} else {
numConsecutiveSlashes = 0;
}
} else {
break;
}
}
pop(JSON.parse('"' + parsedString + '"'), stack, metaStack);
break;
case '[':
arrayElement = { element: [], index: stack.length };
stack.push(arrayElement.element);
metaStack.push(arrayElement);
break;
case '{':
objElement = { element: {}, index: stack.length };
stack.push(objElement.element);
metaStack.push(objElement);
break;
default:
throw new Error(
'unexpectedly reached end of input: ' + collationIndex);
}
}
};
},{}]},{},[3])(3)
}); | matiaspunx/devrock-notes | public/bower_components/pouchdb/dist/pouchdb.js | JavaScript | mit | 371,245 |
var HELLO_COMPONENT = `
var HelloMessage = React.createClass({
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
ReactDOM.render(<HelloMessage name="John" />, mountNode);
`;
ReactDOM.render(
<ReactPlayground codeText={HELLO_COMPONENT} />,
document.getElementById('helloExample')
);
| nsipplswezey/nodal | new_docs/_js/examples/hello.js | JavaScript | mit | 316 |
/**
* @fileoverview Rule to flag use of comma operator
* @author Brandon Mills
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = function(context) {
/**
* Parts of the grammar that are required to have parens.
*/
var parenthesized = {
"DoWhileStatement": "test",
"IfStatement": "test",
"SwitchStatement": "discriminant",
"WhileStatement": "test",
"WithStatement": "object"
// Omitting CallExpression - commas are parsed as argument separators
// Omitting NewExpression - commas are parsed as argument separators
// Omitting ForInStatement - parts aren't individually parenthesised
// Omitting ForStatement - parts aren't individually parenthesised
};
/**
* Determines whether a node is required by the grammar to be wrapped in
* parens, e.g. the test of an if statement.
* @param {ASTNode} node - The AST node
* @returns {boolean} True if parens around node belong to parent node.
*/
function requiresExtraParens(node) {
return node.parent && parenthesized[node.parent.type] &&
node === node.parent[parenthesized[node.parent.type]];
}
/**
* Check if a node is wrapped in parens.
* @param {ASTNode} node - The AST node
* @returns {boolean} True if the node has a paren on each side.
*/
function isParenthesised(node) {
var previousToken = context.getTokenBefore(node),
nextToken = context.getTokenAfter(node);
return previousToken && nextToken &&
previousToken.value === "(" && previousToken.range[1] <= node.range[0] &&
nextToken.value === ")" && nextToken.range[0] >= node.range[1];
}
/**
* Check if a node is wrapped in two levels of parens.
* @param {ASTNode} node - The AST node
* @returns {boolean} True if two parens surround the node on each side.
*/
function isParenthesisedTwice(node) {
var previousToken = context.getTokenBefore(node, 1),
nextToken = context.getTokenAfter(node, 1);
return isParenthesised(node) && previousToken && nextToken &&
previousToken.value === "(" && previousToken.range[1] <= node.range[0] &&
nextToken.value === ")" && nextToken.range[0] >= node.range[1];
}
return {
"SequenceExpression": function(node) {
// Always allow sequences in for statement update
if (node.parent.type === "ForStatement" &&
(node === node.parent.init || node === node.parent.update)) {
return;
}
// Wrapping a sequence in extra parens indicates intent
if (requiresExtraParens(node)) {
if (isParenthesisedTwice(node)) {
return;
}
} else {
if (isParenthesised(node)) {
return;
}
}
context.report(node, "Unexpected use of comma operator.");
}
};
};
module.exports.schema = [];
| BabbleCar/demo-mirrorlink-cordova | plugins/cordova-plugin-mirrorlink/www/node_modules/eslint/lib/rules/no-sequences.js | JavaScript | mit | 3,252 |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("placeholder","nb",{title:"Egenskaper for plassholder",toolbar:"Opprett plassholder",name:"Navn på plassholder",invalidName:"Plassholderen kan ikke være tom, og kan ikke inneholde følgende tegn: [, ], \x3c, \x3e",pathName:"plassholder"}); | donatienthorez/sf_mobilIT_backEnd | web/assets/vendor/ckeditor/plugins/placeholder/lang/nb.js | JavaScript | mit | 414 |
/*
YUI 3.4.1 (build 4118)
Copyright 2011 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('node-load', function(Y) {
/**
* Extended Node interface with a basic IO API.
* @module node
* @submodule node-load
*/
/**
* The default IO complete handler.
* @method _ioComplete
* @protected
* @for Node
* @param {String} code The response code.
* @param {Object} response The response object.
* @param {Array} args An array containing the callback and selector
*/
Y.Node.prototype._ioComplete = function(code, response, args) {
var selector = args[0],
callback = args[1],
tmp,
content;
if (response && response.responseText) {
content = response.responseText;
if (selector) {
tmp = Y.DOM.create(content);
content = Y.Selector.query(selector, tmp);
}
this.setContent(content);
}
if (callback) {
callback.call(this, code, response);
}
};
/**
* Loads content from the given url and replaces the Node's
* existing content with the remote content.
* @method load
* @param {String} url The URL to load via XMLHttpRequest.
* @param {String} selector An optional selector representing a subset of an HTML document to load.
* @param {Function} callback An optional function to run after the content has been loaded.
* @chainable
*/
Y.Node.prototype.load = function(url, selector, callback) {
if (typeof selector == 'function') {
callback = selector;
selector = null;
}
var config = {
context: this,
on: {
complete: this._ioComplete
},
arguments: [selector, callback]
};
Y.io(url, config);
return this;
}
}, '3.4.1' ,{requires:['node-base', 'io-base']});
| zuverza/se | sites/all/libraries/yui/build/node-load/node-load.js | JavaScript | gpl-2.0 | 1,815 |
(function($, UI) {
"use strict";
UI.component('alert', {
defaults: {
"fade": true,
"duration": 200,
"trigger": ".@-alert-close"
},
boot: function() {
// init code
UI.$html.on("click.alert.uikit", "[data-@-alert]", function(e) {
var ele = UI.$(this);
if (!ele.data("alert")) {
var alert = UI.alert(ele, UI.Utils.options(ele.attr("data-@-alert")));
if (UI.$(e.target).is(alert.options.trigger)) {
e.preventDefault();
alert.close();
}
}
});
},
init: function() {
var $this = this;
this.on("click", this.options.trigger, function(e) {
e.preventDefault();
$this.close();
});
},
close: function() {
var element = this.trigger("close.uk.alert"),
removeElement = function () {
this.trigger("closed.uk.alert").remove();
}.bind(this);
if (this.options.fade) {
element.css("overflow", "hidden").css("max-height", element.height()).animate({
"height" : 0,
"opacity" : 0,
"padding-top" : 0,
"padding-bottom" : 0,
"margin-top" : 0,
"margin-bottom" : 0
}, this.options.duration, removeElement);
} else {
removeElement();
}
}
});
})(jQuery, UIkit);
| mubassirhayat/uikit | src/js/core/alert.js | JavaScript | mit | 1,719 |
/*! SWFMini - a SWFObject 2.2 cut down version for webshims
*
* based on SWFObject v2.2 <http://code.google.com/p/swfobject/>
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfmini = function() {
var UNDEF = "undefined",
OBJECT = "object",
webshims = window.webshims,
SHOCKWAVE_FLASH = "Shockwave Flash",
SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
FLASH_MIME_TYPE = "application/x-shockwave-flash",
win = window,
doc = document,
nav = navigator,
plugin = false,
domLoadFnArr = [main],
objIdArr = [],
listenersArr = [],
storedAltContent,
storedAltContentId,
storedCallbackFn,
storedCallbackObj,
isDomLoaded = false,
dynamicStylesheet,
dynamicStylesheetMedia,
autoHideShow = true,
/* Centralized function for browser feature detection
- User agent string detection is only used when no good alternative is possible
- Is executed directly for optimal performance
*/
ua = function() {
var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
u = nav.userAgent.toLowerCase(),
p = nav.platform.toLowerCase(),
windows = p ? /win/.test(p) : /win/.test(u),
mac = p ? /mac/.test(p) : /mac/.test(u),
webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html
playerVersion = [0,0,0],
d = null;
if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
d = nav.plugins[SHOCKWAVE_FLASH].description;
if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
plugin = true;
ie = false; // cascaded feature detection for Internet Explorer
d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0;
}
}
else if (typeof win.ActiveXObject != UNDEF) {
try {
var a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
if (a) { // a will return null when ActiveX is disabled
d = a.GetVariable("$version");
if (d) {
ie = true; // cascaded feature detection for Internet Explorer
d = d.split(" ")[1].split(",");
playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
}
catch(e) {}
}
return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac };
}();
function callDomLoadFunctions() {
if (isDomLoaded) { return; }
try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early
var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span"));
t.parentNode.removeChild(t);
}
catch (e) { return; }
isDomLoaded = true;
var dl = domLoadFnArr.length;
for (var i = 0; i < dl; i++) {
domLoadFnArr[i]();
}
}
function addDomLoadEvent(fn) {
if (isDomLoaded) {
fn();
}
else {
domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
}
}
/* Cross-browser onload
- Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
- Will fire an event as soon as a web page including all of its assets are loaded
*/
function addLoadEvent(fn) {
}
/* Main function
- Will preferably execute onDomLoad, otherwise onload (as a fallback)
*/
function main() {
if (plugin) {
testPlayerVersion();
}
}
/* Detect the Flash Player version for non-Internet Explorer browsers
- Detecting the plug-in version via the object element is more precise than using the plugins collection item's description:
a. Both release and build numbers can be detected
b. Avoid wrong descriptions by corrupt installers provided by Adobe
c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports
- Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available
*/
function testPlayerVersion() {
var b = doc.getElementsByTagName("body")[0];
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
var t = b.appendChild(o);
if (t) {
var counter = 0;
(function(){
if (typeof t.GetVariable != UNDEF) {
var d = t.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
else if (counter < 10) {
counter++;
setTimeout(arguments.callee, 10);
return;
}
b.removeChild(o);
t = null;
})();
}
}
function getObjectById(objectIdStr) {
var r = null;
var o = getElementById(objectIdStr);
if (o && o.nodeName == "OBJECT") {
if (typeof o.SetVariable != UNDEF) {
r = o;
}
else {
var n = o.getElementsByTagName(OBJECT)[0];
if (n) {
r = n;
}
}
}
return r;
}
/* Cross-browser dynamic SWF creation
*/
function createSWF(attObj, parObj, id) {
var r, el = getElementById(id);
if (ua.wk && ua.wk < 312) { return r; }
if (el) {
if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
attObj.id = id;
}
if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML
var att = "";
for (var i in attObj) {
if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries
if (i.toLowerCase() == "data") {
parObj.movie = attObj[i];
}
else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
att += ' class="' + attObj[i] + '"';
}
else if (i.toLowerCase() != "classid") {
att += ' ' + i + '="' + attObj[i] + '"';
}
}
}
var par = "";
for (var j in parObj) {
if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries
par += '<param name="' + j + '" value="' + parObj[j] + '" />';
}
}
el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only)
r = getElementById(attObj.id);
}
else { // well-behaving browsers
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
for (var m in attObj) {
if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries
if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
o.setAttribute("class", attObj[m]);
}
else if (m.toLowerCase() != "classid") { // filter out IE specific attribute
o.setAttribute(m, attObj[m]);
}
}
}
for (var n in parObj) {
if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element
createObjParam(o, n, parObj[n]);
}
}
el.parentNode.replaceChild(o, el);
r = o;
}
}
return r;
}
function createObjParam(el, pName, pValue) {
var p = createElement("param");
p.setAttribute("name", pName);
p.setAttribute("value", pValue);
el.appendChild(p);
}
/* Cross-browser SWF removal
- Especially needed to safely and completely remove a SWF in Internet Explorer
*/
function removeSWF(id) {
var obj = getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (ua.ie && ua.win) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
removeObjectInIE(id);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
else {
obj.parentNode.removeChild(obj);
}
}
}
function removeObjectInIE(id) {
var obj = getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
/* Functions to optimize JavaScript compression
*/
function getElementById(id) {
var el = null;
try {
el = doc.getElementById(id);
}
catch (e) {}
return el;
}
function createElement(el) {
return doc.createElement(el);
}
/* Updated attachEvent function for Internet Explorer
- Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
*/
function addListener(target, eventType, fn) {
target.attachEvent(eventType, fn);
listenersArr[listenersArr.length] = [target, eventType, fn];
}
/* Flash Player and SWF content version matching
*/
function hasPlayerVersion(rv) {
var pv = ua.pv, v = rv.split(".");
v[0] = parseInt(v[0], 10);
v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
v[2] = parseInt(v[2], 10) || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
}
function setVisibility(id, isVisible) {
if (!autoHideShow) { return; }
var elem;
var v = isVisible ? "visible" : "hidden";
if (isDomLoaded && (elem && getElementById(id))) {
getElementById(id).style.visibility = v;
}
}
/* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
*/
var cleanup = function() {
if (ua.ie && ua.win && window.attachEvent) {
window.attachEvent("onunload", function() {
// remove listeners to avoid memory leaks
var ll = listenersArr.length;
for (var i = 0; i < ll; i++) {
listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
}
// cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
var il = objIdArr.length;
for (var j = 0; j < il; j++) {
removeSWF(objIdArr[j]);
}
// cleanup library's main closures to avoid memory leaks
for (var k in ua) {
ua[k] = null;
}
ua = null;
for (var l in swfmini) {
swfmini[l] = null;
}
swfmini = null;
});
}
}();
webshims.ready('DOM', callDomLoadFunctions);
return {
/* Public API
- Reference: http://code.google.com/p/swfobject/wiki/documentation
*/
registerObject: function() {
},
getObjectById: function(objectIdStr) {
if (ua.w3) {
return getObjectById(objectIdStr);
}
},
embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) {
var callbackObj = {success:false, id:replaceElemIdStr};
if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) {
setVisibility(replaceElemIdStr, false);
addDomLoadEvent(function() {
widthStr += ""; // auto-convert to string
heightStr += "";
var att = {};
if (attObj && typeof attObj === OBJECT) {
for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs
att[i] = attObj[i];
}
}
att.data = swfUrlStr;
att.width = widthStr;
att.height = heightStr;
var par = {};
if (parObj && typeof parObj === OBJECT) {
for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs
par[j] = parObj[j];
}
}
if (flashvarsObj && typeof flashvarsObj === OBJECT) {
for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs
if (typeof par.flashvars != UNDEF) {
par.flashvars += "&" + k + "=" + flashvarsObj[k];
}
else {
par.flashvars = k + "=" + flashvarsObj[k];
}
}
}
if (hasPlayerVersion(swfVersionStr)) { // create SWF
var obj = createSWF(att, par, replaceElemIdStr);
if (att.id == replaceElemIdStr) {
setVisibility(replaceElemIdStr, true);
}
callbackObj.success = true;
callbackObj.ref = obj;
}
else { // show alternative content
setVisibility(replaceElemIdStr, true);
}
if (callbackFn) { callbackFn(callbackObj); }
});
}
else if (callbackFn) { callbackFn(callbackObj); }
},
switchOffAutoHideShow: function() {
autoHideShow = false;
},
ua: ua,
getFlashPlayerVersion: function() {
return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
},
hasFlashPlayerVersion: hasPlayerVersion,
createSWF: function(attObj, parObj, replaceElemIdStr) {
if (ua.w3) {
return createSWF(attObj, parObj, replaceElemIdStr);
}
else {
return undefined;
}
},
showExpressInstall: function() {
},
removeSWF: function(objElemIdStr) {
if (ua.w3) {
removeSWF(objElemIdStr);
}
},
createCSS: function() {
},
addDomLoadEvent: addDomLoadEvent,
addLoadEvent: addLoadEvent,
// For internal usage only
expressInstallCallback: function() {
}
};
}();
webshims.isReady('swfmini', true);
;webshims.register('filereader', function( $, webshims ){
"use strict";
/**
* Code is based on https://github.com/Jahdrien/FileReader
*
*/
(function(){
var swfobject = window.swfmini || window.swfobject;
var readyCallbacks = $.Callbacks('once unique memory'),
inputsCount = 0,
currentTarget = null;
// if native FileReader support, then dont add the polyfill and make the plugin do nothing
if (window.FileReader) {
$.fn.fileReader = function () { return this; }
return ;
}
/**
* JQuery Plugin
*/
$.fn.fileReader = function( options ) {
if(this.length){
options = $.extend($.fn.fileReader.defaults, options);
var self = this;
readyCallbacks.add(function() {
return main(self, options);
});
if ($.isFunction(options.callback)) readyCallbacks.add(options.callback);
if (!FileAPIProxy.ready) {
FileAPIProxy.init(options);
}
}
return this;
};
/**
* Default options
* allows user set default options
*/
$.fn.fileReader.defaults = {
id : 'fileReaderSWFObject', // ID for the created swf object container,
multiple : null,
accept : null,
label : null,
extensions : null,
filereader : 'files/filereader.swf', // The path to the filereader swf file
expressInstall : null, // The path to the express install swf file
debugMode : false,
callback : false // Callback function when Filereader is ready
};
/**
* Plugin callback
* adds an input to registry
*/
var main = function(el, options) {
return el.each(function(i, input) {
input = $(input);
var id = input.attr('id');
var multiple, accept, label;
if (!id) {
id = 'flashFileInput' + inputsCount;
input.attr('id', id);
inputsCount++;
}
multiple = input.prop('multiple');
accept = input.data('swfaccept') || input.prop('accept') || options.accept;
label = input.jProp('labels')
.map(function(){
return $(this).text();
}).get().join(' ') ||
input.data('swflabel') ||
options.label;
FileAPIProxy.inputs[id] = input;
FileAPIProxy.swfObject.add(id, multiple, accept, label, options.extensions);
input.css('z-index', 0)
.mouseover(function (e) {
if (id !== currentTarget) {
e = e || window.event;
currentTarget = id;
FileAPIProxy.swfObject.mouseover(id);
FileAPIProxy.container
.height(input.outerHeight())
.width(input.outerWidth())
.css(input.offset());
}
})
.click(function(e) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
});
});
};
/**
* Flash FileReader Proxy
*/
window.FileAPIProxy = {
ready: false,
_inititalized: false,
init: function(o) {
var self = this;
this.debugMode = o.debugMode;
if(!this.container){
this.container = $('<div>').attr('id', o.id)
.wrap('<div>')
.parent()
.css({
position:'fixed',
// top:'0px',
width:'1px',
height:'1px',
display:'inline-block',
background:'transparent',
'z-index':99999
})
// Hands over mouse events to original input for css styles
.on('mouseover mouseout mousedown mouseup', function(evt) {
if(currentTarget){
$('#' + currentTarget).trigger(evt.type);
}
})
.appendTo('body');
swfobject.embedSWF(o.filereader, o.id, '100%', '100%', '10', o.expressInstall, {debugMode: o.debugMode ? true : ''}, {'wmode':'transparent','allowScriptAccess':'sameDomain'}, {}, function(e) {
self.swfObject = e.ref;
$(self.swfObject)
.css({
display: 'block',
outline: 0
})
.attr('tabindex', 0);
self.ready = e.success && typeof e.ref.add === "function";
if (self.ready) {
readyCallbacks.fire();
}
});
}
},
swfObject: null,
container: null,
// Inputs Registry
inputs: {},
// Readers Registry
readers: {},
// Receives FileInput events
onFileInputEvent: function(evt) {
if (this.debugMode) console.info('FileInput Event ', evt.type, evt);
if (evt.target in this.inputs) {
var el = this.inputs[evt.target];
evt.target = el[0];
if( evt.type === 'change') {
webshims.data(evt.target, 'fileList', new FileList(evt.files));
}
el.trigger(evt);
}
window.focus();
},
// Receives FileReader ProgressEvents
onFileReaderEvent: function(evt) {
if (this.debugMode) console.info('FileReader Event ', evt.type, evt, evt.target in this.readers);
if (evt.target in this.readers) {
var reader = this.readers[evt.target];
evt.target = reader;
reader._handleFlashEvent.call(reader, evt);
}
},
// Receives flash FileReader Error Events
onFileReaderError: function(error) {
if (this.debugMode) console.log(error);
},
onSWFReady: function() {
this.container.css({position: 'absolute'});
this.ready = typeof this.swfObject.add === "function";
if (this.ready) {
readyCallbacks.fire();
}
return true;
}
};
/**
* Add FileReader to the window object
*/
window.FileReader = function () {
// states
this.EMPTY = 0;
this.LOADING = 1;
this.DONE = 2;
this.readyState = 0;
// File or Blob data
this.result = null;
this.error = null;
// event handler attributes
this.onloadstart = null;
this.onprogress = null;
this.onload = null;
this.onabort = null;
this.onerror = null;
this.onloadend = null;
// Event Listeners handling using JQuery Callbacks
this._callbacks = {
loadstart : $.Callbacks( "unique" ),
progress : $.Callbacks( "unique" ),
abort : $.Callbacks( "unique" ),
error : $.Callbacks( "unique" ),
load : $.Callbacks( "unique" ),
loadend : $.Callbacks( "unique" )
};
// Custom properties
this._id = null;
};
window.FileReader.prototype = {
// async read methods
readAsBinaryString: function (file) {
this._start(file);
FileAPIProxy.swfObject.read(file.input, file.name, 'readAsBinaryString');
},
readAsText: function (file, encoding) {
this._start(file);
FileAPIProxy.swfObject.read(file.input, file.name, 'readAsText');
},
readAsDataURL: function (file) {
this._start(file);
FileAPIProxy.swfObject.read(file.input, file.name, 'readAsDataURL');
},
readAsArrayBuffer: function(file){
throw("Whoops FileReader.readAsArrayBuffer is unimplemented");
},
abort: function () {
this.result = null;
if (this.readyState === this.EMPTY || this.readyState === this.DONE) return;
FileAPIProxy.swfObject.abort(this._id);
},
// Event Target interface
addEventListener: function (type, listener) {
if (type in this._callbacks) this._callbacks[type].add(listener);
},
removeEventListener: function (type, listener) {
if (type in this._callbacks) this._callbacks[type].remove(listener);
},
dispatchEvent: function (event) {
event.target = this;
if (event.type in this._callbacks) {
var fn = this['on' + event.type];
if ($.isFunction(fn)) fn(event);
this._callbacks[event.type].fire(event);
}
return true;
},
// Custom private methods
// Registers FileReader instance for flash callbacks
_register: function(file) {
this._id = file.input + '.' + file.name;
FileAPIProxy.readers[this._id] = this;
},
_start: function(file) {
this._register(file);
if (this.readyState === this.LOADING) throw {type: 'InvalidStateError', code: 11, message: 'The object is in an invalid state.'};
},
_handleFlashEvent: function(evt) {
switch (evt.type) {
case 'loadstart':
this.readyState = this.LOADING;
break;
case 'loadend':
this.readyState = this.DONE;
break;
case 'load':
this.readyState = this.DONE;
this.result = FileAPIProxy.swfObject.result(this._id);
break;
case 'error':
this.result = null;
this.error = {
name: 'NotReadableError',
message: 'The File cannot be read!'
};
}
this.dispatchEvent(new FileReaderEvent(evt));
}
};
/**
* FileReader ProgressEvent implenting Event interface
*/
window.FileReaderEvent = function (e) {
this.initEvent(e);
};
window.FileReaderEvent.prototype = {
initEvent: function (event) {
$.extend(this, {
type: null,
target: null,
currentTarget: null,
eventPhase: 2,
bubbles: false,
cancelable: false,
defaultPrevented: false,
isTrusted: false,
timeStamp: new Date().getTime()
}, event);
},
stopPropagation: function (){
},
stopImmediatePropagation: function (){
},
preventDefault: function (){
}
};
/**
* FileList interface (Object with item function)
*/
window.FileList = function(array) {
if (array) {
for (var i = 0; i < array.length; i++) {
this[i] = array[i];
}
this.length = array.length;
} else {
this.length = 0;
}
};
window.FileList.prototype = {
item: function(index) {
return (index in this) ? this[index] : null;
}
};
})();
webshims.defineNodeNameProperty('input', 'files', {
prop: {
writeable: false,
get: function(){
if(this.type != 'file'){return null;}
if(!$(this).is('.ws-filereader')){
webshims.error("please add the 'ws-filereader' class to your input[type='file'] to implement files-property");
}
return webshims.data(this, 'fileList') || webshims.data(this, 'fileList', new FileList());
}
}
}
);
webshims.defineNodeNamesBooleanProperty('input', 'multiple');
//webshims
$.fn.fileReader.defaults.filereader = webshims.cfg.basePath +'swf/filereader.swf';
var wait = ['DOM'];
if(webshims.modules["form-core"].loaded){
wait.push('forms');
}
webshims.ready(wait, function(){
webshims.addReady(function(context, contextElem){
$('input[type="file"].ws-filereader', context).fileReader();
});
});
});
| the-destro/cdnjs | ajax/libs/webshim/1.12.5-RC-1/dev/shims/combos/27.js | JavaScript | mit | 24,141 |
YUI.add('overlay', function(Y) {
/**
* Provides a basic Overlay widget, with Standard Module content support. The Overlay widget
* provides Page XY positioning support, alignment and centering support along with basic
* stackable support (z-index and shimming).
*
* @module overlay
*/
/**
* A basic Overlay Widget, which can be positioned based on Page XY co-ordinates and is stackable (z-index support).
* It also provides alignment and centering support and uses a standard module format for it's content, with header,
* body and footer section support.
*
* @class Overlay
* @constructor
* @extends Widget
* @uses WidgetPosition
* @uses WidgetStack
* @uses WidgetPositionExt
* @uses WidgetStdMod
* @param {Object} object The user configuration for the instance.
*/
Y.Overlay = Y.Base.build("overlay", Y.Widget, [Y.WidgetPosition, Y.WidgetStack, Y.WidgetPositionExt, Y.WidgetStdMod]);
}, '@VERSION@' ,{requires:['widget', 'widget-position', 'widget-stack', 'widget-position-ext', 'widget-stdmod']});
| pc035860/cdnjs | ajax/libs/yui/3.0.0beta1m3/overlay/overlay.js | JavaScript | mit | 1,027 |
define('ace/snippets/html_completions', ['require', 'exports', 'module' ], function(require, exports, module) {
exports.snippetText = "";
exports.scope = "html_completions";
});
| tancredi/draw | www/js/vendor/ace/snippets/html_completions.js | JavaScript | mit | 181 |
function htmlRemove() {
this.innerHTML = "";
}
function htmlConstant(value) {
return function() {
this.innerHTML = value;
};
}
function htmlFunction(value) {
return function() {
var v = value.apply(this, arguments);
this.innerHTML = v == null ? "" : v;
};
}
export default function(value) {
return arguments.length
? this.each(value == null
? htmlRemove : (typeof value === "function"
? htmlFunction
: htmlConstant)(value))
: this.node().innerHTML;
}
| rhoon/thesis | work/analysis/node_modules/d3/node_modules/d3-selection/src/selection/html.js | JavaScript | mit | 520 |
'use strict';
var test = require('tape');
var toPrimitive = require('../es2015');
var is = require('object-is');
var forEach = require('foreach');
var functionName = require('function.prototype.name');
var debug = require('object-inspect');
var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';
var hasSymbolToPrimitive = hasSymbols && typeof Symbol.toPrimitive === 'symbol';
test('function properties', function (t) {
t.equal(toPrimitive.length, 1, 'length is 1');
t.equal(functionName(toPrimitive), 'ToPrimitive', 'name is ToPrimitive');
t.end();
});
var primitives = [null, undefined, true, false, 0, -0, 42, NaN, Infinity, -Infinity, '', 'abc'];
test('primitives', function (t) {
forEach(primitives, function (i) {
t.ok(is(toPrimitive(i), i), 'toPrimitive(' + debug(i) + ') returns the same value');
t.ok(is(toPrimitive(i, String), i), 'toPrimitive(' + debug(i) + ', String) returns the same value');
t.ok(is(toPrimitive(i, Number), i), 'toPrimitive(' + debug(i) + ', Number) returns the same value');
});
t.end();
});
test('Symbols', { skip: !hasSymbols }, function (t) {
var symbols = [
Symbol('foo'),
Symbol.iterator,
Symbol['for']('foo') // eslint-disable-line no-restricted-properties
];
forEach(symbols, function (sym) {
t.equal(toPrimitive(sym), sym, 'toPrimitive(' + debug(sym) + ') returns the same value');
t.equal(toPrimitive(sym, String), sym, 'toPrimitive(' + debug(sym) + ', String) returns the same value');
t.equal(toPrimitive(sym, Number), sym, 'toPrimitive(' + debug(sym) + ', Number) returns the same value');
});
var primitiveSym = Symbol('primitiveSym');
var objectSym = Object(primitiveSym);
t.equal(toPrimitive(objectSym), primitiveSym, 'toPrimitive(' + debug(objectSym) + ') returns ' + debug(primitiveSym));
t.equal(toPrimitive(objectSym, String), primitiveSym, 'toPrimitive(' + debug(objectSym) + ', String) returns ' + debug(primitiveSym));
t.equal(toPrimitive(objectSym, Number), primitiveSym, 'toPrimitive(' + debug(objectSym) + ', Number) returns ' + debug(primitiveSym));
t.end();
});
test('Arrays', function (t) {
var arrays = [[], ['a', 'b'], [1, 2]];
forEach(arrays, function (arr) {
t.equal(toPrimitive(arr), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array');
t.equal(toPrimitive(arr, String), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array');
t.equal(toPrimitive(arr, Number), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array');
});
t.end();
});
test('Dates', function (t) {
var dates = [new Date(), new Date(0), new Date(NaN)];
forEach(dates, function (date) {
t.equal(toPrimitive(date), String(date), 'toPrimitive(' + debug(date) + ') returns the string version of the date');
t.equal(toPrimitive(date, String), String(date), 'toPrimitive(' + debug(date) + ') returns the string version of the date');
t.ok(is(toPrimitive(date, Number), Number(date)), 'toPrimitive(' + debug(date) + ') returns the number version of the date');
});
t.end();
});
var coercibleObject = { valueOf: function () { return 3; }, toString: function () { return 42; } };
var valueOfOnlyObject = { valueOf: function () { return 4; }, toString: function () { return {}; } };
var toStringOnlyObject = { valueOf: function () { return {}; }, toString: function () { return 7; } };
var coercibleFnObject = {
valueOf: function () { return function valueOfFn() {}; },
toString: function () { return 42; }
};
var uncoercibleObject = { valueOf: function () { return {}; }, toString: function () { return {}; } };
var uncoercibleFnObject = {
valueOf: function () { return function valueOfFn() {}; },
toString: function () { return function toStrFn() {}; }
};
test('Objects', function (t) {
t.equal(toPrimitive(coercibleObject), coercibleObject.valueOf(), 'coercibleObject with no hint coerces to valueOf');
t.equal(toPrimitive(coercibleObject, Number), coercibleObject.valueOf(), 'coercibleObject with hint Number coerces to valueOf');
t.equal(toPrimitive(coercibleObject, String), coercibleObject.toString(), 'coercibleObject with hint String coerces to non-stringified toString');
t.equal(toPrimitive(coercibleFnObject), coercibleFnObject.toString(), 'coercibleFnObject coerces to non-stringified toString');
t.equal(toPrimitive(coercibleFnObject, Number), coercibleFnObject.toString(), 'coercibleFnObject with hint Number coerces to non-stringified toString');
t.equal(toPrimitive(coercibleFnObject, String), coercibleFnObject.toString(), 'coercibleFnObject with hint String coerces to non-stringified toString');
t.equal(toPrimitive({}), '[object Object]', '{} with no hint coerces to Object#toString');
t.equal(toPrimitive({}, Number), '[object Object]', '{} with hint Number coerces to Object#toString');
t.equal(toPrimitive({}, String), '[object Object]', '{} with hint String coerces to Object#toString');
t.equal(toPrimitive(toStringOnlyObject), toStringOnlyObject.toString(), 'toStringOnlyObject returns non-stringified toString');
t.equal(toPrimitive(toStringOnlyObject, Number), toStringOnlyObject.toString(), 'toStringOnlyObject with hint Number returns non-stringified toString');
t.equal(toPrimitive(toStringOnlyObject, String), toStringOnlyObject.toString(), 'toStringOnlyObject with hint String returns non-stringified toString');
t.equal(toPrimitive(valueOfOnlyObject), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject returns valueOf');
t.equal(toPrimitive(valueOfOnlyObject, Number), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint Number returns valueOf');
t.equal(toPrimitive(valueOfOnlyObject, String), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint String returns non-stringified valueOf');
t.test('Symbol.toPrimitive', { skip: !hasSymbolToPrimitive }, function (st) {
var overriddenObject = { toString: st.fail, valueOf: st.fail };
overriddenObject[Symbol.toPrimitive] = function (hint) { return String(hint); };
st.equal(toPrimitive(overriddenObject), 'default', 'object with Symbol.toPrimitive + no hint invokes that');
st.equal(toPrimitive(overriddenObject, Number), 'number', 'object with Symbol.toPrimitive + hint Number invokes that');
st.equal(toPrimitive(overriddenObject, String), 'string', 'object with Symbol.toPrimitive + hint String invokes that');
var nullToPrimitive = { toString: coercibleObject.toString, valueOf: coercibleObject.valueOf };
nullToPrimitive[Symbol.toPrimitive] = null;
st.equal(toPrimitive(nullToPrimitive), toPrimitive(coercibleObject), 'object with no hint + null Symbol.toPrimitive ignores it');
st.equal(toPrimitive(nullToPrimitive, Number), toPrimitive(coercibleObject, Number), 'object with hint Number + null Symbol.toPrimitive ignores it');
st.equal(toPrimitive(nullToPrimitive, String), toPrimitive(coercibleObject, String), 'object with hint String + null Symbol.toPrimitive ignores it');
st.test('exceptions', function (sst) {
var nonFunctionToPrimitive = { toString: sst.fail, valueOf: sst.fail };
nonFunctionToPrimitive[Symbol.toPrimitive] = {};
sst['throws'](toPrimitive.bind(null, nonFunctionToPrimitive), TypeError, 'Symbol.toPrimitive returning a non-function throws');
var uncoercibleToPrimitive = { toString: sst.fail, valueOf: sst.fail };
uncoercibleToPrimitive[Symbol.toPrimitive] = function (hint) {
return { toString: function () { return hint; } };
};
sst['throws'](toPrimitive.bind(null, uncoercibleToPrimitive), TypeError, 'Symbol.toPrimitive returning an object throws');
var throwingToPrimitive = { toString: sst.fail, valueOf: sst.fail };
throwingToPrimitive[Symbol.toPrimitive] = function (hint) { throw new RangeError(hint); };
sst['throws'](toPrimitive.bind(null, throwingToPrimitive), RangeError, 'Symbol.toPrimitive throwing throws');
sst.end();
});
st.end();
});
t.test('exceptions', function (st) {
st['throws'](toPrimitive.bind(null, uncoercibleObject), TypeError, 'uncoercibleObject throws a TypeError');
st['throws'](toPrimitive.bind(null, uncoercibleObject, Number), TypeError, 'uncoercibleObject with hint Number throws a TypeError');
st['throws'](toPrimitive.bind(null, uncoercibleObject, String), TypeError, 'uncoercibleObject with hint String throws a TypeError');
st['throws'](toPrimitive.bind(null, uncoercibleFnObject), TypeError, 'uncoercibleFnObject throws a TypeError');
st['throws'](toPrimitive.bind(null, uncoercibleFnObject, Number), TypeError, 'uncoercibleFnObject with hint Number throws a TypeError');
st['throws'](toPrimitive.bind(null, uncoercibleFnObject, String), TypeError, 'uncoercibleFnObject with hint String throws a TypeError');
st.end();
});
t.end();
});
| matryer/bitbar | xbarapp.com/node_modules/es-to-primitive/test/es2015.js | JavaScript | mit | 8,732 |
const paginationActionTypes = {
SELECT_PANEL: "SELECT_PANEL"
};
export default paginationActionTypes;
| dnnsoftware/Dnn.AdminExperience.Extensions | src/Modules/Settings/Dnn.PersonaBar.Vocabularies/Vocabularies.Web/src/constants/actionTypes/visiblePanel.js | JavaScript | mit | 111 |
{
"metadata" :
{
"formatVersion" : 3.1,
"sourceFile" : "gallardo_wheel.obj",
"generatedBy" : "OBJConverter",
"vertices" : 4434,
"faces" : 4394,
"normals" : 2654,
"uvs" : 0,
"materials" : 2
},
"materials": [ {
"DbgColor" : 15658734,
"DbgIndex" : 0,
"DbgName" : "wire_255255255",
"colorAmbient" : [0.0, 0.0, 0.0],
"colorDiffuse" : [0.64, 0.64, 0.64],
"colorSpecular" : [0.175, 0.175, 0.175],
"illumination" : 2,
"opticalDensity" : 1.0,
"specularCoef" : 27.45098,
"transparency" : 0.0
},
{
"DbgColor" : 15597568,
"DbgIndex" : 1,
"DbgName" : "wire_115115115",
"colorAmbient" : [0.0, 0.0, 0.0],
"colorDiffuse" : [0.28864, 0.28864, 0.28864],
"colorSpecular" : [0.175, 0.175, 0.175],
"illumination" : 2,
"opticalDensity" : 1.0,
"specularCoef" : 27.45098,
"transparency" : 0.0
}],
"buffers": "gallardo_wheel_bin.bin"
}
| zhaodanchun/webgl_learning | 初级教程r73/chapter9/obj/gallardo/parts/gallardo_wheel_bin.js | JavaScript | mit | 961 |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var React = require('React');
var Site = require('Site');
var center = require('center');
var apps = [
{
name: 'Beetroot',
icon: 'http://is1.mzstatic.com/image/pf/us/r30/Purple5/v4/66/fd/dd/66fddd70-f848-4fc5-43ee-4d52197ccab8/pr_source.png',
link: 'https://itunes.apple.com/us/app/beetroot/id1016159001?ls=1&mt=8',
author: 'Alex Duckmanton',
},
{
name: 'Discord',
icon: 'http://a5.mzstatic.com/us/r30/Purple5/v4/c1/2f/4c/c12f4cba-1d9a-f6bf-2240-04085d3470ec/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/discord-chat-for-gamers/id985746746?mt=8',
author: 'Hammer & Chisel',
},
{
name: 'Discovery VR',
icon: 'http://a2.mzstatic.com/us/r30/Purple6/v4/d1/d5/f4/d1d5f437-9f6b-b5aa-5fe7-47bd19f934bf/icon175x175.png',
link: 'https://itunes.apple.com/us/app/discovery-vr/id1030815031?mt=8',
author: 'Discovery Communications',
},
{
name: 'DropBot',
icon: 'http://a2.mzstatic.com/us/r30/Purple69/v4/fb/df/73/fbdf73e0-22d2-c936-3115-1defa195acba/icon175x175.png',
link: 'https://itunes.apple.com/us/app/dropbot-phone-replacement/id1000855694?mt=8',
author: 'Peach Labs',
},
{
name: 'Exponent',
icon: 'http://a4.mzstatic.com/us/r30/Purple2/v4/3a/d3/c9/3ad3c96c-5e14-f988-4bdd-0fdc95efd140/icon175x175.png',
link: 'https://itunes.apple.com/ca/app/exponent/id982107779?mt=8',
author: 'Charlie Cheever & James Ide',
},
{
name: 'F8',
icon: 'http://is4.mzstatic.com/image/pf/us/r30/Purple5/v4/bf/d9/50/bfd9504e-a1bd-67c5-b50b-24e97016dae9/pr_source.jpg',
link: 'https://itunes.apple.com/us/app/f8/id853467066?mt=8',
author: 'Facebook',
},
{
name: 'Facebook Groups',
icon: 'http://is4.mzstatic.com/image/pf/us/r30/Purple69/v4/57/f8/4c/57f84c0c-793d-5f9a-95ee-c212d0369e37/mzl.ugjwfhzx.png',
link: 'https://itunes.apple.com/us/app/facebook-groups/id931735837?mt=8',
author: 'Facebook',
},
{
name: 'Facebook Adverts Manager - Android',
icon: 'https://lh3.googleusercontent.com/ODKlFYm7BaNiLMEEDO2b4DOCU-hmS1-Fg3_x_lLUaJZ0ssFsxciSoX1dYERaWDJuEs8=w300',
link: 'https://play.google.com/store/apps/details?id=com.facebook.adsmanager',
author: 'Facebook',
},
{
name: 'Facebook Ads Manager - iOS',
icon: 'http://is5.mzstatic.com/image/pf/us/r30/Purple5/v4/9e/16/86/9e1686ef-cc55-805a-c977-538ddb5e6832/mzl.gqbhwitj.png',
link: 'https://itunes.apple.com/us/app/facebook-ads-manager/id964397083?mt=8',
author: 'Facebook',
},
{
name: 'FastPaper',
icon: 'http://a2.mzstatic.com/us/r30/Purple5/v4/72/b4/d8/72b4d866-90d2-3aad-d1dc-0315f2d9d045/icon350x350.jpeg',
link: 'https://itunes.apple.com/us/app/fast-paper/id1001174614',
author: 'Liubomyr Mykhalchenko (@liubko)',
},
{
name: 'HSK Level 1 Chinese Flashcards',
icon: 'http://is2.mzstatic.com/image/pf/us/r30/Purple1/v4/b2/4f/3a/b24f3ae3-2597-cc70-1040-731b425a5904/mzl.amxdcktl.jpg',
link: 'https://itunes.apple.com/us/app/hsk-level-1-chinese-flashcards/id936639994',
author: 'HS Schaaf',
},
{
name: 'Leanpub',
icon: 'http://a2.mzstatic.com/us/r30/Purple6/v4/9f/4a/6f/9f4a6f8c-8951-ed89-4083-74ace23df9ef/icon350x350.jpeg',
link: 'https://itunes.apple.com/us/app/leanpub/id913517110?ls=1&mt=8',
author: 'Leanpub',
},
{
name: 'Lrn',
icon: 'http://is4.mzstatic.com/image/pf/us/r30/Purple1/v4/41/a9/e9/41a9e9b6-7801-aef7-2400-2eca14923321/mzl.adyswxad.png',
link: 'https://itunes.apple.com/us/app/lrn-learn-to-code-at-your/id1019622677',
author: 'Lrn Labs, Inc',
},
{
name: 'Lumpen Radio',
icon: 'http://is5.mzstatic.com/image/pf/us/r30/Purple1/v4/46/43/00/464300b1-fae3-9640-d4a2-0eb050ea3ff2/mzl.xjjawige.png',
link: 'https://itunes.apple.com/us/app/lumpen-radio/id1002193127?mt=8',
author: 'Joshua Habdas',
},
{
name: 'MinTrain',
icon: 'http://is5.mzstatic.com/image/pf/us/r30/Purple5/v4/51/51/68/51516875-1323-3100-31a8-cd1853d9a2c0/mzl.gozwmstp.png',
link: 'https://itunes.apple.com/us/app/mintrain/id1015739031?mt=8',
author: 'Peter Cottle',
},
{
name: 'Mr. Dapper',
icon: 'http://is5.mzstatic.com/image/pf/us/r30/Purple4/v4/e8/3f/7c/e83f7cb3-2602-f8e8-de9a-ce0a775a4a14/mzl.hmdjhfai.png',
link: 'https://itunes.apple.com/us/app/mr.-dapper-men-fashion-app/id989735184?ls=1&mt=8',
author: 'wei ping woon',
},
{
name: 'Ncredible',
icon: 'http://a3.mzstatic.com/us/r30/Purple2/v4/a9/00/74/a9007400-7ccf-df10-553b-3b6cb67f3f5f/icon350x350.png',
link: 'https://itunes.apple.com/ca/app/ncredible/id1019662810?mt=8',
author: 'NBC News Digital, LLC',
},
{
name: 'Night Light',
icon: 'http://is3.mzstatic.com/image/pf/us/r30/Purple7/v4/5f/50/5f/5f505fe5-0a30-6bbf-6ed9-81ef09351aba/mzl.lkeqxyeo.png',
link: 'https://itunes.apple.com/gb/app/night-light-feeding-light/id1016843582?mt=8',
author: 'Tian Yuan',
},
{
name: 'ReactTo36',
icon: 'http://is2.mzstatic.com/image/pf/us/r30/Purple5/v4/e3/c8/79/e3c87934-70c6-4974-f20d-4adcfc68d71d/mzl.wevtbbkq.png',
link: 'https://itunes.apple.com/us/app/reactto36/id989009293?mt=8',
author: 'Jonathan Solichin',
},
{
name: 'RN Playground',
icon: 'http://is5.mzstatic.com/image/pf/us/r30/Purple1/v4/20/ec/8e/20ec8eb8-9e12-6686-cd16-7ac9e3ef1d52/mzl.ngvuoybx.png',
link: 'https://itunes.apple.com/us/app/react-native-playground/id1002032944?mt=8',
author: 'Joshua Sierles',
},
{
name: 'SG Toto 4d',
icon: 'http://a4.mzstatic.com/us/r30/Purple7/v4/d2/bc/46/d2bc4696-84d6-9681-a49f-7f660d6b04a7/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/sg-toto-4d/id1006371481?mt=8',
author: 'Steve Ng'
},
{
name: 'Spero for Cancer',
icon: 'https://s3-us-west-1.amazonaws.com/cancerspot/site_images/Spero1024.png',
link: 'https://geo.itunes.apple.com/us/app/spero-for-cancer/id1033923573?mt=8',
author: 'Spero.io',
},
{
name: 'Start - medication manager for depression',
icon: 'http://a1.mzstatic.com/us/r30/Purple49/v4/de/9b/6f/de9b6fe8-84ea-7a12-ba2c-0a6d6c7b10b0/icon175x175.png',
link: 'https://itunes.apple.com/us/app/start-medication-manager-for/id1012099928?mt=8',
author: 'Iodine Inc.',
},
{
name: 'Tabtor Parent',
icon: 'http://a1.mzstatic.com/us/r30/Purple4/v4/80/50/9d/80509d05-18f4-a0b8-0cbb-9ba927d04477/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/tabtor-math/id1018651199?utm_source=ParentAppLP',
author: 'PrazAs Learning Inc.',
},
{
name: 'Tong Xing Wang',
icon: 'http://a3.mzstatic.com/us/r30/Purple1/v4/7d/52/a7/7d52a71f-9532-82a5-b92f-87076624fdb2/icon175x175.jpeg',
link: 'https://itunes.apple.com/cn/app/tong-xing-wang/id914254459?mt=8',
author: 'Ho Yin Tsun Eugene',
},
{
name: 'Yoloci',
icon: 'http://a5.mzstatic.com/eu/r30/Purple7/v4/fa/e5/26/fae52635-b97c-bd53-2ade-89e2a4326745/icon175x175.jpeg',
link: 'https://itunes.apple.com/de/app/yoloci/id991323225?mt=8',
author: 'Yonduva GmbH (@PhilippKrone)',
},
{
name: 'youmeyou',
icon: 'http://is1.mzstatic.com/image/pf/us/r30/Purple7/v4/7c/42/30/7c423042-8945-7733-8af3-1523468706a8/mzl.qlecxphf.png',
link: 'https://itunes.apple.com/us/app/youmeyou/id949540333?mt=8',
author: 'youmeyou, LLC',
},
];
var showcase = React.createClass({
render: function() {
return (
<Site section="showcase" title="Showcase">
<section className="content wrap documentationContent nosidebar">
<div className="inner-content showcaseHeader">
<h1>Apps using React Native</h1>
<div className="subHeader"></div>
<p>
Here is a list of apps using <strong>React Native</strong>. Submit a pull request on <a href="https://github.com/facebook/react-native">GitHub</a> to list your app.
</p>
</div>
{
apps.map((app, i) => {
return (
<a href={app.link} className="showcase" key={i} target="blank">
<img src={app.icon} alt={app.name} />
<h3>{app.name}</h3>
<p>By {app.author}</p>
</a>
);
})
}
</section>
</Site>
);
}
});
module.exports = showcase;
| jackeychens/react-native | website/src/react-native/showcase.js | JavaScript | bsd-3-clause | 8,606 |
//
// Dust - Asynchronous Templating v2.0.3
// http://akdubya.github.com/dustjs
//
// Copyright (c) 2010, Aleksander Williams
// Released under the MIT License.
//
var dust = {};
function getGlobal(){
return (function(){
return this.dust;
}).call(null);
}
(function(dust) {
dust.helpers = {};
dust.cache = {};
dust.register = function(name, tmpl) {
if (!name) return;
dust.cache[name] = tmpl;
};
dust.render = function(name, context, callback) {
var chunk = new Stub(callback).head;
dust.load(name, chunk, Context.wrap(context, name)).end();
};
dust.stream = function(name, context) {
var stream = new Stream();
dust.nextTick(function() {
dust.load(name, stream.head, Context.wrap(context, name)).end();
});
return stream;
};
dust.renderSource = function(source, context, callback) {
return dust.compileFn(source)(context, callback);
};
dust.compileFn = function(source, name) {
var tmpl = dust.loadSource(dust.compile(source, name));
return function(context, callback) {
var master = callback ? new Stub(callback) : new Stream();
dust.nextTick(function() {
tmpl(master.head, Context.wrap(context, name)).end();
});
return master;
};
};
dust.load = function(name, chunk, context) {
var tmpl = dust.cache[name];
if (tmpl) {
return tmpl(chunk, context);
} else {
if (dust.onLoad) {
return chunk.map(function(chunk) {
dust.onLoad(name, function(err, src) {
if (err) return chunk.setError(err);
if (!dust.cache[name]) dust.loadSource(dust.compile(src, name));
dust.cache[name](chunk, context).end();
});
});
}
return chunk.setError(new Error("Template Not Found: " + name));
}
};
dust.loadSource = function(source, path) {
return eval(source);
};
if (Array.isArray) {
dust.isArray = Array.isArray;
} else {
dust.isArray = function(arr) {
return Object.prototype.toString.call(arr) == "[object Array]";
};
}
dust.nextTick = (function() {
if (typeof process !== "undefined") {
return process.nextTick;
} else {
return function(callback) {
setTimeout(callback,0);
};
}
} )();
dust.isEmpty = function(value) {
if (dust.isArray(value) && !value.length) return true;
if (value === 0) return false;
return (!value);
};
// apply the filter chain and return the output string
dust.filter = function(string, auto, filters) {
if (filters) {
for (var i=0, len=filters.length; i<len; i++) {
var name = filters[i];
if (name === "s") {
auto = null;
}
// fail silently for invalid filters
else if (typeof dust.filters[name] === 'function') {
string = dust.filters[name](string);
}
}
}
// by default always apply the h filter, unless asked to unescape with |s
if (auto) {
string = dust.filters[auto](string);
}
return string;
};
dust.filters = {
h: function(value) { return dust.escapeHtml(value); },
j: function(value) { return dust.escapeJs(value); },
u: encodeURI,
uc: encodeURIComponent,
js: function(value) { if (!JSON) { return value; } return JSON.stringify(value); },
jp: function(value) { if (!JSON) { return value; } return JSON.parse(value); }
};
function Context(stack, global, blocks, templateName) {
this.stack = stack;
this.global = global;
this.blocks = blocks;
this.templateName = templateName;
}
dust.makeBase = function(global) {
return new Context(new Stack(), global);
};
Context.wrap = function(context, name) {
if (context instanceof Context) {
return context;
}
return new Context(new Stack(context), {}, null, name);
};
Context.prototype.get = function(key) {
var ctx = this.stack, value;
while(ctx) {
if (ctx.isObject) {
value = ctx.head[key];
if (!(value === undefined)) {
return value;
}
}
ctx = ctx.tail;
}
return this.global ? this.global[key] : undefined;
};
//supports dot path resolution, function wrapped apply, and searching global paths
Context.prototype.getPath = function(cur, down) {
var ctx = this.stack, ctxThis,
len = down.length,
tail = cur ? undefined : this.stack.tail;
if (cur && len === 0) return ctx.head;
ctx = ctx.head;
var i = 0;
while(ctx && i < len) {
ctxThis = ctx;
ctx = ctx[down[i]];
i++;
while (!ctx && !cur){
// i is the count of number of path elements matched. If > 1 then we have a partial match
// and do not continue to search for the rest of the path.
// Note: a falsey value at the end of a matched path also comes here.
// This returns the value or undefined if we just have a partial match.
if (i > 1) return ctx;
if (tail){
ctx = tail.head;
tail = tail.tail;
i=0;
} else if (!cur) {
//finally search this.global. we set cur to true to halt after
ctx = this.global;
cur = true;
i=0;
}
}
}
if (typeof ctx == 'function'){
//wrap to preserve context 'this' see #174
return function(){
return ctx.apply(ctxThis,arguments);
};
}
else {
return ctx;
}
};
Context.prototype.push = function(head, idx, len) {
return new Context(new Stack(head, this.stack, idx, len), this.global, this.blocks, this.templateName);
};
Context.prototype.rebase = function(head) {
return new Context(new Stack(head), this.global, this.blocks, this.templateName);
};
Context.prototype.current = function() {
return this.stack.head;
};
Context.prototype.getBlock = function(key, chk, ctx) {
if (typeof key === "function") {
var tempChk = new Chunk();
key = key(tempChk, this).data.join("");
}
var blocks = this.blocks;
if (!blocks) return;
var len = blocks.length, fn;
while (len--) {
fn = blocks[len][key];
if (fn) return fn;
}
};
Context.prototype.shiftBlocks = function(locals) {
var blocks = this.blocks,
newBlocks;
if (locals) {
if (!blocks) {
newBlocks = [locals];
} else {
newBlocks = blocks.concat([locals]);
}
return new Context(this.stack, this.global, newBlocks, this.templateName);
}
return this;
};
function Stack(head, tail, idx, len) {
this.tail = tail;
this.isObject = !dust.isArray(head) && head && typeof head === "object";
this.head = head;
this.index = idx;
this.of = len;
}
function Stub(callback) {
this.head = new Chunk(this);
this.callback = callback;
this.out = '';
}
Stub.prototype.flush = function() {
var chunk = this.head;
while (chunk) {
if (chunk.flushable) {
this.out += chunk.data.join(""); //ie7 perf
} else if (chunk.error) {
this.callback(chunk.error);
this.flush = function() {};
return;
} else {
return;
}
chunk = chunk.next;
this.head = chunk;
}
this.callback(null, this.out);
};
function Stream() {
this.head = new Chunk(this);
}
Stream.prototype.flush = function() {
var chunk = this.head;
while(chunk) {
if (chunk.flushable) {
this.emit('data', chunk.data.join("")); //ie7 perf
} else if (chunk.error) {
this.emit('error', chunk.error);
this.flush = function() {};
return;
} else {
return;
}
chunk = chunk.next;
this.head = chunk;
}
this.emit('end');
};
Stream.prototype.emit = function(type, data) {
if (!this.events) return false;
var handler = this.events[type];
if (!handler) return false;
if (typeof handler == 'function') {
handler(data);
} else {
var listeners = handler.slice(0);
for (var i = 0, l = listeners.length; i < l; i++) {
listeners[i](data);
}
}
};
Stream.prototype.on = function(type, callback) {
if (!this.events) {
this.events = {};
}
if (!this.events[type]) {
this.events[type] = callback;
} else if(typeof this.events[type] === 'function') {
this.events[type] = [this.events[type], callback];
} else {
this.events[type].push(callback);
}
return this;
};
Stream.prototype.pipe = function(stream) {
this.on("data", function(data) {
stream.write(data, "utf8");
}).on("end", function() {
stream.end();
}).on("error", function(err) {
stream.error(err);
});
return this;
};
function Chunk(root, next, taps) {
this.root = root;
this.next = next;
this.data = []; //ie7 perf
this.flushable = false;
this.taps = taps;
}
Chunk.prototype.write = function(data) {
var taps = this.taps;
if (taps) {
data = taps.go(data);
}
this.data.push(data);
return this;
};
Chunk.prototype.end = function(data) {
if (data) {
this.write(data);
}
this.flushable = true;
this.root.flush();
return this;
};
Chunk.prototype.map = function(callback) {
var cursor = new Chunk(this.root, this.next, this.taps),
branch = new Chunk(this.root, cursor, this.taps);
this.next = branch;
this.flushable = true;
callback(branch);
return cursor;
};
Chunk.prototype.tap = function(tap) {
var taps = this.taps;
if (taps) {
this.taps = taps.push(tap);
} else {
this.taps = new Tap(tap);
}
return this;
};
Chunk.prototype.untap = function() {
this.taps = this.taps.tail;
return this;
};
Chunk.prototype.render = function(body, context) {
return body(this, context);
};
Chunk.prototype.reference = function(elem, context, auto, filters) {
if (typeof elem === "function") {
elem.isFunction = true;
// Changed the function calling to use apply with the current context to make sure
// that "this" is wat we expect it to be inside the function
elem = elem.apply(context.current(), [this, context, null, {auto: auto, filters: filters}]);
if (elem instanceof Chunk) {
return elem;
}
}
if (!dust.isEmpty(elem)) {
return this.write(dust.filter(elem, auto, filters));
} else {
return this;
}
};
Chunk.prototype.section = function(elem, context, bodies, params) {
// anonymous functions
if (typeof elem === "function") {
elem = elem.apply(context.current(), [this, context, bodies, params]);
// functions that return chunks are assumed to have handled the body and/or have modified the chunk
// use that return value as the current chunk and go to the next method in the chain
if (elem instanceof Chunk) {
return elem;
}
}
var body = bodies.block,
skip = bodies['else'];
// a.k.a Inline parameters in the Dust documentations
if (params) {
context = context.push(params);
}
/*
Dust's default behavior is to enumerate over the array elem, passing each object in the array to the block.
When elem resolves to a value or object instead of an array, Dust sets the current context to the value
and renders the block one time.
*/
//non empty array is truthy, empty array is falsy
if (dust.isArray(elem)) {
if (body) {
var len = elem.length, chunk = this;
if (len > 0) {
// any custom helper can blow up the stack
// and store a flattened context, guard defensively
if(context.stack.head) {
context.stack.head['$len'] = len;
}
for (var i=0; i<len; i++) {
if(context.stack.head) {
context.stack.head['$idx'] = i;
}
chunk = body(chunk, context.push(elem[i], i, len));
}
if(context.stack.head) {
context.stack.head['$idx'] = undefined;
context.stack.head['$len'] = undefined;
}
return chunk;
}
else if (skip) {
return skip(this, context);
}
}
}
// true is truthy but does not change context
else if (elem === true) {
if (body) {
return body(this, context);
}
}
// everything that evaluates to true are truthy ( e.g. Non-empty strings and Empty objects are truthy. )
// zero is truthy
// for anonymous functions that did not returns a chunk, truthiness is evaluated based on the return value
//
else if (elem || elem === 0) {
if (body) return body(this, context.push(elem));
// nonexistent, scalar false value, scalar empty string, null,
// undefined are all falsy
} else if (skip) {
return skip(this, context);
}
return this;
};
Chunk.prototype.exists = function(elem, context, bodies) {
var body = bodies.block,
skip = bodies['else'];
if (!dust.isEmpty(elem)) {
if (body) return body(this, context);
} else if (skip) {
return skip(this, context);
}
return this;
};
Chunk.prototype.notexists = function(elem, context, bodies) {
var body = bodies.block,
skip = bodies['else'];
if (dust.isEmpty(elem)) {
if (body) return body(this, context);
} else if (skip) {
return skip(this, context);
}
return this;
};
Chunk.prototype.block = function(elem, context, bodies) {
var body = bodies.block;
if (elem) {
body = elem;
}
if (body) {
return body(this, context);
}
return this;
};
Chunk.prototype.partial = function(elem, context, params) {
var partialContext;
//put the params context second to match what section does. {.} matches the current context without parameters
// start with an empty context
partialContext = dust.makeBase(context.global);
partialContext.blocks = context.blocks;
if (context.stack && context.stack.tail){
// grab the stack(tail) off of the previous context if we have it
partialContext.stack = context.stack.tail;
}
if (params){
//put params on
partialContext = partialContext.push(params);
}
if(typeof elem === "string") {
partialContext.templateName = elem;
}
//reattach the head
partialContext = partialContext.push(context.stack.head);
var partialChunk;
if (typeof elem === "function") {
partialChunk = this.capture(elem, partialContext, function(name, chunk) {
dust.load(name, chunk, partialContext).end();
});
}
else {
partialChunk = dust.load(elem, this, partialContext);
}
return partialChunk;
};
Chunk.prototype.helper = function(name, context, bodies, params) {
// handle invalid helpers, similar to invalid filters
if( dust.helpers[name]){
return dust.helpers[name](this, context, bodies, params);
} else {
return this;
}
};
Chunk.prototype.capture = function(body, context, callback) {
return this.map(function(chunk) {
var stub = new Stub(function(err, out) {
if (err) {
chunk.setError(err);
} else {
callback(out, chunk);
}
});
body(stub.head, context).end();
});
};
Chunk.prototype.setError = function(err) {
this.error = err;
this.root.flush();
return this;
};
function Tap(head, tail) {
this.head = head;
this.tail = tail;
}
Tap.prototype.push = function(tap) {
return new Tap(tap, this);
};
Tap.prototype.go = function(value) {
var tap = this;
while(tap) {
value = tap.head(value);
tap = tap.tail;
}
return value;
};
var HCHARS = new RegExp(/[&<>\"\']/),
AMP = /&/g,
LT = /</g,
GT = />/g,
QUOT = /\"/g,
SQUOT = /\'/g;
dust.escapeHtml = function(s) {
if (typeof s === "string") {
if (!HCHARS.test(s)) {
return s;
}
return s.replace(AMP,'&').replace(LT,'<').replace(GT,'>').replace(QUOT,'"').replace(SQUOT, ''');
}
return s;
};
var BS = /\\/g,
FS = /\//g,
CR = /\r/g,
LS = /\u2028/g,
PS = /\u2029/g,
NL = /\n/g,
LF = /\f/g,
SQ = /'/g,
DQ = /"/g,
TB = /\t/g;
dust.escapeJs = function(s) {
if (typeof s === "string") {
return s
.replace(BS, '\\\\')
.replace(FS, '\\/')
.replace(DQ, '\\"')
.replace(SQ, "\\'")
.replace(CR, '\\r')
.replace(LS, '\\u2028')
.replace(PS, '\\u2029')
.replace(NL, '\\n')
.replace(LF, '\\f')
.replace(TB, "\\t");
}
return s;
};
})(dust);
if (typeof exports !== "undefined") {
if (typeof process !== "undefined") {
require('./server')(dust);
}
module.exports = dust;
}
| NinoScript/resume | src/node_modules/dustjs-linkedin/dist/dust-core-2.0.3.js | JavaScript | mit | 15,916 |
'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": [
"vm.",
"nm."
],
"DAY": [
"Sondag",
"Maandag",
"Dinsdag",
"Woensdag",
"Donderdag",
"Vrydag",
"Saterdag"
],
"ERANAMES": [
"voor Christus",
"na Christus"
],
"ERAS": [
"v.C.",
"n.C."
],
"FIRSTDAYOFWEEK": 6,
"MONTH": [
"Januarie",
"Februarie",
"Maart",
"April",
"Mei",
"Junie",
"Julie",
"Augustus",
"September",
"Oktober",
"November",
"Desember"
],
"SHORTDAY": [
"So.",
"Ma.",
"Di.",
"Wo.",
"Do.",
"Vr.",
"Sa."
],
"SHORTMONTH": [
"Jan.",
"Feb.",
"Mrt.",
"Apr.",
"Mei",
"Jun.",
"Jul.",
"Aug.",
"Sep.",
"Okt.",
"Nov.",
"Des."
],
"STANDALONEMONTH": [
"Januarie",
"Februarie",
"Maart",
"April",
"Mei",
"Junie",
"Julie",
"Augustus",
"September",
"Oktober",
"November",
"Desember"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, dd MMMM y",
"longDate": "dd MMMM y",
"medium": "dd MMM y HH:mm:ss",
"mediumDate": "dd MMM y",
"mediumTime": "HH:mm:ss",
"short": "y-MM-dd HH:mm",
"shortDate": "y-MM-dd",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "R",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-\u00a4",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "af",
"localeID": "af",
"pluralCat": function(n, opt_precision) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| LearnNavi/Naranawm | www/assets/library/angular-1.6.5/i18n/angular-locale_af.js | JavaScript | agpl-3.0 | 2,344 |
'use strict';
/* jshint -W030 */
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/support')
, DataTypes = require(__dirname + '/../../lib/data-types');
describe(Support.getTestDialectTeaser('Schema'), function() {
beforeEach(function() {
return this.sequelize.createSchema('testschema');
});
afterEach(function() {
return this.sequelize.dropSchema('testschema');
});
beforeEach(function() {
this.User = this.sequelize.define('User', {
aNumber: { type: DataTypes.INTEGER }
}, {
schema: 'testschema'
});
return this.User.sync({ force: true });
});
it('supports increment', function() {
return this.User.create({ aNumber: 1 }).then(function(user) {
return user.increment('aNumber', { by: 3 });
}).then(function(result) {
return result.reload();
}).then(function(user) {
expect(user).to.be.ok;
expect(user.aNumber).to.be.equal(4);
});
});
it('supports decrement', function() {
return this.User.create({ aNumber: 10 }).then(function(user) {
return user.decrement('aNumber', { by: 3 });
}).then(function(result) {
return result.reload();
}).then(function(user) {
expect(user).to.be.ok;
expect(user.aNumber).to.be.equal(7);
});
});
});
| atorkhov/sequelize | test/integration/schema.test.js | JavaScript | mit | 1,312 |
module.exports={title:"TYPO3",slug:"typo3",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>TYPO3 icon</title><path d="M18.08 16.539c-.356.105-.64.144-1.012.144-3.048 0-7.524-10.652-7.524-14.197 0-1.305.31-1.74.745-2.114C6.56.808 2.082 2.177.651 3.917c-.31.436-.497 1.12-.497 1.99C.154 11.442 6.06 24 10.228 24c1.928 0 5.178-3.168 7.852-7.46M16.134 0c3.855 0 7.713.622 7.713 2.798 0 4.415-2.8 9.765-4.23 9.765-2.549 0-5.72-7.09-5.72-10.635C13.897.31 14.518 0 16.134 0"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://typo3.com/fileadmin/assets/typo3logos/typo3_bullet_01.svg",hex:"FF8700"}; | cdnjs/cdnjs | ajax/libs/simple-icons/4.9.0/typo3.min.js | JavaScript | mit | 660 |
goog.setTestOnly('query_test');
goog.require('goog.dom');
goog.require('goog.userAgent');
function testBasicSelectors() {
assertQuery(4, 'h3');
assertQuery(1, 'h1:first-child');
assertQuery(2, 'h3:first-child');
assertQuery(1, '#t');
assertQuery(1, '#bug');
assertQuery(4, '#t h3');
assertQuery(1, 'div#t');
assertQuery(4, 'div#t h3');
assertQuery(0, 'span#t');
assertQuery(1, '#t div > h3');
assertQuery(2, '.foo');
assertQuery(1, '.foo.bar');
assertQuery(2, '.baz');
assertQuery(3, '#t > h3');
}
function testSyntacticEquivalents() {
// syntactic equivalents
assertQuery(12, '#t > *');
assertQuery(12, '#t >');
assertQuery(3, '.foo > *');
assertQuery(3, '.foo >');
}
function testWithARootById() {
// Broken in latest chrome.
if (goog.userAgent.WEBKIT) {
return;
}
// with a root, by ID
assertQuery(3, '> *', 'container');
assertQuery(3, '> h3', 't');
}
function testCompoundQueries() {
// compound queries
assertQuery(2, '.foo, .bar');
assertQuery(2, '.foo,.bar');
}
function testMultipleClassAttributes() {
// multiple class attribute
assertQuery(1, '.foo.bar');
assertQuery(2, '.foo');
assertQuery(2, '.baz');
}
function testCaseSensitivity() {
// case sensitivity
assertQuery(1, 'span.baz');
assertQuery(1, 'sPaN.baz');
assertQuery(1, 'SPAN.baz');
assertQuery(1, '[class = \"foo bar\"]');
assertQuery(2, '[foo~=\"bar\"]');
assertQuery(2, '[ foo ~= \"bar\" ]');
}
function testAttributes() {
assertQuery(3, '[foo]');
assertQuery(1, '[foo$=\"thud\"]');
assertQuery(1, '[foo$=thud]');
assertQuery(1, '[foo$=\"thudish\"]');
assertQuery(1, '#t [foo$=thud]');
assertQuery(1, '#t [ title $= thud ]');
assertQuery(0, '#t span[ title $= thud ]');
assertQuery(2, '[foo|=\"bar\"]');
assertQuery(1, '[foo|=\"bar-baz\"]');
assertQuery(0, '[foo|=\"baz\"]');
}
function testDescendantSelectors() {
// Broken in latest chrome.
if (goog.userAgent.WEBKIT) {
return;
}
assertQuery(3, '>', 'container');
assertQuery(3, '> *', 'container');
assertQuery(2, '> [qux]', 'container');
assertEquals('child1', goog.dom.query('> [qux]', 'container')[0].id);
assertEquals('child3', goog.dom.query('> [qux]', 'container')[1].id);
assertQuery(3, '>', 'container');
assertQuery(3, '> *', 'container');
}
function testSiblingSelectors() {
assertQuery(1, '+', 'container');
assertQuery(3, '~', 'container');
assertQuery(1, '.foo + span');
assertQuery(4, '.foo ~ span');
assertQuery(1, '#foo ~ *');
assertQuery(1, '#foo ~');
}
function testSubSelectors() {
// sub-selector parsing
assertQuery(1, '#t span.foo:not(span:first-child)');
assertQuery(1, '#t span.foo:not(:first-child)');
}
function testNthChild() {
assertEquals(goog.dom.$('_foo'), goog.dom.query('.foo:nth-child(2)')[0]);
assertQuery(2, '#t > h3:nth-child(odd)');
assertQuery(3, '#t h3:nth-child(odd)');
assertQuery(3, '#t h3:nth-child(2n+1)');
assertQuery(1, '#t h3:nth-child(even)');
assertQuery(1, '#t h3:nth-child(2n)');
assertQuery(1, '#t h3:nth-child(2n+3)');
assertQuery(2, '#t h3:nth-child(1)');
assertQuery(1, '#t > h3:nth-child(1)');
assertQuery(3, '#t :nth-child(3)');
assertQuery(0, '#t > div:nth-child(1)');
assertQuery(7, '#t span');
assertQuery(3, '#t > *:nth-child(n+10)');
assertQuery(1, '#t > *:nth-child(n+12)');
assertQuery(10, '#t > *:nth-child(-n+10)');
assertQuery(5, '#t > *:nth-child(-2n+10)');
assertQuery(6, '#t > *:nth-child(2n+2)');
assertQuery(5, '#t > *:nth-child(2n+4)');
assertQuery(5, '#t > *:nth-child(2n+4)');
assertQuery(12, '#t > *:nth-child(n-5)');
assertQuery(6, '#t > *:nth-child(2n-5)');
}
function testEmptyPseudoSelector() {
assertQuery(4, '#t > span:empty');
assertQuery(6, '#t span:empty');
assertQuery(0, 'h3 span:empty');
assertQuery(1, 'h3 :not(:empty)');
}
function testIdsWithColons() {
assertQuery(1, '#silly\\:id\\:\\:with\\:colons');
}
function testOrder() {
var els = goog.dom.query('.myupperclass .myclass input');
assertEquals('myid1', els[0].id);
assertEquals('myid2', els[1].id);
}
function testCorrectDocumentInFrame() {
var frameDocument = window.frames['ifr'].document;
frameDocument.body.innerHTML =
document.getElementById('iframe-test').innerHTML;
var els = goog.dom.query('#if1 .if2 div', document);
var frameEls = goog.dom.query('#if1 .if2 div', frameDocument);
assertEquals(els.length, frameEls.length);
assertEquals(1, frameEls.length);
assertNotEquals(document.getElementById('if3'),
frameDocument.getElementById('if3'));
}
/**
* @param {number} expectedNumberOfNodes
* @param {...*} var_args
*/
function assertQuery(expectedNumberOfNodes, var_args) {
var args = Array.prototype.slice.call(arguments, 1);
assertEquals(expectedNumberOfNodes,
goog.dom.query.apply(null, args).length);
}
| Serard/cmsulysse | web/js/verifphone/goog/closure-library-master/third_party/closure/goog/dojo/dom/query_test.js | JavaScript | lgpl-3.0 | 4,874 |
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var invariant = require('fbjs/lib/invariant');
/**
* Static poolers. Several custom versions for each potential number of
* arguments. A completely generic pooler is easy to implement, but would
* require accessing the `arguments` object. In each of these, `this` refers to
* the Class itself, not an instance. If any others are needed, simply add them
* here, or in their own files.
*/
var oneArgumentPooler = function (copyFieldsFrom) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, copyFieldsFrom);
return instance;
} else {
return new Klass(copyFieldsFrom);
}
};
var twoArgumentPooler = function (a1, a2) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2);
return instance;
} else {
return new Klass(a1, a2);
}
};
var threeArgumentPooler = function (a1, a2, a3) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3);
return instance;
} else {
return new Klass(a1, a2, a3);
}
};
var fourArgumentPooler = function (a1, a2, a3, a4) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4);
return instance;
} else {
return new Klass(a1, a2, a3, a4);
}
};
var standardReleaser = function (instance) {
var Klass = this;
!(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : void 0;
instance.destructor();
if (Klass.instancePool.length < Klass.poolSize) {
Klass.instancePool.push(instance);
}
};
var DEFAULT_POOL_SIZE = 10;
var DEFAULT_POOLER = oneArgumentPooler;
/**
* Augments `CopyConstructor` to be a poolable class, augmenting only the class
* itself (statically) not adding any prototypical fields. Any CopyConstructor
* you give this may have a `poolSize` property, and will look for a
* prototypical `destructor` on instances.
*
* @param {Function} CopyConstructor Constructor that can be used to reset.
* @param {Function} pooler Customizable pooler.
*/
var addPoolingTo = function (CopyConstructor, pooler) {
// Casting as any so that flow ignores the actual implementation and trusts
// it to match the type we declared
var NewKlass = CopyConstructor;
NewKlass.instancePool = [];
NewKlass.getPooled = pooler || DEFAULT_POOLER;
if (!NewKlass.poolSize) {
NewKlass.poolSize = DEFAULT_POOL_SIZE;
}
NewKlass.release = standardReleaser;
return NewKlass;
};
var PooledClass = {
addPoolingTo: addPoolingTo,
oneArgumentPooler: oneArgumentPooler,
twoArgumentPooler: twoArgumentPooler,
threeArgumentPooler: threeArgumentPooler,
fourArgumentPooler: fourArgumentPooler
};
module.exports = PooledClass; | puyanLiu/LPYFramework | 前端练习/autoFramework/webpack-demo3/node_modules/react/lib/PooledClass.js | JavaScript | apache-2.0 | 3,356 |
/*! tableSorter 2.8+ widgets - updated 10/18/2013
*
* Column Styles
* Column Filters
* Column Resizing
* Sticky Header
* UI Theme (generalized)
* Save Sort
* [ "columns", "filter", "resizable", "stickyHeaders", "uitheme", "saveSort" ]
*/
/*jshint browser:true, jquery:true, unused:false, loopfunc:true */
/*global jQuery: false, localStorage: false, navigator: false */
;(function($){
"use strict";
var ts = $.tablesorter = $.tablesorter || {};
ts.themes = {
"bootstrap" : {
table : 'table table-bordered table-striped',
header : 'bootstrap-header', // give the header a gradient background
footerRow : '',
footerCells: '',
icons : '', // add "icon-white" to make them white; this icon class is added to the <i> in the header
sortNone : 'bootstrap-icon-unsorted',
sortAsc : 'icon-chevron-up glyphicon glyphicon-chevron-up',
sortDesc : 'icon-chevron-down glyphicon glyphicon-chevron-down',
active : '', // applied when column is sorted
hover : '', // use custom css here - bootstrap class may not override it
filterRow : '', // filter row class
even : '', // even row zebra striping
odd : '' // odd row zebra striping
},
"jui" : {
table : 'ui-widget ui-widget-content ui-corner-all', // table classes
header : 'ui-widget-header ui-corner-all ui-state-default', // header classes
footerRow : '',
footerCells: '',
icons : 'ui-icon', // icon class added to the <i> in the header
sortNone : 'ui-icon-carat-2-n-s',
sortAsc : 'ui-icon-carat-1-n',
sortDesc : 'ui-icon-carat-1-s',
active : 'ui-state-active', // applied when column is sorted
hover : 'ui-state-hover', // hover class
filterRow : '',
even : 'ui-widget-content', // even row zebra striping
odd : 'ui-state-default' // odd row zebra striping
}
};
// *** Store data in local storage, with a cookie fallback ***
/* IE7 needs JSON library for JSON.stringify - (http://caniuse.com/#search=json)
if you need it, then include https://github.com/douglascrockford/JSON-js
$.parseJSON is not available is jQuery versions older than 1.4.1, using older
versions will only allow storing information for one page at a time
// *** Save data (JSON format only) ***
// val must be valid JSON... use http://jsonlint.com/ to ensure it is valid
var val = { "mywidget" : "data1" }; // valid JSON uses double quotes
// $.tablesorter.storage(table, key, val);
$.tablesorter.storage(table, 'tablesorter-mywidget', val);
// *** Get data: $.tablesorter.storage(table, key); ***
v = $.tablesorter.storage(table, 'tablesorter-mywidget');
// val may be empty, so also check for your data
val = (v && v.hasOwnProperty('mywidget')) ? v.mywidget : '';
alert(val); // "data1" if saved, or "" if not
*/
ts.storage = function(table, key, val, options){
var d, k, ls = false, v = {},
c = table.config,
id = options && options.id || $(table).attr(options && options.group || 'data-table-group') || table.id || $('.tablesorter').index( $(table) ),
url = options && options.url || $(table).attr(options && options.page || 'data-table-page') || c && c.fixedUrl || window.location.pathname;
// https://gist.github.com/paulirish/5558557
if ("localStorage" in window) {
try {
window.localStorage.setItem('_tmptest', 'temp');
ls = true;
window.localStorage.removeItem('_tmptest');
} catch(e) {}
}
// *** get val ***
if ($.parseJSON){
if (ls){
v = $.parseJSON(localStorage[key] || '{}');
} else {
k = document.cookie.split(/[;\s|=]/); // cookie
d = $.inArray(key, k) + 1; // add one to get from the key to the value
v = (d !== 0) ? $.parseJSON(k[d] || '{}') : {};
}
}
// allow val to be an empty string to
if ((val || val === '') && window.JSON && JSON.hasOwnProperty('stringify')){
// add unique identifiers = url pathname > table ID/index on page > data
if (!v[url]) {
v[url] = {};
}
v[url][id] = val;
// *** set val ***
if (ls){
localStorage[key] = JSON.stringify(v);
} else {
d = new Date();
d.setTime(d.getTime() + (31536e+6)); // 365 days
document.cookie = key + '=' + (JSON.stringify(v)).replace(/\"/g,'\"') + '; expires=' + d.toGMTString() + '; path=/';
}
} else {
return v && v[url] ? v[url][id] : {};
}
};
// Add a resize event to table headers
// **************************
ts.addHeaderResizeEvent = function(table, disable, options){
var defaults = {
timer : 250
},
o = $.extend({}, defaults, options),
c = table.config,
wo = c.widgetOptions,
headers,
checkSizes = function(){
wo.resize_flag = true;
headers = [];
c.$headers.each(function(){
var d = $.data(this, 'savedSizes'),
w = this.offsetWidth,
h = this.offsetHeight;
if (w !== d[0] || h !== d[1]) {
$.data(this, 'savedSizes', [ w, h ]);
headers.push(this);
}
});
if (headers.length) { c.$table.trigger('resize', [ headers ]); }
wo.resize_flag = false;
};
clearInterval(wo.resize_timer);
if (disable) {
wo.resize_flag = false;
return false;
}
c.$headers.each(function(){
$.data(this, 'savedSizes', [ this.offsetWidth, this.offsetHeight ]);
});
wo.resize_timer = setInterval(function(){
if (wo.resize_flag) { return; }
checkSizes();
}, o.timer);
};
// Widget: General UI theme
// "uitheme" option in "widgetOptions"
// **************************
ts.addWidget({
id: "uitheme",
priority: 10,
options: {
uitheme : 'jui'
},
format: function(table, c, wo){
var time, klass, $el, $tar,
t = ts.themes,
$t = c.$table,
theme = c.theme !== 'default' ? c.theme : wo.uitheme || 'jui',
o = t[ t[theme] ? theme : t[wo.uitheme] ? wo.uitheme : 'jui'],
$h = c.$headers,
sh = 'tr.' + (wo.stickyHeaders || 'tablesorter-stickyHeader'),
rmv = o.sortNone + ' ' + o.sortDesc + ' ' + o.sortAsc;
if (c.debug) { time = new Date(); }
if (!$t.hasClass('tablesorter-' + theme) || c.theme === theme || !table.hasInitialized){
// update zebra stripes
if (o.even !== '') { wo.zebra[0] += ' ' + o.even; }
if (o.odd !== '') { wo.zebra[1] += ' ' + o.odd; }
// add table/footer class names
t = $t
// remove other selected themes; use widgetOptions.theme_remove
.removeClass( c.theme === '' ? '' : 'tablesorter-' + c.theme )
.addClass('tablesorter-' + theme + ' ' + o.table) // add theme widget class name
.find('tfoot');
if (t.length) {
t
.find('tr').addClass(o.footerRow)
.children('th, td').addClass(o.footerCells);
}
// update header classes
$h
.addClass(o.header)
.filter(':not(.sorter-false)')
.bind('mouseenter.tsuitheme mouseleave.tsuitheme', function(e){
// toggleClass with switch added in jQuery 1.3
$(this)[ e.type === 'mouseenter' ? 'addClass' : 'removeClass' ](o.hover);
});
if (!$h.find('.tablesorter-wrapper').length) {
// Firefox needs this inner div to position the resizer correctly
$h.wrapInner('<div class="tablesorter-wrapper" style="position:relative;height:100%;width:100%"></div>');
}
if (c.cssIcon){
// if c.cssIcon is '', then no <i> is added to the header
$h.find('.' + ts.css.icon).addClass(o.icons);
}
if ($t.hasClass('hasFilters')){
$h.find('.tablesorter-filter-row').addClass(o.filterRow);
}
}
$.each($h, function(i){
$el = $(this);
$tar = (ts.css.icon) ? $el.find('.' + ts.css.icon) : $el;
if (this.sortDisabled){
// no sort arrows for disabled columns!
$el.removeClass(rmv);
$tar.removeClass(rmv + ' tablesorter-icon ' + o.icons);
} else {
t = ($t.hasClass('hasStickyHeaders')) ? $t.find(sh).find('th').eq(i).add($el) : $el;
klass = ($el.hasClass(ts.css.sortAsc)) ? o.sortAsc : ($el.hasClass(ts.css.sortDesc)) ? o.sortDesc : $el.hasClass(ts.css.header) ? o.sortNone : '';
$el[klass === o.sortNone ? 'removeClass' : 'addClass'](o.active);
$tar.removeClass(rmv).addClass(klass);
}
});
if (c.debug){
ts.benchmark("Applying " + theme + " theme", time);
}
},
remove: function(table, c, wo){
var $t = c.$table,
theme = typeof wo.uitheme === 'object' ? 'jui' : wo.uitheme || 'jui',
o = typeof wo.uitheme === 'object' ? wo.uitheme : ts.themes[ ts.themes.hasOwnProperty(theme) ? theme : 'jui'],
$h = $t.children('thead').children(),
rmv = o.sortNone + ' ' + o.sortDesc + ' ' + o.sortAsc;
$t
.removeClass('tablesorter-' + theme + ' ' + o.table)
.find(ts.css.header).removeClass(o.header);
$h
.unbind('mouseenter.tsuitheme mouseleave.tsuitheme') // remove hover
.removeClass(o.hover + ' ' + rmv + ' ' + o.active)
.find('.tablesorter-filter-row').removeClass(o.filterRow);
$h.find('.tablesorter-icon').removeClass(o.icons);
}
});
// Widget: Column styles
// "columns", "columns_thead" (true) and
// "columns_tfoot" (true) options in "widgetOptions"
// **************************
ts.addWidget({
id: "columns",
priority: 30,
options : {
columns : [ "primary", "secondary", "tertiary" ]
},
format: function(table, c, wo){
var $tb, $tr, $td, $t, time, last, rmv, i, k, l,
$tbl = c.$table,
b = c.$tbodies,
list = c.sortList,
len = list.length,
// keep backwards compatibility, for now
css = (c.widgetColumns && c.widgetColumns.hasOwnProperty('css')) ? c.widgetColumns.css || css :
(wo && wo.hasOwnProperty('columns')) ? wo.columns || css : css;
last = css.length-1;
rmv = css.join(' ');
if (c.debug){
time = new Date();
}
// check if there is a sort (on initialization there may not be one)
for (k = 0; k < b.length; k++ ){
$tb = ts.processTbody(table, b.eq(k), true); // detach tbody
$tr = $tb.children('tr');
l = $tr.length;
// loop through the visible rows
$tr.each(function(){
$t = $(this);
if (this.style.display !== 'none'){
// remove all columns class names
$td = $t.children().removeClass(rmv);
// add appropriate column class names
if (list && list[0]){
// primary sort column class
$td.eq(list[0][0]).addClass(css[0]);
if (len > 1){
for (i = 1; i < len; i++){
// secondary, tertiary, etc sort column classes
$td.eq(list[i][0]).addClass( css[i] || css[last] );
}
}
}
}
});
ts.processTbody(table, $tb, false);
}
// add classes to thead and tfoot
$tr = wo.columns_thead !== false ? ['thead tr'] : [];
if (wo.columns_tfoot !== false) {
$tr.push('tfoot tr');
}
if ($tr.length) {
$t = $tbl.find($tr.join(',')).children().removeClass(rmv);
if (len){
for (i = 0; i < len; i++){
// add primary. secondary, tertiary, etc sort column classes
$t.filter('[data-column="' + list[i][0] + '"]').addClass(css[i] || css[last]);
}
}
}
if (c.debug){
ts.benchmark("Applying Columns widget", time);
}
},
remove: function(table, c, wo){
var k, $tb,
b = c.$tbodies,
rmv = (wo.columns || [ "primary", "secondary", "tertiary" ]).join(' ');
c.$headers.removeClass(rmv);
c.$table.children('tfoot').children('tr').children('th, td').removeClass(rmv);
for (k = 0; k < b.length; k++ ){
$tb = ts.processTbody(table, b.eq(k), true); // remove tbody
$tb.children('tr').each(function(){
$(this).children().removeClass(rmv);
});
ts.processTbody(table, $tb, false); // restore tbody
}
}
});
// Widget: filter
// **************************
ts.addWidget({
id: "filter",
priority: 50,
options : {
filter_childRows : false, // if true, filter includes child row content in the search
filter_columnFilters : true, // if true, a filter will be added to the top of each table column
filter_cssFilter : '', // css class name added to the filter row & each input in the row (tablesorter-filter is ALWAYS added)
filter_filteredRow : 'filtered', // class added to filtered rows; needed by pager plugin
filter_formatter : null, // add custom filter elements to the filter row
filter_functions : null, // add custom filter functions using this option
filter_hideFilters : false, // collapse filter row when mouse leaves the area
filter_ignoreCase : true, // if true, make all searches case-insensitive
filter_liveSearch : true, // if true, search column content while the user types (with a delay)
filter_onlyAvail : 'filter-onlyAvail', // a header with a select dropdown & this class name will only show available (visible) options within the drop down
filter_reset : null, // jQuery selector string of an element used to reset the filters
filter_searchDelay : 300, // typing delay in milliseconds before starting a search
filter_startsWith : false, // if true, filter start from the beginning of the cell contents
filter_useParsedData : false, // filter all data using parsed content
filter_serversideFiltering : false, // if true, server-side filtering should be performed because client-side filtering will be disabled, but the ui and events will still be used.
filter_defaultAttrib : 'data-value', // data attribute in the header cell that contains the default filter value
// regex used in filter "check" functions - not for general use and not documented
filter_regex : {
"regex" : /^\/((?:\\\/|[^\/])+)\/([mig]{0,3})?$/, // regex to test for regex
"child" : /tablesorter-childRow/, // child row class name; this gets updated in the script
"filtered" : /filtered/, // filtered (hidden) row class name; updated in the script
"type" : /undefined|number/, // check type
"exact" : /(^[\"|\'|=]+)|([\"|\'|=]+$)/g, // exact match (allow '==')
"nondigit" : /[^\w,. \-()]/g, // replace non-digits (from digit & currency parser)
"operators" : /[<>=]/g // replace operators
}
},
format: function(table, c, wo){
if (c.$table.hasClass('hasFilters')) { return; }
// allow filter widget to work if it is being used
if (c.parsers || !c.parsers && wo.filter_serversideFiltering){
var i, j, k, l, val, ff, x, xi, st, sel, str,
ft, ft2, $th, rg, s, t, dis, col,
fmt = ts.formatFloat,
last = '', // save last filter search
$ths = c.$headers,
$t = c.$table.addClass('hasFilters'),
b = c.$tbodies,
// c.columns defined in computeThIndexes()
cols = c.columns || c.$headers.filter('th').length,
parsed, time, timer,
// dig fer gold
checkFilters = function(filter){
var arry = $.isArray(filter),
v = (arry) ? filter : ts.getFilters(table),
cv = (v || []).join(''); // combined filter values
// add filter array back into inputs
if (arry) {
ts.setFilters( $t, v );
}
if (wo.filter_hideFilters){
// show/hide filter row as needed
$t.find('.tablesorter-filter-row').trigger( cv === '' ? 'mouseleave' : 'mouseenter' );
}
// return if the last search is the same; but filter === false when updating the search
// see example-widget-filter.html filter toggle buttons
if (last === cv && filter !== false) { return; }
$t.trigger('filterStart', [v]);
if (c.showProcessing) {
// give it time for the processing icon to kick in
setTimeout(function(){
findRows(filter, v, cv);
return false;
}, 30);
} else {
findRows(filter, v, cv);
return false;
}
},
findRows = function(filter, v, cv){
var $tb, $tr, $td, cr, r, l, ff, time, r1, r2, searchFiltered;
if (c.debug) { time = new Date(); }
for (k = 0; k < b.length; k++ ){
if (b.eq(k).hasClass(ts.css.info)) { continue; } // ignore info blocks, issue #264
$tb = ts.processTbody(table, b.eq(k), true);
$tr = $tb.children('tr:not(.' + c.cssChildRow + ')');
l = $tr.length;
if (cv === '' || wo.filter_serversideFiltering){
$tb.children().show().removeClass(wo.filter_filteredRow);
} else {
// optimize searching only through already filtered rows - see #313
searchFiltered = true;
r = $t.data('lastSearch') || [];
$.each(v, function(i,val){
// check for changes from beginning of filter; but ignore if there is a logical "or" in the string
searchFiltered = (val || '').indexOf(r[i] || '') === 0 && searchFiltered && !/(\s+or\s+|\|)/g.test(val || '');
});
// can't search when all rows are hidden - this happens when looking for exact matches
if (searchFiltered && $tr.filter(':visible').length === 0) { searchFiltered = false; }
// loop through the rows
for (j = 0; j < l; j++){
r = $tr[j].className;
// skip child rows & already filtered rows
if ( wo.filter_regex.child.test(r) || (searchFiltered && wo.filter_regex.filtered.test(r)) ) { continue; }
r = true;
cr = $tr.eq(j).nextUntil('tr:not(.' + c.cssChildRow + ')');
// so, if "table.config.widgetOptions.filter_childRows" is true and there is
// a match anywhere in the child row, then it will make the row visible
// checked here so the option can be changed dynamically
t = (cr.length && wo.filter_childRows) ? cr.text() : '';
t = wo.filter_ignoreCase ? t.toLocaleLowerCase() : t;
$td = $tr.eq(j).children('td');
for (i = 0; i < cols; i++){
// ignore if filter is empty or disabled
if (v[i]){
// check if column data should be from the cell or from parsed data
if (wo.filter_useParsedData || parsed[i]){
x = c.cache[k].normalized[j][i];
} else {
// using older or original tablesorter
x = $.trim($td.eq(i).text());
}
xi = !wo.filter_regex.type.test(typeof x) && wo.filter_ignoreCase ? x.toLocaleLowerCase() : x;
ff = r; // if r is true, show that row
// replace accents - see #357
v[i] = c.sortLocaleCompare ? ts.replaceAccents(v[i]) : v[i];
// val = case insensitive, v[i] = case sensitive
val = wo.filter_ignoreCase ? v[i].toLocaleLowerCase() : v[i];
if (wo.filter_functions && wo.filter_functions[i]){
if (wo.filter_functions[i] === true){
// default selector; no "filter-select" class
ff = ($ths.filter('[data-column="' + i + '"]:last').hasClass('filter-match')) ? xi.search(val) >= 0 : v[i] === x;
} else if (typeof wo.filter_functions[i] === 'function'){
// filter callback( exact cell content, parser normalized content, filter input value, column index )
ff = wo.filter_functions[i](x, c.cache[k].normalized[j][i], v[i], i, $tr.eq(j));
} else if (typeof wo.filter_functions[i][v[i]] === 'function'){
// selector option function
ff = wo.filter_functions[i][v[i]](x, c.cache[k].normalized[j][i], v[i], i, $tr.eq(j));
}
// Look for regex
} else if (wo.filter_regex.regex.test(val)){
rg = wo.filter_regex.regex.exec(val);
try {
ff = new RegExp(rg[1], rg[2]).test(xi);
} catch (err){
ff = false;
}
// Look for quotes or equals to get an exact match; ignore type since xi could be numeric
/*jshint eqeqeq:false */
} else if (val.replace(wo.filter_regex.exact, '') == xi){
ff = true;
// Look for a not match
} else if (/^\!/.test(val)){
val = val.replace('!','');
s = xi.search($.trim(val));
ff = val === '' ? true : !(wo.filter_startsWith ? s === 0 : s >= 0);
// Look for operators >, >=, < or <=
} else if (/^[<>]=?/.test(val)){
s = fmt(val.replace(wo.filter_regex.nondigit, '').replace(wo.filter_regex.operators,''), table);
// parse filter value in case we're comparing numbers (dates)
if (parsed[i] || c.parsers[i].type === 'numeric') {
rg = c.parsers[i].format('' + val.replace(wo.filter_regex.operators,''), table, $ths.eq(i), i);
s = (rg !== '' && !isNaN(rg)) ? rg : s;
}
// xi may be numeric - see issue #149;
// check if c.cache[k].normalized[j] is defined, because sometimes j goes out of range? (numeric columns)
rg = ( parsed[i] || c.parsers[i].type === 'numeric' ) && !isNaN(s) && c.cache[k].normalized[j] ? c.cache[k].normalized[j][i] :
isNaN(xi) ? fmt(xi.replace(wo.filter_regex.nondigit, ''), table) : fmt(xi, table);
if (/>/.test(val)) { ff = />=/.test(val) ? rg >= s : rg > s; }
if (/</.test(val)) { ff = /<=/.test(val) ? rg <= s : rg < s; }
if (s === '') { ff = true; } // keep showing all rows if nothing follows the operator
// Look for an AND or && operator (logical and)
} else if (/\s+(AND|&&)\s+/g.test(v[i])) {
s = val.split(/(?:\s+(?:and|&&)\s+)/g);
ff = xi.search($.trim(s[0])) >= 0;
r1 = s.length - 1;
while (ff && r1) {
ff = ff && xi.search($.trim(s[r1])) >= 0;
r1--;
}
// Look for a range (using " to " or " - ") - see issue #166; thanks matzhu!
} else if (/\s+(-|to)\s+/.test(val)){
s = val.split(/(?: - | to )/); // make sure the dash is for a range and not indicating a negative number
r1 = fmt(s[0].replace(wo.filter_regex.nondigit, ''), table);
r2 = fmt(s[1].replace(wo.filter_regex.nondigit, ''), table);
// parse filter value in case we're comparing numbers (dates)
if (parsed[i] || c.parsers[i].type === 'numeric') {
rg = c.parsers[i].format('' + s[0], table, $ths.eq(i), i);
r1 = (rg !== '' && !isNaN(rg)) ? rg : r1;
rg = c.parsers[i].format('' + s[1], table, $ths.eq(i), i);
r2 = (rg !== '' && !isNaN(rg)) ? rg : r2;
}
rg = ( parsed[i] || c.parsers[i].type === 'numeric' ) && !isNaN(r1) && !isNaN(r2) ? c.cache[k].normalized[j][i] :
isNaN(xi) ? fmt(xi.replace(wo.filter_regex.nondigit, ''), table) : fmt(xi, table);
if (r1 > r2) { ff = r1; r1 = r2; r2 = ff; } // swap
ff = (rg >= r1 && rg <= r2) || (r1 === '' || r2 === '') ? true : false;
// Look for wild card: ? = single, * = multiple, or | = logical OR
} else if ( /[\?|\*]/.test(val) || /\s+OR\s+/.test(v[i]) ){
s = val.replace(/\s+OR\s+/gi,"|");
// look for an exact match with the "or" unless the "filter-match" class is found
if (!$ths.filter('[data-column="' + i + '"]:last').hasClass('filter-match') && /\|/.test(s)) {
s = '^(' + s + ')$';
}
ff = new RegExp( s.replace(/\?/g, '\\S{1}').replace(/\*/g, '\\S*') ).test(xi);
// Look for match, and add child row data for matching
} else {
x = (xi + t).indexOf(val);
ff = ( (!wo.filter_startsWith && x >= 0) || (wo.filter_startsWith && x === 0) );
}
r = (ff) ? (r ? true : false) : false;
}
}
$tr[j].style.display = (r ? '' : 'none');
$tr.eq(j)[r ? 'removeClass' : 'addClass'](wo.filter_filteredRow);
if (cr.length) { cr[r ? 'show' : 'hide'](); }
}
}
ts.processTbody(table, $tb, false);
}
last = cv; // save last search
$t.data('lastSearch', v);
if (c.debug){
ts.benchmark("Completed filter widget search", time);
}
$t.trigger('applyWidgets'); // make sure zebra widget is applied
$t.trigger('filterEnd');
},
buildSelect = function(i, updating, onlyavail){
var o, t, arry = [], currentVal;
i = parseInt(i, 10);
t = $ths.filter('[data-column="' + i + '"]:last');
// t.data('placeholder') won't work in jQuery older than 1.4.3
o = '<option value="">' + (t.data('placeholder') || t.attr('data-placeholder') || '') + '</option>';
for (k = 0; k < b.length; k++ ){
l = c.cache[k].row.length;
// loop through the rows
for (j = 0; j < l; j++){
// check if has class filtered
if (onlyavail && c.cache[k].row[j][0].className.match(wo.filter_filteredRow)) { continue; }
// get non-normalized cell content
if (wo.filter_useParsedData){
arry.push( '' + c.cache[k].normalized[j][i] );
} else {
t = c.cache[k].row[j][0].cells[i];
if (t){
arry.push( $.trim(c.supportsTextContent ? t.textContent : $(t).text()) );
}
}
}
}
// get unique elements and sort the list
// if $.tablesorter.sortText exists (not in the original tablesorter),
// then natural sort the list otherwise use a basic sort
arry = $.grep(arry, function(v, k){
return $.inArray(v, arry) === k;
});
arry = (ts.sortNatural) ? arry.sort(function(a, b){ return ts.sortNatural(a, b); }) : arry.sort(true);
// Get curent filter value
currentVal = $t.find('thead').find('select.tablesorter-filter[data-column="' + i + '"]').val();
// build option list
for (k = 0; k < arry.length; k++){
t = arry[k].replace(/\"/g, """);
// replace quotes - fixes #242 & ignore empty strings - see http://stackoverflow.com/q/14990971/145346
o += arry[k] !== '' ? '<option value="' + t + '"' + (currentVal === t ? ' selected="selected"' : '') +'>' + arry[k] + '</option>' : '';
}
$t.find('thead').find('select.tablesorter-filter[data-column="' + i + '"]')[ updating ? 'html' : 'append' ](o);
},
buildDefault = function(updating){
// build default select dropdown
for (i = 0; i < cols; i++){
t = $ths.filter('[data-column="' + i + '"]:last');
// look for the filter-select class; build/update it if found
if ((t.hasClass('filter-select') || wo.filter_functions && wo.filter_functions[i] === true) && !t.hasClass('filter-false')){
if (!wo.filter_functions) { wo.filter_functions = {}; }
wo.filter_functions[i] = true; // make sure this select gets processed by filter_functions
buildSelect(i, updating, t.hasClass(wo.filter_onlyAvail));
}
}
},
searching = function(filter){
if (typeof filter === 'undefined' || filter === true){
// delay filtering
clearTimeout(timer);
timer = setTimeout(function(){
checkFilters(filter);
}, wo.filter_liveSearch ? wo.filter_searchDelay : 10);
} else {
// skip delay
checkFilters(filter);
}
};
if (c.debug){
time = new Date();
}
wo.filter_regex.child = new RegExp(c.cssChildRow);
wo.filter_regex.filtered = new RegExp(wo.filter_filteredRow);
// don't build filter row if columnFilters is false or all columns are set to "filter-false" - issue #156
if (wo.filter_columnFilters !== false && $ths.filter('.filter-false').length !== $ths.length){
// build filter row
t = '<tr class="tablesorter-filter-row">';
for (i = 0; i < cols; i++){
t += '<td></td>';
}
c.$filters = $(t += '</tr>').appendTo( $t.find('thead').eq(0) ).find('td');
// build each filter input
for (i = 0; i < cols; i++){
dis = false;
$th = $ths.filter('[data-column="' + i + '"]:last'); // assuming last cell of a column is the main column
sel = (wo.filter_functions && wo.filter_functions[i] && typeof wo.filter_functions[i] !== 'function') || $th.hasClass('filter-select');
// use header option - headers: { 1: { filter: false } } OR add class="filter-false"
if (ts.getData){
// get data from jQuery data, metadata, headers option or header class name
dis = ts.getData($th[0], c.headers[i], 'filter') === 'false';
} else {
// only class names and header options - keep this for compatibility with tablesorter v2.0.5
dis = (c.headers[i] && c.headers[i].hasOwnProperty('filter') && c.headers[i].filter === false) || $th.hasClass('filter-false');
}
if (sel){
t = $('<select>').appendTo( c.$filters.eq(i) );
} else {
if (wo.filter_formatter && $.isFunction(wo.filter_formatter[i])) {
t = wo.filter_formatter[i]( c.$filters.eq(i), i );
// no element returned, so lets go find it
if (t && t.length === 0) { t = c.$filters.eq(i).children('input'); }
// element not in DOM, so lets attach it
if (t && (t.parent().length === 0 || (t.parent().length && t.parent()[0] !== c.$filters[i]))) {
c.$filters.eq(i).append(t);
}
} else {
t = $('<input type="search">').appendTo( c.$filters.eq(i) );
}
if (t) {
t.attr('placeholder', $th.data('placeholder') || $th.attr('data-placeholder') || '');
}
}
if (t) {
t.addClass('tablesorter-filter ' + wo.filter_cssFilter).attr('data-column', i);
if (dis) {
t.addClass('disabled')[0].disabled = true; // disabled!
}
}
}
}
$t
.bind('addRows updateCell update updateRows updateComplete appendCache filterReset filterEnd search '.split(' ').join('.tsfilter '), function(e, filter){
if (!/(search|filterReset|filterEnd)/.test(e.type)){
e.stopPropagation();
buildDefault(true);
}
if (e.type === 'filterReset') {
searching([]);
}
if (e.type === 'filterEnd') {
buildDefault(true);
} else {
// send false argument to force a new search; otherwise if the filter hasn't changed, it will return
filter = e.type === 'search' ? filter : e.type === 'updateComplete' ? $t.data('lastSearch') : '';
searching(filter);
}
return false;
})
.find('input.tablesorter-filter').bind('keyup search', function(e, filter){
// emulate what webkit does.... escape clears the filter
if (e.which === 27) {
this.value = '';
// liveSearch can contain a min value length; ignore arrow and meta keys, but allow backspace
} else if ( (typeof wo.filter_liveSearch === 'number' && this.value.length < wo.filter_liveSearch && this.value !== '') || ( e.type === 'keyup' &&
( (e.which < 32 && e.which !== 8 && wo.filter_liveSearch === true && e.which !== 13) || (e.which >= 37 && e.which <=40) || (e.which !== 13 && wo.filter_liveSearch === false) ) ) ) {
return;
}
searching(filter);
});
// parse columns after formatter, in case the class is added at that point
parsed = $ths.map(function(i){
return (ts.getData) ? ts.getData($ths.filter('[data-column="' + i + '"]:last'), c.headers[i], 'filter') === 'parsed' : $(this).hasClass('filter-parsed');
}).get();
// reset button/link
if (wo.filter_reset){
$(document).delegate(wo.filter_reset, 'click.tsfilter', function(){
$t.trigger('filterReset');
});
}
if (wo.filter_functions){
// i = column # (string)
for (col in wo.filter_functions){
if (wo.filter_functions.hasOwnProperty(col) && typeof col === 'string'){
t = $ths.filter('[data-column="' + col + '"]:last');
ff = '';
if (wo.filter_functions[col] === true && !t.hasClass('filter-false')){
buildSelect(col);
} else if (typeof col === 'string' && !t.hasClass('filter-false')){
// add custom drop down list
for (str in wo.filter_functions[col]){
if (typeof str === 'string'){
ff += ff === '' ? '<option value="">' + (t.data('placeholder') || t.attr('data-placeholder') || '') + '</option>' : '';
ff += '<option value="' + str + '">' + str + '</option>';
}
}
$t.find('thead').find('select.tablesorter-filter[data-column="' + col + '"]').append(ff);
}
}
}
}
// not really updating, but if the column has both the "filter-select" class & filter_functions set to true,
// it would append the same options twice.
buildDefault(true);
$t.find('select.tablesorter-filter').bind('change search', function(e, filter){
checkFilters(filter);
});
if (wo.filter_hideFilters){
$t
.find('.tablesorter-filter-row')
.addClass('hideme')
.bind('mouseenter mouseleave', function(e){
// save event object - http://bugs.jquery.com/ticket/12140
var all, evt = e;
ft = $(this);
clearTimeout(st);
st = setTimeout(function(){
if (/enter|over/.test(evt.type)){
ft.removeClass('hideme');
} else {
// don't hide if input has focus
// $(':focus') needs jQuery 1.6+
if ($(document.activeElement).closest('tr')[0] !== ft[0]){
// get all filter values
all = $t.find('.tablesorter-filter').map(function(){
return $(this).val() || '';
}).get().join('');
// don't hide row if any filter has a value
if (all === ''){
ft.addClass('hideme');
}
}
}
}, 200);
})
.find('input, select').bind('focus blur', function(e){
ft2 = $(this).closest('tr');
clearTimeout(st);
st = setTimeout(function(){
// don't hide row if any filter has a value
if ($t.find('.tablesorter-filter').map(function(){ return $(this).val() || ''; }).get().join('') === ''){
ft2[ e.type === 'focus' ? 'removeClass' : 'addClass']('hideme');
}
}, 200);
});
}
// show processing icon
if (c.showProcessing) {
$t.bind('filterStart.tsfilter filterEnd.tsfilter', function(e, v) {
var fc = (v) ? $t.find('.' + ts.css.header).filter('[data-column]').filter(function(){
return v[$(this).data('column')] !== '';
}) : '';
ts.isProcessing($t[0], e.type === 'filterStart', v ? fc : '');
});
}
if (c.debug){
ts.benchmark("Applying Filter widget", time);
}
// add default values
$t.bind('tablesorter-initialized', function(){
ff = ts.getFilters(table);
// ff is undefined when filter_columnFilters = false
if (ff) {
for (i = 0; i < ff.length; i++) {
ff[i] = $ths.filter('[data-column="' + i + '"]:last').attr(wo.filter_defaultAttrib) || ff[i];
}
ts.setFilters(table, ff, true);
}
});
// filter widget initialized
$t.trigger('filterInit');
checkFilters();
}
},
remove: function(table, c, wo){
var k, $tb,
$t = c.$table,
b = c.$tbodies;
$t
.removeClass('hasFilters')
// add .tsfilter namespace to all BUT search
.unbind('addRows updateCell update updateComplete appendCache search filterStart filterEnd '.split(' ').join('.tsfilter '))
.find('.tablesorter-filter-row').remove();
for (k = 0; k < b.length; k++ ){
$tb = ts.processTbody(table, b.eq(k), true); // remove tbody
$tb.children().removeClass(wo.filter_filteredRow).show();
ts.processTbody(table, $tb, false); // restore tbody
}
if (wo.filterreset) { $(document).undelegate(wo.filter_reset, 'click.tsfilter'); }
}
});
ts.getFilters = function(table) {
var c = table ? $(table)[0].config : {};
if (c && c.widgetOptions && !c.widgetOptions.filter_columnFilters) { return $(table).data('lastSearch'); }
return c && c.$filters ? c.$filters.find('.tablesorter-filter').map(function(i, el) {
return $(el).val();
}).get() || [] : false;
};
ts.setFilters = function(table, filter, apply) {
var $t = $(table),
c = $t.length ? $t[0].config : {},
valid = c && c.$filters ? c.$filters.find('.tablesorter-filter').each(function(i, el) {
$(el).val(filter[i] || '');
}).trigger('change.tsfilter') || false : false;
if (apply) { $t.trigger('search', [filter, false]); }
return !!valid;
};
// Widget: Sticky headers
// based on this awesome article:
// http://css-tricks.com/13465-persistent-headers/
// and https://github.com/jmosbech/StickyTableHeaders by Jonas Mosbech
// **************************
ts.addWidget({
id: "stickyHeaders",
priority: 60,
options: {
stickyHeaders : '', // extra class name added to the sticky header row
stickyHeaders_offset : 0, // number or jquery selector targeting the position:fixed element
stickyHeaders_cloneId : '-sticky', // added to table ID, if it exists
stickyHeaders_addResizeEvent : true, // trigger "resize" event on headers
stickyHeaders_includeCaption : true, // if false and a caption exist, it won't be included in the sticky header
stickyHeaders_zIndex : 2 // The zIndex of the stickyHeaders, allows the user to adjust this to their needs
},
format: function(table, c, wo){
if (c.$table.hasClass('hasStickyHeaders')) { return; }
var $t = c.$table,
$win = $(window),
header = $t.children('thead:first'),
hdrCells = header.children('tr:not(.sticky-false)').children(),
innr = '.tablesorter-header-inner',
tfoot = $t.find('tfoot'),
filterInputs = '.tablesorter-filter',
$stickyOffset = isNaN(wo.stickyHeaders_offset) ? $(wo.stickyHeaders_offset) : '',
stickyOffset = $stickyOffset.length ? $stickyOffset.height() || 0 : parseInt(wo.stickyHeaders_offset, 10) || 0,
stickyzIndex = wo.stickyHeaders_zIndex ? wo.stickyHeaders_zIndex : 2,
$stickyTable = wo.$sticky = $t.clone()
.addClass('containsStickyHeaders')
.css({
position : 'fixed',
margin : 0,
top : stickyOffset,
visibility : 'hidden',
zIndex : stickyzIndex
}),
stkyHdr = $stickyTable.children('thead:first').addClass('tablesorter-stickyHeader ' + wo.stickyHeaders),
stkyCells,
laststate = '',
spacing = 0,
flag = false,
resizeHdr = function(){
stickyOffset = $stickyOffset.length ? $stickyOffset.height() || 0 : parseInt(wo.stickyHeaders_offset, 10) || 0;
var bwsr = navigator.userAgent;
spacing = 0;
// yes, I dislike browser sniffing, but it really is needed here :(
// webkit automatically compensates for border spacing
if ($t.css('border-collapse') !== 'collapse' && !/(webkit|msie)/i.test(bwsr)) {
// Firefox & Opera use the border-spacing
// update border-spacing here because of demos that switch themes
spacing = parseInt(hdrCells.eq(0).css('border-left-width'), 10) * 2;
}
$stickyTable.css({
left : header.offset().left - $win.scrollLeft() - spacing,
width: $t.width()
});
stkyCells.filter(':visible').each(function(i){
var $h = hdrCells.filter(':visible').eq(i);
$(this)
.css({
width: $h.width() - spacing,
height: $h.height()
})
.find(innr).width( $h.find(innr).width() );
});
};
// fix clone ID, if it exists - fixes #271
if ($stickyTable.attr('id')) { $stickyTable[0].id += wo.stickyHeaders_cloneId; }
// clear out cloned table, except for sticky header
// include caption & filter row (fixes #126 & #249)
$stickyTable.find('thead:gt(0), tr.sticky-false, tbody, tfoot').remove();
if (!wo.stickyHeaders_includeCaption) {
$stickyTable.find('caption').remove();
}
// issue #172 - find td/th in sticky header
stkyCells = stkyHdr.children().children();
$stickyTable.css({ height:0, width:0, padding:0, margin:0, border:0 });
// remove resizable block
stkyCells.find('.tablesorter-resizer').remove();
// update sticky header class names to match real header after sorting
$t
.addClass('hasStickyHeaders')
.bind('sortEnd.tsSticky', function(){
hdrCells.filter(':visible').each(function(i){
var t = stkyCells.filter(':visible').eq(i);
t
.attr('class', $(this).attr('class'))
// remove processing icon
.removeClass(ts.css.processing + ' ' + c.cssProcessing);
if (c.cssIcon){
t
.find('.' + ts.css.icon)
.attr('class', $(this).find('.' + ts.css.icon).attr('class'));
}
});
})
.bind('pagerComplete.tsSticky', function(){
resizeHdr();
});
// http://stackoverflow.com/questions/5312849/jquery-find-self;
hdrCells.find(c.selectorSort).add( c.$headers.filter(c.selectorSort) ).each(function(i){
var t = $(this),
// clicking on sticky will trigger sort
$cell = stkyHdr.children('tr.tablesorter-headerRow').children().eq(i).bind('mouseup', function(e){
t.trigger(e, true); // external mouseup flag (click timer is ignored)
});
// prevent sticky header text selection
if (c.cancelSelection) {
$cell
.attr('unselectable', 'on')
.bind('selectstart', false)
.css({
'user-select': 'none',
'MozUserSelect': 'none'
});
}
});
// add stickyheaders AFTER the table. If the table is selected by ID, the original one (first) will be returned.
$t.after( $stickyTable );
// make it sticky!
$win.bind('scroll.tsSticky resize.tsSticky', function(e){
if (!$t.is(':visible')) { return; } // fixes #278
var pre = 'tablesorter-sticky-',
offset = $t.offset(),
cap = (wo.stickyHeaders_includeCaption ? 0 : $t.find('caption').outerHeight(true)),
sTop = $win.scrollTop() + stickyOffset - cap,
tableHt = $t.height() - ($stickyTable.height() + (tfoot.height() || 0)),
vis = (sTop > offset.top) && (sTop < offset.top + tableHt) ? 'visible' : 'hidden';
$stickyTable
.removeClass(pre + 'visible ' + pre + 'hidden')
.addClass(pre + vis)
.css({
// adjust when scrolling horizontally - fixes issue #143
left : header.offset().left - $win.scrollLeft() - spacing,
visibility : vis
});
if (vis !== laststate || e.type === 'resize'){
// make sure the column widths match
resizeHdr();
laststate = vis;
}
});
if (wo.stickyHeaders_addResizeEvent) {
ts.addHeaderResizeEvent(table);
}
// look for filter widget
$t.bind('filterEnd', function(){
if (flag) { return; }
stkyHdr.find('.tablesorter-filter-row').children().each(function(i){
$(this).find(filterInputs).val( c.$filters.find(filterInputs).eq(i).val() );
});
});
stkyCells.find(filterInputs).bind('keyup search change', function(e){
// ignore arrow and meta keys; allow backspace
if ((e.which < 32 && e.which !== 8) || (e.which >= 37 && e.which <=40)) { return; }
flag = true;
var $f = $(this), col = $f.attr('data-column');
c.$filters.find(filterInputs).eq(col)
.val( $f.val() )
.trigger('search');
setTimeout(function(){
flag = false;
}, wo.filter_searchDelay);
});
$t.trigger('stickyHeadersInit');
},
remove: function(table, c, wo){
c.$table
.removeClass('hasStickyHeaders')
.unbind('sortEnd.tsSticky pagerComplete.tsSticky')
.find('.tablesorter-stickyHeader').remove();
if (wo.$sticky && wo.$sticky.length) { wo.$sticky.remove(); } // remove cloned table
// don't unbind if any table on the page still has stickyheaders applied
if (!$('.hasStickyHeaders').length) {
$(window).unbind('scroll.tsSticky resize.tsSticky');
}
ts.addHeaderResizeEvent(table, false);
}
});
// Add Column resizing widget
// this widget saves the column widths if
// $.tablesorter.storage function is included
// **************************
ts.addWidget({
id: "resizable",
priority: 40,
options: {
resizable : true,
resizable_addLastColumn : false
},
format: function(table, c, wo){
if (c.$table.hasClass('hasResizable')) { return; }
c.$table.addClass('hasResizable');
var $t, t, i, j, s = {}, $c, $cols, w, tw,
$tbl = c.$table,
position = 0,
$target = null,
$next = null,
fullWidth = Math.abs($tbl.parent().width() - $tbl.width()) < 20,
stopResize = function(){
if (ts.storage && $target){
s[$target.index()] = $target.width();
s[$next.index()] = $next.width();
$target.width( s[$target.index()] );
$next.width( s[$next.index()] );
if (wo.resizable !== false){
ts.storage(table, 'tablesorter-resizable', s);
}
}
position = 0;
$target = $next = null;
$(window).trigger('resize'); // will update stickyHeaders, just in case
};
s = (ts.storage && wo.resizable !== false) ? ts.storage(table, 'tablesorter-resizable') : {};
// process only if table ID or url match
if (s){
for (j in s){
if (!isNaN(j) && j < c.$headers.length){
c.$headers.eq(j).width(s[j]); // set saved resizable widths
}
}
}
$t = $tbl.children('thead:first').children('tr');
// add resizable-false class name to headers (across rows as needed)
$t.children().each(function(){
t = $(this);
i = t.attr('data-column');
j = ts.getData( t, c.headers[i], 'resizable') === "false";
$t.children().filter('[data-column="' + i + '"]').toggleClass('resizable-false', j);
});
// add wrapper inside each cell to allow for positioning of the resizable target block
$t.each(function(){
$c = $(this).children(':not(.resizable-false)');
if (!$(this).find('.tablesorter-wrapper').length) {
// Firefox needs this inner div to position the resizer correctly
$c.wrapInner('<div class="tablesorter-wrapper" style="position:relative;height:100%;width:100%"></div>');
}
// don't include the last column of the row
if (!wo.resizable_addLastColumn) { $c = $c.slice(0,-1); }
$cols = $cols ? $cols.add($c) : $c;
});
$cols
.each(function(){
$t = $(this);
j = parseInt($t.css('padding-right'), 10) + 10; // 8 is 1/2 of the 16px wide resizer grip
t = '<div class="tablesorter-resizer" style="cursor:w-resize;position:absolute;z-index:1;right:-' + j +
'px;top:0;height:100%;width:20px;"></div>';
$t
.find('.tablesorter-wrapper')
.append(t);
})
.bind('mousemove.tsresize', function(e){
// ignore mousemove if no mousedown
if (position === 0 || !$target) { return; }
// resize columns
w = e.pageX - position;
tw = $target.width();
$target.width( tw + w );
if ($target.width() !== tw && fullWidth){
$next.width( $next.width() - w );
}
position = e.pageX;
})
.bind('mouseup.tsresize', function(){
stopResize();
})
.find('.tablesorter-resizer,.tablesorter-resizer-grip')
.bind('mousedown', function(e){
// save header cell and mouse position; closest() not supported by jQuery v1.2.6
$target = $(e.target).closest('th');
t = c.$headers.filter('[data-column="' + $target.attr('data-column') + '"]');
if (t.length > 1) { $target = $target.add(t); }
// if table is not as wide as it's parent, then resize the table
$next = e.shiftKey ? $target.parent().find('th:not(.resizable-false)').filter(':last') : $target.nextAll(':not(.resizable-false)').eq(0);
position = e.pageX;
});
$tbl.find('thead:first')
.bind('mouseup.tsresize mouseleave.tsresize', function(){
stopResize();
})
// right click to reset columns to default widths
.bind('contextmenu.tsresize', function(){
ts.resizableReset(table);
// $.isEmptyObject() needs jQuery 1.4+
var rtn = $.isEmptyObject ? $.isEmptyObject(s) : s === {}; // allow right click if already reset
s = {};
return rtn;
});
},
remove: function(table, c, wo){
c.$table
.removeClass('hasResizable')
.find('thead')
.unbind('mouseup.tsresize mouseleave.tsresize contextmenu.tsresize')
.find('tr').children()
.unbind('mousemove.tsresize mouseup.tsresize')
// don't remove "tablesorter-wrapper" as uitheme uses it too
.find('.tablesorter-resizer,.tablesorter-resizer-grip').remove();
ts.resizableReset(table);
}
});
ts.resizableReset = function(table){
table.config.$headers.filter(':not(.resizable-false)').css('width','');
if (ts.storage) { ts.storage(table, 'tablesorter-resizable', {}); }
};
// Save table sort widget
// this widget saves the last sort only if the
// saveSort widget option is true AND the
// $.tablesorter.storage function is included
// **************************
ts.addWidget({
id: 'saveSort',
priority: 20,
options: {
saveSort : true
},
init: function(table, thisWidget, c, wo){
// run widget format before all other widgets are applied to the table
thisWidget.format(table, c, wo, true);
},
format: function(table, c, wo, init){
var sl, time,
$t = c.$table,
ss = wo.saveSort !== false, // make saveSort active/inactive; default to true
sortList = { "sortList" : c.sortList };
if (c.debug){
time = new Date();
}
if ($t.hasClass('hasSaveSort')){
if (ss && table.hasInitialized && ts.storage){
ts.storage( table, 'tablesorter-savesort', sortList );
if (c.debug){
ts.benchmark('saveSort widget: Saving last sort: ' + c.sortList, time);
}
}
} else {
// set table sort on initial run of the widget
$t.addClass('hasSaveSort');
sortList = '';
// get data
if (ts.storage){
sl = ts.storage( table, 'tablesorter-savesort' );
sortList = (sl && sl.hasOwnProperty('sortList') && $.isArray(sl.sortList)) ? sl.sortList : '';
if (c.debug){
ts.benchmark('saveSort: Last sort loaded: "' + sortList + '"', time);
}
$t.bind('saveSortReset', function(e){
e.stopPropagation();
ts.storage( table, 'tablesorter-savesort', '' );
});
}
// init is true when widget init is run, this will run this widget before all other widgets have initialized
// this method allows using this widget in the original tablesorter plugin; but then it will run all widgets twice.
if (init && sortList && sortList.length > 0){
c.sortList = sortList;
} else if (table.hasInitialized && sortList && sortList.length > 0){
// update sort change
$t.trigger('sorton', [sortList]);
}
}
},
remove: function(table){
// clear storage
if (ts.storage) { ts.storage( table, 'tablesorter-savesort', '' ); }
}
});
})(jQuery);
| hebronlin/churchlife | static/js/libs/tablesorter/jquery.tablesorter.widgets.js | JavaScript | gpl-3.0 | 48,668 |
// Localization support
const messages = {
'en': {
'copy': 'Copy',
'copy_to_clipboard': 'Copy to clipboard',
'copy_success': 'Copied!',
'copy_failure': 'Failed to copy',
},
'es' : {
'copy': 'Copiar',
'copy_to_clipboard': 'Copiar al portapapeles',
'copy_success': '¡Copiado!',
'copy_failure': 'Error al copiar',
},
'de' : {
'copy': 'Kopieren',
'copy_to_clipboard': 'In die Zwischenablage kopieren',
'copy_success': 'Kopiert!',
'copy_failure': 'Fehler beim Kopieren',
},
'fr' : {
'copy': 'Copier',
'copy_to_clipboard': 'Copié dans le presse-papier',
'copy_success': 'Copié !',
'copy_failure': 'Échec de la copie',
},
'ru': {
'copy': 'Скопировать',
'copy_to_clipboard': 'Скопировать в буфер',
'copy_success': 'Скопировано!',
'copy_failure': 'Не удалось скопировать',
},
'zh-CN': {
'copy': '复制',
'copy_to_clipboard': '复制到剪贴板',
'copy_success': '复制成功!',
'copy_failure': '复制失败',
}
}
let locale = 'en'
if( document.documentElement.lang !== undefined
&& messages[document.documentElement.lang] !== undefined ) {
locale = document.documentElement.lang
}
let doc_url_root = DOCUMENTATION_OPTIONS.URL_ROOT;
if (doc_url_root == '#') {
doc_url_root = '';
}
const path_static = `${doc_url_root}_static/`;
/**
* Set up copy/paste for code blocks
*/
const runWhenDOMLoaded = cb => {
if (document.readyState != 'loading') {
cb()
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', cb)
} else {
document.attachEvent('onreadystatechange', function() {
if (document.readyState == 'complete') cb()
})
}
}
const codeCellId = index => `codecell${index}`
// Clears selected text since ClipboardJS will select the text when copying
const clearSelection = () => {
if (window.getSelection) {
window.getSelection().removeAllRanges()
} else if (document.selection) {
document.selection.empty()
}
}
// Changes tooltip text for two seconds, then changes it back
const temporarilyChangeTooltip = (el, oldText, newText) => {
el.setAttribute('data-tooltip', newText)
el.classList.add('success')
setTimeout(() => el.setAttribute('data-tooltip', oldText), 2000)
setTimeout(() => el.classList.remove('success'), 2000)
}
// Changes the copy button icon for two seconds, then changes it back
const temporarilyChangeIcon = (el) => {
img = el.querySelector("img");
img.setAttribute('src', `${path_static}check-solid.svg`)
setTimeout(() => img.setAttribute('src', `${path_static}copy-button.svg`), 2000)
}
const addCopyButtonToCodeCells = () => {
// If ClipboardJS hasn't loaded, wait a bit and try again. This
// happens because we load ClipboardJS asynchronously.
if (window.ClipboardJS === undefined) {
setTimeout(addCopyButtonToCodeCells, 250)
return
}
// Add copybuttons to all of our code cells
const codeCells = document.querySelectorAll('div.highlight pre')
codeCells.forEach((codeCell, index) => {
const id = codeCellId(index)
codeCell.setAttribute('id', id)
const clipboardButton = id =>
`<button class="copybtn o-tooltip--left" data-tooltip="${messages[locale]['copy']}" data-clipboard-target="#${id}">
<img src="${path_static}copy-button.svg" alt="${messages[locale]['copy_to_clipboard']}">
</button>`
codeCell.insertAdjacentHTML('afterend', clipboardButton(id))
})
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
// Callback when a copy button is clicked. Will be passed the node that was clicked
// should then grab the text and replace pieces of text that shouldn't be used in output
function formatCopyText(textContent, copybuttonPromptText, isRegexp = false, onlyCopyPromptLines = true, removePrompts = true, copyEmptyLines = true, lineContinuationChar = "", hereDocDelim = "") {
var regexp;
var match;
// Do we check for line continuation characters and "HERE-documents"?
var useLineCont = !!lineContinuationChar
var useHereDoc = !!hereDocDelim
// create regexp to capture prompt and remaining line
if (isRegexp) {
regexp = new RegExp('^(' + copybuttonPromptText + ')(.*)')
} else {
regexp = new RegExp('^(' + escapeRegExp(copybuttonPromptText) + ')(.*)')
}
const outputLines = [];
var promptFound = false;
var gotLineCont = false;
var gotHereDoc = false;
const lineGotPrompt = [];
for (const line of textContent.split('\n')) {
match = line.match(regexp)
if (match || gotLineCont || gotHereDoc) {
promptFound = regexp.test(line)
lineGotPrompt.push(promptFound)
if (removePrompts && promptFound) {
outputLines.push(match[2])
} else {
outputLines.push(line)
}
gotLineCont = line.endsWith(lineContinuationChar) & useLineCont
if (line.includes(hereDocDelim) & useHereDoc)
gotHereDoc = !gotHereDoc
} else if (!onlyCopyPromptLines) {
outputLines.push(line)
} else if (copyEmptyLines && line.trim() === '') {
outputLines.push(line)
}
}
// If no lines with the prompt were found then just use original lines
if (lineGotPrompt.some(v => v === true)) {
textContent = outputLines.join('\n');
}
// Remove a trailing newline to avoid auto-running when pasting
if (textContent.endsWith("\n")) {
textContent = textContent.slice(0, -1)
}
return textContent
}
var copyTargetText = (trigger) => {
var target = document.querySelector(trigger.attributes['data-clipboard-target'].value);
return formatCopyText(target.innerText, '', false, true, true, true, '', '')
}
// Initialize with a callback so we can modify the text before copy
const clipboard = new ClipboardJS('.copybtn', {text: copyTargetText})
// Update UI with error/success messages
clipboard.on('success', event => {
clearSelection()
temporarilyChangeTooltip(event.trigger, messages[locale]['copy'], messages[locale]['copy_success'])
temporarilyChangeIcon(event.trigger)
})
clipboard.on('error', event => {
temporarilyChangeTooltip(event.trigger, messages[locale]['copy'], messages[locale]['copy_failure'])
})
}
runWhenDOMLoaded(addCopyButtonToCodeCells) | r-pufky/docs | docs/_static/copybutton.js | JavaScript | gpl-2.0 | 6,506 |
CKEDITOR.plugins.setLang("print","ca",{toolbar:"Imprimeix"}); | bmmg888/moodlemobile2 | www/lib/ckeditor/plugins/print/lang/ca.js | JavaScript | apache-2.0 | 64 |
(function(){tinymce.create("tinymce.plugins.Nonbreaking",{init:function(a,b){var c=this;c.editor=a;a.addCommand("mceNonBreaking",function(){a.execCommand("mceInsertContent",false,(a.plugins.visualchars&&a.plugins.visualchars.state)?'<span class="mceItemHidden mceVisualNbsp">·</span>':" ")});a.addButton("nonbreaking",{title:"nonbreaking.nonbreaking_desc",cmd:"mceNonBreaking"});if(a.getParam("nonbreaking_force_tab")){a.onKeyDown.add(function(d,f){if(tinymce.isIE&&f.keyCode==9){d.execCommand("mceNonBreaking");d.execCommand("mceNonBreaking");d.execCommand("mceNonBreaking");tinymce.dom.Event.cancel(f)}})}},getInfo:function(){return{longname:"Nonbreaking space",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/nonbreaking",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("nonbreaking",tinymce.plugins.Nonbreaking)})(); | jewsroch/sf-photos | zp-core/plugins/tiny_mce/plugins/nonbreaking/editor_plugin.js | JavaScript | gpl-2.0 | 952 |
webshims.register('details', function($, webshims, window, doc, undefined, options){
var isInterActiveSummary = function(summary){
var details = $(summary).parent('details');
if(details[0] && details.children(':first').get(0) === summary){
return details;
}
};
var bindDetailsSummary = function(summary, details){
summary = $(summary);
details = $(details);
var oldSummary = $.data(details[0], 'summaryElement');
$.data(summary[0], 'detailsElement', details);
if(!oldSummary || summary[0] !== oldSummary[0]){
if(oldSummary){
if(oldSummary.hasClass('fallback-summary')){
oldSummary.remove();
} else {
oldSummary
.off('.summaryPolyfill')
.removeData('detailsElement')
.removeAttr('role')
.removeAttr('tabindex')
.removeAttr('aria-expanded')
.removeClass('summary-button')
.find('span.details-open-indicator')
.remove()
;
}
}
$.data(details[0], 'summaryElement', summary);
details.prop('open', details.prop('open'));
}
};
var getSummary = function(details){
var summary = $.data(details, 'summaryElement');
if(!summary){
summary = $(details).children('summary:first-child');
if(!summary[0]){
$(details).prependPolyfill('<summary class="fallback-summary">'+ options.text +'</summary>');
summary = $.data(details, 'summaryElement');
} else {
bindDetailsSummary(summary, details);
}
}
return summary;
};
// var isOriginalPrevented = function(e){
// var src = e.originalEvent;
// if(!src){return e.isDefaultPrevented();}
//
// return src.defaultPrevented || src.returnValue === false ||
// src.getPreventDefault && src.getPreventDefault();
// };
webshims.createElement('summary', function(){
var details = isInterActiveSummary(this);
if(!details || $.data(this, 'detailsElement')){return;}
var timer;
var stopNativeClickTest;
var tabindex = $.attr(this, 'tabIndex') || '0';
bindDetailsSummary(this, details);
$(this)
.on({
'focus.summaryPolyfill': function(){
$(this).addClass('summary-has-focus');
},
'blur.summaryPolyfill': function(){
$(this).removeClass('summary-has-focus');
},
'mouseenter.summaryPolyfill': function(){
$(this).addClass('summary-has-hover');
},
'mouseleave.summaryPolyfill': function(){
$(this).removeClass('summary-has-hover');
},
'click.summaryPolyfill': function(e){
var details = isInterActiveSummary(this);
if(details){
if(!stopNativeClickTest && e.originalEvent){
stopNativeClickTest = true;
e.stopImmediatePropagation();
e.preventDefault();
$(this).trigger('click');
stopNativeClickTest = false;
return false;
} else {
clearTimeout(timer);
timer = setTimeout(function(){
if(!e.isDefaultPrevented()){
details.prop('open', !details.prop('open'));
}
}, 0);
}
}
},
'keydown.summaryPolyfill': function(e){
if( (e.keyCode == 13 || e.keyCode == 32) && !e.isDefaultPrevented()){
stopNativeClickTest = true;
e.preventDefault();
$(this).trigger('click');
stopNativeClickTest = false;
}
}
})
.attr({tabindex: tabindex, role: 'button'})
.prepend('<span class="details-open-indicator" />')
;
webshims.moveToFirstEvent(this, 'click');
});
var initDetails;
webshims.defineNodeNamesBooleanProperty('details', 'open', function(val){
var summary = $($.data(this, 'summaryElement'));
if(!summary){return;}
var action = (val) ? 'removeClass' : 'addClass';
var details = $(this);
if (!initDetails && options.animate){
details.stop().css({width: '', height: ''});
var start = {
width: details.width(),
height: details.height()
};
}
summary.attr('aria-expanded', ''+val);
details[action]('closed-details-summary').children().not(summary[0])[action]('closed-details-child');
if(!initDetails && options.animate){
var end = {
width: details.width(),
height: details.height()
};
details.css(start).animate(end, {
complete: function(){
$(this).css({width: '', height: ''});
}
});
}
});
webshims.createElement('details', function(){
initDetails = true;
var summary = getSummary(this);
$.prop(this, 'open', $.prop(this, 'open'));
initDetails = false;
});
});
;webshims.register('track', function($, webshims, window, document, undefined){
"use strict";
var mediaelement = webshims.mediaelement;
var id = new Date().getTime();
//descriptions are not really shown, but they are inserted into the dom
var showTracks = {subtitles: 1, captions: 1, descriptions: 1};
var dummyTrack = $('<track />');
var support = webshims.support;
var supportTrackMod = support.ES5 && support.objectAccessor;
var createEventTarget = function(obj){
var eventList = {};
obj.addEventListener = function(name, fn){
if(eventList[name]){
webshims.error('always use $.on to the shimed event: '+ name +' already bound fn was: '+ eventList[name] +' your fn was: '+ fn);
}
eventList[name] = fn;
};
obj.removeEventListener = function(name, fn){
if(eventList[name] && eventList[name] != fn){
webshims.error('always use $.on/$.off to the shimed event: '+ name +' already bound fn was: '+ eventList[name] +' your fn was: '+ fn);
}
if(eventList[name]){
delete eventList[name];
}
};
return obj;
};
var cueListProto = {
getCueById: function(id){
var cue = null;
for(var i = 0, len = this.length; i < len; i++){
if(this[i].id === id){
cue = this[i];
break;
}
}
return cue;
}
};
var numericModes = {
0: 'disabled',
1: 'hidden',
2: 'showing'
};
var textTrackProto = {
shimActiveCues: null,
_shimActiveCues: null,
activeCues: null,
cues: null,
kind: 'subtitles',
label: '',
language: '',
id: '',
mode: 'disabled',
oncuechange: null,
toString: function() {
return "[object TextTrack]";
},
addCue: function(cue){
if(!this.cues){
this.cues = mediaelement.createCueList();
} else {
var lastCue = this.cues[this.cues.length-1];
if(lastCue && lastCue.startTime > cue.startTime){
webshims.error("cue startTime higher than previous cue's startTime");
}
}
if(cue.track && cue.track.removeCue){
cue.track.removeCue(cue);
}
cue.track = this;
this.cues.push(cue);
},
//ToDo: make it more dynamic
removeCue: function(cue){
var cues = this.cues || [];
var i = 0;
var len = cues.length;
if(cue.track != this){
webshims.error("cue not part of track");
return;
}
for(; i < len; i++){
if(cues[i] === cue){
cues.splice(i, 1);
cue.track = null;
break;
}
}
if(cue.track){
webshims.error("cue not part of track");
return;
}
}/*,
DISABLED: 'disabled',
OFF: 'disabled',
HIDDEN: 'hidden',
SHOWING: 'showing',
ERROR: 3,
LOADED: 2,
LOADING: 1,
NONE: 0*/
};
var copyProps = ['kind', 'label', 'srclang'];
var copyName = {srclang: 'language'};
var updateMediaTrackList = function(baseData, trackList){
var removed = [];
var added = [];
var newTracks = [];
var i, len;
if(!baseData){
baseData = webshims.data(this, 'mediaelementBase') || webshims.data(this, 'mediaelementBase', {});
}
if(!trackList){
baseData.blockTrackListUpdate = true;
trackList = $.prop(this, 'textTracks');
baseData.blockTrackListUpdate = false;
}
clearTimeout(baseData.updateTrackListTimer);
$('track', this).each(function(){
var track = $.prop(this, 'track');
newTracks.push(track);
if(trackList.indexOf(track) == -1){
added.push(track);
}
});
if(baseData.scriptedTextTracks){
for(i = 0, len = baseData.scriptedTextTracks.length; i < len; i++){
newTracks.push(baseData.scriptedTextTracks[i]);
if(trackList.indexOf(baseData.scriptedTextTracks[i]) == -1){
added.push(baseData.scriptedTextTracks[i]);
}
}
}
for(i = 0, len = trackList.length; i < len; i++){
if(newTracks.indexOf(trackList[i]) == -1){
removed.push(trackList[i]);
}
}
if(removed.length || added.length){
trackList.splice(0);
for(i = 0, len = newTracks.length; i < len; i++){
trackList.push(newTracks[i]);
}
for(i = 0, len = removed.length; i < len; i++){
$([trackList]).triggerHandler($.Event({type: 'removetrack', track: removed[i]}));
}
for(i = 0, len = added.length; i < len; i++){
$([trackList]).triggerHandler($.Event({type: 'addtrack', track: added[i]}));
}
if(baseData.scriptedTextTracks || removed.length){
$(this).triggerHandler('updatetrackdisplay');
}
}
};
var refreshTrack = function(track, trackData){
if(!trackData){
trackData = webshims.data(track, 'trackData');
}
if(trackData && !trackData.isTriggering){
trackData.isTriggering = true;
setTimeout(function(){
$(track).closest('audio, video').triggerHandler('updatetrackdisplay');
trackData.isTriggering = false;
}, 1);
}
};
var isDefaultTrack = (function(){
var defaultKinds = {
subtitles: {
subtitles: 1,
captions: 1
},
descriptions: {descriptions: 1},
chapters: {chapters: 1}
};
defaultKinds.captions = defaultKinds.subtitles;
return function(track){
var kind, firstDefaultTrack;
var isDefault = $.prop(track, 'default');
if(isDefault && (kind = $.prop(track, 'kind')) != 'metadata'){
firstDefaultTrack = $(track)
.parent()
.find('track[default]')
.filter(function(){
return !!(defaultKinds[kind][$.prop(this, 'kind')]);
})[0]
;
if(firstDefaultTrack != track){
isDefault = false;
webshims.error('more than one default track of a specific kind detected. Fall back to default = false');
}
}
return isDefault;
};
})();
var emptyDiv = $('<div />')[0];
function VTTCue(startTime, endTime, text){
if(arguments.length != 3){
webshims.error("wrong arguments.length for VTTCue.constructor");
}
this.startTime = startTime;
this.endTime = endTime;
this.text = text;
this.onenter = null;
this.onexit = null;
this.pauseOnExit = false;
this.track = null;
this.id = null;
this.getCueAsHTML = (function(){
var lastText = "";
var parsedText = "";
var fragment;
return function(){
var i, len;
if(!fragment){
fragment = document.createDocumentFragment();
}
if(lastText != this.text){
lastText = this.text;
parsedText = mediaelement.parseCueTextToHTML(lastText);
emptyDiv.innerHTML = parsedText;
for(i = 0, len = emptyDiv.childNodes.length; i < len; i++){
fragment.appendChild(emptyDiv.childNodes[i].cloneNode(true));
}
}
return fragment.cloneNode(true);
};
})();
}
window.VTTCue = VTTCue;
window.TextTrackCue = function(){
webshims.error("Use VTTCue constructor instead of abstract TextTrackCue constructor.");
VTTCue.apply(this, arguments);
};
window.TextTrackCue.prototype = VTTCue.prototype;
mediaelement.createCueList = function(){
return $.extend([], cueListProto);
};
mediaelement.parseCueTextToHTML = (function(){
var tagSplits = /(<\/?[^>]+>)/ig;
var allowedTags = /^(?:c|v|ruby|rt|b|i|u)/;
var regEnd = /\<\s*\//;
var addToTemplate = function(localName, attribute, tag, html){
var ret;
if(regEnd.test(html)){
ret = '</'+ localName +'>';
} else {
tag.splice(0, 1);
ret = '<'+ localName +' '+ attribute +'="'+ (tag.join(' ').replace(/\"/g, '"')) +'">';
}
return ret;
};
var replacer = function(html){
var tag = html.replace(/[<\/>]+/ig,"").split(/[\s\.]+/);
if(tag[0]){
tag[0] = tag[0].toLowerCase();
if(allowedTags.test(tag[0])){
if(tag[0] == 'c'){
html = addToTemplate('span', 'class', tag, html);
} else if(tag[0] == 'v'){
html = addToTemplate('q', 'title', tag, html);
}
} else {
html = "";
}
}
return html;
};
return function(cueText){
return cueText.replace(tagSplits, replacer);
};
})();
var mapTtmlToVtt = function(i){
var content = i+'';
var begin = this.getAttribute('begin') || '';
var end = this.getAttribute('end') || '';
var text = $.trim($.text(this));
if(!/\./.test(begin)){
begin += '.000';
}
if(!/\./.test(end)){
end += '.000';
}
content += '\n';
content += begin +' --> '+end+'\n';
content += text;
return content;
};
var ttmlTextToVTT = function(ttml){
ttml = $.parseXML(ttml) || [];
return $(ttml).find('[begin][end]').map(mapTtmlToVtt).get().join('\n\n') || '';
};
var loadingTracks = 0;
mediaelement.loadTextTrack = function(mediaelem, track, trackData, _default){
var loadEvents = 'play playing loadedmetadata loadstart';
var obj = trackData.track;
var load = function(){
var error, ajax, createAjax;
var isDisabled = obj.mode == 'disabled';
var videoState = !!($.prop(mediaelem, 'readyState') > 0 || $.prop(mediaelem, 'networkState') == 2 || !$.prop(mediaelem, 'paused'));
var src = (!isDisabled || videoState) && ($.attr(track, 'src') && $.prop(track, 'src'));
if(src){
$(mediaelem).off(loadEvents, load).off('updatetrackdisplay', load);
if(!trackData.readyState){
error = function(){
loadingTracks--;
trackData.readyState = 3;
obj.cues = null;
obj.activeCues = obj.shimActiveCues = obj._shimActiveCues = null;
$(track).triggerHandler('error');
};
trackData.readyState = 1;
try {
obj.cues = mediaelement.createCueList();
obj.activeCues = obj.shimActiveCues = obj._shimActiveCues = mediaelement.createCueList();
loadingTracks++;
createAjax = function(){
ajax = $.ajax({
dataType: 'text',
url: src,
success: function(text){
loadingTracks--;
var contentType = ajax.getResponseHeader('content-type') || '';
if(!contentType.indexOf('application/xml')){
text = ttmlTextToVTT(text);
} else if(contentType.indexOf('text/vtt')){
webshims.error('set the mime-type of your WebVTT files to text/vtt. see: http://dev.w3.org/html5/webvtt/#text/vtt');
}
mediaelement.parseCaptions(text, obj, function(cues){
if(cues && 'length' in cues){
trackData.readyState = 2;
$(track).triggerHandler('load');
$(mediaelem).triggerHandler('updatetrackdisplay');
} else {
error();
}
});
},
error: error
});
};
if(isDisabled){
setTimeout(createAjax, loadingTracks * 2);
} else {
createAjax();
}
} catch(er){
error();
webshims.error(er);
}
}
}
};
trackData.readyState = 0;
obj.shimActiveCues = null;
obj._shimActiveCues = null;
obj.activeCues = null;
obj.cues = null;
$(mediaelem).on(loadEvents, load);
if(_default){
obj.mode = showTracks[obj.kind] ? 'showing' : 'hidden';
load();
} else {
$(mediaelem).on('updatetrackdisplay', load);
}
};
mediaelement.createTextTrack = function(mediaelem, track){
var obj, trackData;
if(track.nodeName){
trackData = webshims.data(track, 'trackData');
if(trackData){
refreshTrack(track, trackData);
obj = trackData.track;
}
}
if(!obj){
obj = createEventTarget(webshims.objectCreate(textTrackProto));
if(!supportTrackMod){
copyProps.forEach(function(copyProp){
var prop = $.prop(track, copyProp);
if(prop){
obj[copyName[copyProp] || copyProp] = prop;
}
});
}
if(track.nodeName){
if(supportTrackMod){
copyProps.forEach(function(copyProp){
webshims.defineProperty(obj, copyName[copyProp] || copyProp, {
get: function(){
return $.prop(track, copyProp);
}
});
});
}
obj.id = $(track).prop('id');
trackData = webshims.data(track, 'trackData', {track: obj});
mediaelement.loadTextTrack(mediaelem, track, trackData, isDefaultTrack(track));
} else {
if(supportTrackMod){
copyProps.forEach(function(copyProp){
webshims.defineProperty(obj, copyName[copyProp] || copyProp, {
value: track[copyProp],
writeable: false
});
});
}
obj.cues = mediaelement.createCueList();
obj.activeCues = obj._shimActiveCues = obj.shimActiveCues = mediaelement.createCueList();
obj.mode = 'hidden';
obj.readyState = 2;
}
if(obj.kind == 'subtitles' && !obj.language){
webshims.error('you must provide a language for track in subtitles state');
}
obj.__wsmode = obj.mode;
webshims.defineProperty(obj, '_wsUpdateMode', {
value: function(){
$(mediaelem).triggerHandler('updatetrackdisplay');
},
enumerable: false
});
}
return obj;
};
if(!$.propHooks.mode){
$.propHooks.mode = {
set: function(obj, value){
obj.mode = value;
if(obj._wsUpdateMode && obj._wsUpdateMode.call){
obj._wsUpdateMode();
}
return obj.mode;
}
};
}
/*
taken from:
Captionator 0.5.1 [CaptionCrunch]
Christopher Giffard, 2011
Share and enjoy
https://github.com/cgiffard/Captionator
modified for webshims
*/
mediaelement.parseCaptionChunk = (function(){
// Set up timestamp parsers
var WebVTTTimestampParser = /^(\d{2})?:?(\d{2}):(\d{2})\.(\d+)\s+\-\-\>\s+(\d{2})?:?(\d{2}):(\d{2})\.(\d+)\s*(.*)/;
var WebVTTDEFAULTSCueParser = /^(DEFAULTS|DEFAULT)\s+\-\-\>\s+(.*)/g;
var WebVTTSTYLECueParser = /^(STYLE|STYLES)\s+\-\-\>\s*\n([\s\S]*)/g;
var WebVTTCOMMENTCueParser = /^(COMMENT|COMMENTS)\s+\-\-\>\s+(.*)/g;
var SRTTimestampParser = /^(\d{2})?:?(\d{2}):(\d{2})[\.\,](\d+)\s+\-\-\>\s+(\d{2})?:?(\d{2}):(\d{2})[\.\,](\d+)\s*(.*)/;
return function(subtitleElement,objectCount){
var subtitleParts, timeIn, timeOut, html, timeData, subtitlePartIndex, id;
var timestampMatch, tmpCue;
// WebVTT Special Cue Logic
if (WebVTTDEFAULTSCueParser.exec(subtitleElement) || WebVTTCOMMENTCueParser.exec(subtitleElement) || WebVTTSTYLECueParser.exec(subtitleElement)) {
return null;
}
subtitleParts = subtitleElement.split(/\n/g);
// Trim off any blank lines (logically, should only be max. one, but loop to be sure)
while (!subtitleParts[0].replace(/\s+/ig,"").length && subtitleParts.length > 0) {
subtitleParts.shift();
}
if (subtitleParts[0].match(/^\s*[a-z0-9-\_]+\s*$/ig)) {
// The identifier becomes the cue ID (when *we* load the cues from file. Programatically created cues can have an ID of whatever.)
id = String(subtitleParts.shift().replace(/\s*/ig,""));
}
for (subtitlePartIndex = 0; subtitlePartIndex < subtitleParts.length; subtitlePartIndex ++) {
var timestamp = subtitleParts[subtitlePartIndex];
if ((timestampMatch = WebVTTTimestampParser.exec(timestamp)) || (timestampMatch = SRTTimestampParser.exec(timestamp))) {
// WebVTT
timeData = timestampMatch.slice(1);
timeIn = parseInt((timeData[0]||0) * 60 * 60,10) + // Hours
parseInt((timeData[1]||0) * 60,10) + // Minutes
parseInt((timeData[2]||0),10) + // Seconds
parseFloat("0." + (timeData[3]||0)); // MS
timeOut = parseInt((timeData[4]||0) * 60 * 60,10) + // Hours
parseInt((timeData[5]||0) * 60,10) + // Minutes
parseInt((timeData[6]||0),10) + // Seconds
parseFloat("0." + (timeData[7]||0)); // MS
/*
if (timeData[8]) {
cueSettings = timeData[8];
}
*/
}
// We've got the timestamp - return all the other unmatched lines as the raw subtitle data
subtitleParts = subtitleParts.slice(0,subtitlePartIndex).concat(subtitleParts.slice(subtitlePartIndex+1));
break;
}
if (!timeIn && !timeOut) {
// We didn't extract any time information. Assume the cue is invalid!
webshims.warn("couldn't extract time information: "+[timeIn, timeOut, subtitleParts.join("\n"), id].join(' ; '));
return null;
}
/*
// Consolidate cue settings, convert defaults to object
var compositeCueSettings =
cueDefaults
.reduce(function(previous,current,index,array){
previous[current.split(":")[0]] = current.split(":")[1];
return previous;
},{});
// Loop through cue settings, replace defaults with cue specific settings if they exist
compositeCueSettings =
cueSettings
.split(/\s+/g)
.filter(function(set) { return set && !!set.length; })
// Convert array to a key/val object
.reduce(function(previous,current,index,array){
previous[current.split(":")[0]] = current.split(":")[1];
return previous;
},compositeCueSettings);
// Turn back into string like the VTTCue constructor expects
cueSettings = "";
for (var key in compositeCueSettings) {
if (compositeCueSettings.hasOwnProperty(key)) {
cueSettings += !!cueSettings.length ? " " : "";
cueSettings += key + ":" + compositeCueSettings[key];
}
}
*/
// The remaining lines are the subtitle payload itself (after removing an ID if present, and the time);
html = subtitleParts.join("\n");
tmpCue = new VTTCue(timeIn, timeOut, html);
if(id){
tmpCue.id = id;
}
return tmpCue;
};
})();
mediaelement.parseCaptions = function(captionData, track, complete) {
var cue, lazyProcess, regWevVTT, startDate, isWEBVTT;
mediaelement.createCueList();
if (captionData) {
regWevVTT = /^WEBVTT(\s*FILE)?/ig;
lazyProcess = function(i, len){
for(; i < len; i++){
cue = captionData[i];
if(regWevVTT.test(cue)){
isWEBVTT = true;
} else if(cue.replace(/\s*/ig,"").length){
cue = mediaelement.parseCaptionChunk(cue, i);
if(cue){
track.addCue(cue);
}
}
if(startDate < (new Date().getTime()) - 30){
i++;
setTimeout(function(){
startDate = new Date().getTime();
lazyProcess(i, len);
}, 90);
break;
}
}
if(i >= len){
if(!isWEBVTT){
webshims.error('please use WebVTT format. This is the standard');
}
complete(track.cues);
}
};
captionData = captionData.replace(/\r\n/g,"\n");
setTimeout(function(){
captionData = captionData.replace(/\r/g,"\n");
setTimeout(function(){
startDate = new Date().getTime();
captionData = captionData.split(/\n\n+/g);
lazyProcess(0, captionData.length);
}, 9);
}, 9);
} else {
webshims.error("Required parameter captionData not supplied.");
}
};
mediaelement.createTrackList = function(mediaelem, baseData){
baseData = baseData || webshims.data(mediaelem, 'mediaelementBase') || webshims.data(mediaelem, 'mediaelementBase', {});
if(!baseData.textTracks){
baseData.textTracks = [];
webshims.defineProperties(baseData.textTracks, {
onaddtrack: {value: null},
onremovetrack: {value: null},
onchange: {value: null},
getTrackById: {
value: function(id){
var track = null;
for(var i = 0; i < baseData.textTracks.length; i++){
if(id == baseData.textTracks[i].id){
track = baseData.textTracks[i];
break;
}
}
return track;
}
}
});
createEventTarget(baseData.textTracks);
$(mediaelem).on('updatetrackdisplay', function(){
var track;
for(var i = 0; i < baseData.textTracks.length; i++){
track = baseData.textTracks[i];
if(track.__wsmode != track.mode){
track.__wsmode = track.mode;
$([ baseData.textTracks ]).triggerHandler('change');
}
}
});
}
return baseData.textTracks;
};
if(!support.track){
webshims.defineNodeNamesBooleanProperty(['track'], 'default');
webshims.reflectProperties(['track'], ['srclang', 'label']);
webshims.defineNodeNameProperties('track', {
src: {
//attr: {},
reflect: true,
propType: 'src'
}
});
}
webshims.defineNodeNameProperties('track', {
kind: {
attr: support.track ? {
set: function(value){
var trackData = webshims.data(this, 'trackData');
this.setAttribute('data-kind', value);
if(trackData){
trackData.attrKind = value;
}
},
get: function(){
var trackData = webshims.data(this, 'trackData');
if(trackData && ('attrKind' in trackData)){
return trackData.attrKind;
}
return this.getAttribute('kind');
}
} : {},
reflect: true,
propType: 'enumarated',
defaultValue: 'subtitles',
limitedTo: ['subtitles', 'captions', 'descriptions', 'chapters', 'metadata']
}
});
$.each(copyProps, function(i, copyProp){
var name = copyName[copyProp] || copyProp;
webshims.onNodeNamesPropertyModify('track', copyProp, function(){
var trackData = webshims.data(this, 'trackData');
if(trackData){
if(copyProp == 'kind'){
refreshTrack(this, trackData);
}
if(!supportTrackMod){
trackData.track[name] = $.prop(this, copyProp);
}
}
});
});
webshims.onNodeNamesPropertyModify('track', 'src', function(val){
if(val){
var data = webshims.data(this, 'trackData');
var media;
if(data){
media = $(this).closest('video, audio');
if(media[0]){
mediaelement.loadTextTrack(media, this, data);
}
}
}
});
//
webshims.defineNodeNamesProperties(['track'], {
ERROR: {
value: 3
},
LOADED: {
value: 2
},
LOADING: {
value: 1
},
NONE: {
value: 0
},
readyState: {
get: function(){
return (webshims.data(this, 'trackData') || {readyState: 0}).readyState;
},
writeable: false
},
track: {
get: function(){
return mediaelement.createTextTrack($(this).closest('audio, video')[0], this);
},
writeable: false
}
}, 'prop');
webshims.defineNodeNamesProperties(['audio', 'video'], {
textTracks: {
get: function(){
var media = this;
var baseData = webshims.data(media, 'mediaelementBase') || webshims.data(media, 'mediaelementBase', {});
var tracks = mediaelement.createTrackList(media, baseData);
if(!baseData.blockTrackListUpdate){
updateMediaTrackList.call(media, baseData, tracks);
}
return tracks;
},
writeable: false
},
addTextTrack: {
value: function(kind, label, lang){
var textTrack = mediaelement.createTextTrack(this, {
kind: dummyTrack.prop('kind', kind || '').prop('kind'),
label: label || '',
srclang: lang || ''
});
var baseData = webshims.data(this, 'mediaelementBase') || webshims.data(this, 'mediaelementBase', {});
if (!baseData.scriptedTextTracks) {
baseData.scriptedTextTracks = [];
}
baseData.scriptedTextTracks.push(textTrack);
updateMediaTrackList.call(this);
return textTrack;
}
}
}, 'prop');
//wsmediareload
var thUpdateList = function(e){
if($(e.target).is('audio, video')){
var baseData = webshims.data(e.target, 'mediaelementBase');
if(baseData){
clearTimeout(baseData.updateTrackListTimer);
baseData.updateTrackListTimer = setTimeout(function(){
updateMediaTrackList.call(e.target, baseData);
}, 0);
}
}
};
var getNativeReadyState = function(trackElem, textTrack){
return textTrack.readyState || trackElem.readyState;
};
var stopOriginalEvent = function(e){
if(e.originalEvent){
e.stopImmediatePropagation();
}
};
var hideNativeTracks = function(){
if(webshims.implement(this, 'track')){
var kind;
var origTrack = this.track;
if(origTrack){
if (!webshims.bugs.track && (origTrack.mode || getNativeReadyState(this, origTrack))) {
$.prop(this, 'track').mode = numericModes[origTrack.mode] || origTrack.mode;
}
//disable track from showing + remove UI
kind = $.prop(this, 'kind');
origTrack.mode = (typeof origTrack.mode == 'string') ? 'disabled' : 0;
this.kind = 'metadata';
$(this).attr({kind: kind});
}
$(this).on('load error', stopOriginalEvent);
}
};
webshims.addReady(function(context, insertedElement){
var insertedMedia = insertedElement.filter('video, audio, track').closest('audio, video');
$('video, audio', context)
.add(insertedMedia)
.each(function(){
updateMediaTrackList.call(this);
})
.on('emptied updatetracklist wsmediareload', thUpdateList)
.each(function(){
if(support.track){
var shimedTextTracks = $.prop(this, 'textTracks');
var origTextTracks = this.textTracks;
if(shimedTextTracks.length != origTextTracks.length){
webshims.warn("textTracks couldn't be copied");
}
$('track', this).each(hideNativeTracks);
}
})
;
insertedMedia.each(function(){
var media = this;
var baseData = webshims.data(media, 'mediaelementBase');
if(baseData){
clearTimeout(baseData.updateTrackListTimer);
baseData.updateTrackListTimer = setTimeout(function(){
updateMediaTrackList.call(media, baseData);
}, 9);
}
});
});
if(support.texttrackapi){
$('video, audio').trigger('trackapichange');
}
});
| schoren/cdnjs | ajax/libs/webshim/1.15.0/dev/shims/combos/22.js | JavaScript | mit | 28,861 |
/*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
//>>built
define("dojo/currency",["./_base/kernel","./_base/lang","./_base/array","./number","./i18n","./i18n!./cldr/nls/currency","./cldr/monetary"],function(_1,_2,_3,_4,_5,_6,_7){
_2.getObject("currency",true,_1);
_1.currency._mixInDefaults=function(_8){
_8=_8||{};
_8.type="currency";
var _9=_5.getLocalization("dojo.cldr","currency",_8.locale)||{};
var _a=_8.currency;
var _b=_7.getData(_a);
_3.forEach(["displayName","symbol","group","decimal"],function(_c){
_b[_c]=_9[_a+"_"+_c];
});
_b.fractional=[true,false];
return _2.mixin(_b,_8);
};
_1.currency.format=function(_d,_e){
return _4.format(_d,_1.currency._mixInDefaults(_e));
};
_1.currency.regexp=function(_f){
return _4.regexp(_1.currency._mixInDefaults(_f));
};
_1.currency.parse=function(_10,_11){
return _4.parse(_10,_1.currency._mixInDefaults(_11));
};
return _1.currency;
});
| marcbuils/WorkESB | www/admin/lib/dojo/dojo/currency.js | JavaScript | lgpl-3.0 | 1,037 |
/**
* @license Highcharts JS v5.0.1 (2016-10-26)
*
* (c) 2009-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
(function(factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else {
factory(Highcharts);
}
}(function(Highcharts) {
(function(Highcharts) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*
* Grid theme for Highcharts JS
* @author Torstein Honsi
*/
'use strict';
Highcharts.theme = {
colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'],
chart: {
backgroundColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 1,
y2: 1
},
stops: [
[0, 'rgb(255, 255, 255)'],
[1, 'rgb(240, 240, 255)']
]
},
borderWidth: 2,
plotBackgroundColor: 'rgba(255, 255, 255, .9)',
plotShadow: true,
plotBorderWidth: 1
},
title: {
style: {
color: '#000',
font: 'bold 16px "Trebuchet MS", Verdana, sans-serif'
}
},
subtitle: {
style: {
color: '#666666',
font: 'bold 12px "Trebuchet MS", Verdana, sans-serif'
}
},
xAxis: {
gridLineWidth: 1,
lineColor: '#000',
tickColor: '#000',
labels: {
style: {
color: '#000',
font: '11px Trebuchet MS, Verdana, sans-serif'
}
},
title: {
style: {
color: '#333',
fontWeight: 'bold',
fontSize: '12px',
fontFamily: 'Trebuchet MS, Verdana, sans-serif'
}
}
},
yAxis: {
minorTickInterval: 'auto',
lineColor: '#000',
lineWidth: 1,
tickWidth: 1,
tickColor: '#000',
labels: {
style: {
color: '#000',
font: '11px Trebuchet MS, Verdana, sans-serif'
}
},
title: {
style: {
color: '#333',
fontWeight: 'bold',
fontSize: '12px',
fontFamily: 'Trebuchet MS, Verdana, sans-serif'
}
}
},
legend: {
itemStyle: {
font: '9pt Trebuchet MS, Verdana, sans-serif',
color: 'black'
},
itemHoverStyle: {
color: '#039'
},
itemHiddenStyle: {
color: 'gray'
}
},
labels: {
style: {
color: '#99b'
}
},
navigation: {
buttonOptions: {
theme: {
stroke: '#CCCCCC'
}
}
}
};
// Apply the theme
Highcharts.setOptions(Highcharts.theme);
}(Highcharts));
}));
| redmunds/cdnjs | ajax/libs/highstock/5.0.1/themes/grid.js | JavaScript | mit | 3,816 |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("codesnippet","nb",{button:"Sett inn kodesnutt",codeContents:"Kodeinnhold",emptySnippetError:"En kodesnutt kan ikke være tom.",language:"Språk",title:"Kodesnutt",pathName:"kodesnutt"}); | Battleangel/bitfinexlendingbot | www/admin_lte/bower_components/ckeditor/plugins/codesnippet/lang/nb.js | JavaScript | gpl-3.0 | 360 |
/*
postal
Author: Jim Cowart (http://freshbrewedcode.com/jimcowart)
License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license)
Version 0.8.1
*/
(function ( root, factory ) {
if ( typeof module === "object" && module.exports ) {
// Node, or CommonJS-Like environments
module.exports = function ( _ ) {
_ = _ || require( "underscore" );
return factory( _ );
}
} else if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( ["underscore"], function ( _ ) {
return factory( _, root );
} );
} else {
// Browser globals
root.postal = factory( root._, root );
}
}( this, function ( _, global, undefined ) {
var DEFAULT_CHANNEL = "/",
DEFAULT_DISPOSEAFTER = 0,
SYSTEM_CHANNEL = "postal";
var ConsecutiveDistinctPredicate = function () {
var previous;
return function ( data ) {
var eq = false;
if ( _.isString( data ) ) {
eq = data === previous;
previous = data;
}
else {
eq = _.isEqual( data, previous );
previous = _.clone( data );
}
return !eq;
};
};
var DistinctPredicate = function () {
var previous = [];
return function ( data ) {
var isDistinct = !_.any( previous, function ( p ) {
if ( _.isObject( data ) || _.isArray( data ) ) {
return _.isEqual( data, p );
}
return data === p;
} );
if ( isDistinct ) {
previous.push( data );
}
return isDistinct;
};
};
var ChannelDefinition = function ( channelName ) {
this.channel = channelName || DEFAULT_CHANNEL;
};
ChannelDefinition.prototype.subscribe = function () {
return arguments.length === 1 ?
new SubscriptionDefinition( this.channel, arguments[0].topic, arguments[0].callback ) :
new SubscriptionDefinition( this.channel, arguments[0], arguments[1] );
};
ChannelDefinition.prototype.publish = function () {
var envelope = arguments.length === 1 ?
(Object.prototype.toString.call(arguments[0]) === '[object String]' ?
arguments[0] : { topic: arguments[0] }) : { topic : arguments[0], data : arguments[1] };
envelope.channel = this.channel;
return postal.configuration.bus.publish( envelope );
};
var SubscriptionDefinition = function ( channel, topic, callback ) {
this.channel = channel;
this.topic = topic;
this.callback = callback;
this.constraints = [];
this.context = null;
postal.configuration.bus.publish( {
channel : SYSTEM_CHANNEL,
topic : "subscription.created",
data : {
event : "subscription.created",
channel : channel,
topic : topic
}
} );
postal.configuration.bus.subscribe( this );
};
SubscriptionDefinition.prototype = {
unsubscribe : function () {
postal.configuration.bus.unsubscribe( this );
postal.configuration.bus.publish( {
channel : SYSTEM_CHANNEL,
topic : "subscription.removed",
data : {
event : "subscription.removed",
channel : this.channel,
topic : this.topic
}
} );
},
defer : function () {
var fn = this.callback;
this.callback = function ( data ) {
setTimeout( fn, 0, data );
};
return this;
},
disposeAfter : function ( maxCalls ) {
if ( _.isNaN( maxCalls ) || maxCalls <= 0 ) {
throw "The value provided to disposeAfter (maxCalls) must be a number greater than zero.";
}
var fn = this.callback;
var dispose = _.after( maxCalls, _.bind( function () {
this.unsubscribe();
}, this ) );
this.callback = function () {
fn.apply( this.context, arguments );
dispose();
};
return this;
},
distinctUntilChanged : function () {
this.withConstraint( new ConsecutiveDistinctPredicate() );
return this;
},
distinct : function () {
this.withConstraint( new DistinctPredicate() );
return this;
},
once : function () {
this.disposeAfter( 1 );
},
withConstraint : function ( predicate ) {
if ( !_.isFunction( predicate ) ) {
throw "Predicate constraint must be a function";
}
this.constraints.push( predicate );
return this;
},
withConstraints : function ( predicates ) {
var self = this;
if ( _.isArray( predicates ) ) {
_.each( predicates, function ( predicate ) {
self.withConstraint( predicate );
} );
}
return self;
},
withContext : function ( context ) {
this.context = context;
return this;
},
withDebounce : function ( milliseconds ) {
if ( _.isNaN( milliseconds ) ) {
throw "Milliseconds must be a number";
}
var fn = this.callback;
this.callback = _.debounce( fn, milliseconds );
return this;
},
withDelay : function ( milliseconds ) {
if ( _.isNaN( milliseconds ) ) {
throw "Milliseconds must be a number";
}
var fn = this.callback;
this.callback = function ( data ) {
setTimeout( function () {
fn( data );
}, milliseconds );
};
return this;
},
withThrottle : function ( milliseconds ) {
if ( _.isNaN( milliseconds ) ) {
throw "Milliseconds must be a number";
}
var fn = this.callback;
this.callback = _.throttle( fn, milliseconds );
return this;
},
subscribe : function ( callback ) {
this.callback = callback;
return this;
}
};
var bindingsResolver = {
cache : { },
compare : function ( binding, topic ) {
if ( this.cache[topic] && this.cache[topic][binding] ) {
return true;
}
var pattern = ("^" + binding.replace( /\./g, "\\." ) // escape actual periods
.replace( /\*/g, "[A-Z,a-z,0-9]*" ) // asterisks match any alpha-numeric 'word'
.replace( /#/g, ".*" ) + "$") // hash matches 'n' # of words (+ optional on start/end of topic)
.replace( "\\..*$", "(\\..*)*$" ) // fix end of topic matching on hash wildcards
.replace( "^.*\\.", "^(.*\\.)*" ); // fix beginning of topic matching on hash wildcards
var rgx = new RegExp( pattern );
var result = rgx.test( topic );
if ( result ) {
if ( !this.cache[topic] ) {
this.cache[topic] = {};
}
this.cache[topic][binding] = true;
}
return result;
},
reset : function () {
this.cache = {};
}
};
var fireSub = function(subDef, envelope) {
if ( postal.configuration.resolver.compare( subDef.topic, envelope.topic ) ) {
if ( _.all( subDef.constraints, function ( constraint ) {
return constraint.call( subDef.context, envelope.data, envelope );
} ) ) {
if ( typeof subDef.callback === 'function' ) {
subDef.callback.call( subDef.context, envelope.data, envelope );
}
}
}
};
var localBus = {
addWireTap : function ( callback ) {
var self = this;
self.wireTaps.push( callback );
return function () {
var idx = self.wireTaps.indexOf( callback );
if ( idx !== -1 ) {
self.wireTaps.splice( idx, 1 );
}
};
},
publish : function ( envelope ) {
envelope.timeStamp = new Date();
_.each( this.wireTaps, function ( tap ) {
tap( envelope.data, envelope );
} );
if ( this.subscriptions[envelope.channel] ) {
_.each( this.subscriptions[envelope.channel], function ( subscribers ) {
var idx = 0, len = subscribers.length, subDef;
while(idx < len) {
if( subDef = subscribers[idx++] ){
fireSub(subDef, envelope);
}
}
} );
}
return envelope;
},
reset : function () {
if ( this.subscriptions ) {
_.each( this.subscriptions, function ( channel ) {
_.each( channel, function ( topic ) {
while ( topic.length ) {
topic.pop().unsubscribe();
}
} );
} );
this.subscriptions = {};
}
},
subscribe : function ( subDef ) {
var idx, found, fn, channel = this.subscriptions[subDef.channel], subs;
if ( !channel ) {
channel = this.subscriptions[subDef.channel] = {};
}
subs = this.subscriptions[subDef.channel][subDef.topic];
if ( !subs ) {
subs = this.subscriptions[subDef.channel][subDef.topic] = [];
}
subs.push( subDef );
return subDef;
},
subscriptions : {},
wireTaps : [],
unsubscribe : function ( config ) {
if ( this.subscriptions[config.channel][config.topic] ) {
var len = this.subscriptions[config.channel][config.topic].length,
idx = 0;
for ( ; idx < len; idx++ ) {
if ( this.subscriptions[config.channel][config.topic][idx] === config ) {
this.subscriptions[config.channel][config.topic].splice( idx, 1 );
break;
}
}
}
}
};
localBus.subscriptions[SYSTEM_CHANNEL] = {};
var postal = {
configuration : {
bus : localBus,
resolver : bindingsResolver,
DEFAULT_CHANNEL : DEFAULT_CHANNEL,
SYSTEM_CHANNEL : SYSTEM_CHANNEL
},
ChannelDefinition : ChannelDefinition,
SubscriptionDefinition : SubscriptionDefinition,
channel : function ( channelName ) {
return new ChannelDefinition( channelName );
},
subscribe : function ( options ) {
return new SubscriptionDefinition( options.channel || DEFAULT_CHANNEL, options.topic, options.callback );
},
publish : function ( envelope ) {
envelope.channel = envelope.channel || DEFAULT_CHANNEL;
return postal.configuration.bus.publish( envelope );
},
addWireTap : function ( callback ) {
return this.configuration.bus.addWireTap( callback );
},
linkChannels : function ( sources, destinations ) {
var result = [];
sources = !_.isArray( sources ) ? [sources] : sources;
destinations = !_.isArray( destinations ) ? [destinations] : destinations;
_.each( sources, function ( source ) {
var sourceTopic = source.topic || "#";
_.each( destinations, function ( destination ) {
var destChannel = destination.channel || DEFAULT_CHANNEL;
result.push(
postal.subscribe( {
channel : source.channel || DEFAULT_CHANNEL,
topic : source.topic || "#",
callback : function ( data, env ) {
var newEnv = _.clone( env );
newEnv.topic = _.isFunction( destination.topic ) ? destination.topic( env.topic ) : destination.topic || env.topic;
newEnv.channel = destChannel;
newEnv.data = data;
postal.publish( newEnv );
}
} )
);
} );
} );
return result;
},
utils : {
getSubscribersFor : function () {
var channel = arguments[ 0 ],
tpc = arguments[ 1 ];
if ( arguments.length === 1 ) {
channel = arguments[ 0 ].channel || postal.configuration.DEFAULT_CHANNEL;
tpc = arguments[ 0 ].topic;
}
if ( postal.configuration.bus.subscriptions[ channel ] &&
postal.configuration.bus.subscriptions[ channel ].hasOwnProperty( tpc ) ) {
return postal.configuration.bus.subscriptions[ channel ][ tpc ];
}
return [];
},
reset : function () {
postal.configuration.bus.reset();
postal.configuration.resolver.reset();
}
}
};
return postal;
} )); | tkirda/cdnjs | ajax/libs/postal.js/0.8.1/postal.js | JavaScript | mit | 11,032 |
var app = require('../app')
var Peers = require('../services/Peers')
app.controller('PeersCtrl', ['$scope', function ($scope) {
$scope.loading = true
$scope.status = "Loading Peers..."
Peers.fetch().then(function(peers) {
$scope.loading = false
$scope.peers = peers
$scope.$apply()
})
}])
| bankonme/rippled-peers-webapp | src/controllers/PeersController.js | JavaScript | isc | 315 |
var painless = require('../../assertion/painless')
var test = painless.createGroup('Test object/namespace')
var t = painless.assert
var namespace = require('../../../src/object/namespace')
test('should create nested properties if not existent and return the created object', function () {
var o = {}
namespace(o, 'foo.bar')
t.same(o.foo, {bar: {}})
t.same(o.foo.bar, {})
})
test('should return an empty object', function () {
t.same(namespace({}, 'foo.bar'), {})
})
test('should reuse existing objects', function () {
var o = {
foo: {
lorem: 'ipsum'
}
}
var f = o.foo
t.same(namespace(o, 'foo.bar'), {})
t.same(o.foo, f)
t.same(o.foo.lorem, 'ipsum')
})
test('should return original object if no path', function () {
var obj = {}
t.same(namespace(obj), obj)
t.same(namespace(obj, ''), obj)
t.same(namespace(obj, null), obj)
})
test('shouldn\'t overwrite existing object', function () {
var obj = {
foo: {
bar: {
val: 123
}
}
}
var foo = obj.foo
t.same(namespace(obj, 'foo.bar'), foo.bar)
})
| akileez/toolz | test/spec/object/namespace.js | JavaScript | isc | 1,081 |
var User = require('../models/users');
exports.userLogin = function (fields, sucCb, errCb) {
console.log(fields);
sucCb(1);
}
| anistark/authverse | controllers/users.js | JavaScript | isc | 131 |
#!/usr/bin/env node
'use strict';
var documentation = require('../'),
path = require('path'),
yargs = require('yargs'),
extend = require('extend'),
loadConfig = require('../lib/load_config.js'),
commands = require('../lib/commands');
var parsedArgs = parseArgs();
commands[parsedArgs.command](documentation, parsedArgs);
function parseArgs() {
// reset() needs to be called at parse time because the yargs module uses an
// internal global variable to hold option state
var argv = addCommands(yargs, true)
.usage('Usage: $0 <command> [options]')
.version(function () {
return require('../package').version;
})
.option('shallow', {
describe: 'shallow mode turns off dependency resolution, ' +
'only processing the specified files (or the main script specified in package.json)',
default: false,
type: 'boolean'
})
.option('config', {
describe: 'configuration file. an array defining explicit sort order',
alias: 'c'
})
.option('external', {
describe: 'a string / glob match pattern that defines which external ' +
'modules will be whitelisted and included in the generated documentation.',
default: null
})
.option('extension', {
describe: 'only input source files matching this extension will be parsed, ' +
'this option can be used multiple times.',
alias: 'e'
})
.option('polyglot', {
type: 'boolean',
describe: 'polyglot mode turns off dependency resolution and ' +
'enables multi-language support. use this to document c++'
})
.option('private', {
describe: 'generate documentation tagged as private',
type: 'boolean',
default: false,
alias: 'p'
})
.option('access', {
describe: 'Include only comments with a given access level, out of private, ' +
'protected, public, undefined. By default, public, protected, and undefined access ' +
'levels are included',
choices: ['public', 'private', 'protected', 'undefined'],
alias: 'a'
})
.option('github', {
type: 'boolean',
describe: 'infer links to github in documentation',
alias: 'g'
})
.argv;
var options = {};
if (argv.config) {
options = loadConfig(argv.config);
}
options = extend(options, argv);
if (typeof options.access === 'string') {
options.access = [options.access];
}
if (options.private) {
options.access = (options.access || ['public', 'undefined', 'protected']).concat(['private']);
}
var command = argv._[0],
inputs = argv._.slice(1);
if (!commands[command]) {
yargs.showHelp();
var suggestion = [argv['$0'], 'build'].concat(process.argv.slice(2)).join(' ');
process.stderr.write('Unknown command: ' + command + '. Did you mean "' + suggestion + '"?\n');
process.exit(1);
}
if (inputs.length == 0) {
try {
var p = require(path.resolve('package.json'));
options.package = p;
inputs = [p.main || 'index.js'];
} catch (e) {
yargs.showHelp();
throw new Error('documentation was given no files and was not run in a module directory');
}
}
return {
inputs: inputs,
command: command,
commandOptions: addCommands(yargs).argv,
options: options
};
}
function addCommands(parser, descriptionOnly) {
parser = parser.demand(1);
for (var cmd in commands) {
if (descriptionOnly) {
parser = parser.command(cmd, commands[cmd].description);
} else {
parser = parser.command(cmd, commands[cmd].description, commands[cmd].parseArgs);
}
}
return parser.help('help');
}
| researchgate/documentation | bin/documentation.js | JavaScript | isc | 3,653 |
require('../lib/config')({headless: true}); // turn off output in tests.
var Code = require('code'),
path = require('path'),
Config = require('../lib').Config,
_ = require('lodash');
describe('config', function() {
it('should be initialized with sane defaults', function(done) {
var config = Config();
Code.expect(config.host).to.equal('127.0.0.1');
done();
});
it('should allow defaults to be overridden by opts', function(done) {
var config = Config({
host: '0.0.0.0'
});
Code.expect(config.host).to.equal('0.0.0.0');
done();
});
it('should behave as a singleton once initialized', function(done) {
Config({
host: '8.8.8.8'
});
var config = (require('../lib').Config)();
Code.expect(config.host).to.equal('8.8.8.8');
done();
});
it('it should remain compatible with `registryDBName` config', function(done) {
var config = Config({
registryDBName: 'registry',
couchUrl: 'http://localhost:5984',
couchUrlRemote: 'https://skimdb.npmjs.com/'
});
Code.expect(config.couchUrl).to.equal('http://localhost:5984/registry');
Code.expect(config.couchUrlRemote).to.equal('https://skimdb.npmjs.com/registry');
done();
});
it('it should default `couchUrlCache` to `couchUrlRemote` if operating as read-through cache', function(done) {
var config = Config({
couchUrlRemote: 'https://skimdb.npmjs.com/',
readThroughCache: true
});
Code.expect(config.couchUrlCache).to.equal('https://skimdb.npmjs.com/registry');
done();
});
it('it should use `couchUrlCache` when explicitely given', function(done) {
var config = Config({
couchUrlCache: 'https://skimdb.npmjs.com/',
couchUrlRemote: 'https://im.trapped.in.a.url.com/',
readThroughCache: true
});
Code.expect(config.couchUrlCache).to.equal('https://skimdb.npmjs.com/');
done();
});
});
| npm/enterprise-configurator | test/config-test.js | JavaScript | isc | 1,920 |
#!/usr/bin/env node
"use strict";
const path = require("path");
const argv = require("yargs").argv;
const maky = require("maky");
require(path.join(process.cwd(), "makyfile"));
const tasks = argv._;
if (tasks.length === 0) {
tasks.push("default");
}
maky.series(...tasks)().catch(maky.error);
| Makay11/maky | bin/maky.js | JavaScript | isc | 303 |
'use strict';
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _mixin = require('react-pure-render/mixin');
var _mixin2 = _interopRequireDefault(_mixin);
var _navigation_item = require('./navigation_item');
var _navigation_item2 = _interopRequireDefault(_navigation_item);
var _custom = require('../../custom');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getAllInSectionFromChild(headings, idx) {
for (var i = idx; i > 0; i--) {
if (headings[i].depth === 2) {
return getAllInSection(headings, i);
}
}
}
function getAllInSection(headings, idx) {
var activeHeadings = [];
for (var i = idx + 1; i < headings.length; i++) {
if (headings[i].depth === 3) {
activeHeadings.push(headings[i].children[0].value);
} else if (headings[i].depth === 2) {
break;
}
}
return activeHeadings;
}
var Navigation = _react2.default.createClass({
displayName: 'Navigation',
mixins: [_mixin2.default],
propTypes: {
ast: _react2.default.PropTypes.object.isRequired,
activeSection: _react2.default.PropTypes.string,
navigationItemClicked: _react2.default.PropTypes.func.isRequired
},
render: function render() {
var _this = this;
var activeHeadings = [];
var headings = this.props.ast.children.filter(function (child) {
return child.type === 'heading';
});
if (this.props.activeSection) {
var activeHeadingIdx = headings.findIndex(function (heading) {
return heading.children[0].value === _this.props.activeSection;
});
var activeHeading = headings[activeHeadingIdx];
if (activeHeading.depth === 3) {
activeHeadings = [this.props.activeSection].concat(getAllInSectionFromChild(headings, activeHeadingIdx));
}
// this could potentially have children, try to find them
if (activeHeading.depth === 2) {
activeHeadings = [this.props.activeSection].concat(getAllInSection(headings, activeHeadingIdx));
}
}
activeHeadings = activeHeadings.reduce(function (memo, heading) {
memo[heading] = true;
return memo;
}, {});
return _react2.default.createElement(
'div',
{ className: 'pad0x small' },
headings.map(function (child, i) {
var sectionName = child.children[0].value;
var active = sectionName === _this.props.activeSection;
if (child.depth === 1) {
return _react2.default.createElement(
'div',
{ key: i,
onClick: _this.navigationItemClicked,
className: 'small pad0x quiet space-top1' },
sectionName
);
} else if (child.depth === 2) {
return _react2.default.createElement(_navigation_item2.default, {
key: i,
href: '#' + child.data.id,
onClick: _this.props.navigationItemClicked,
active: active,
sectionName: sectionName });
} else if (child.depth === 3) {
if (activeHeadings.hasOwnProperty(sectionName)) {
return _react2.default.createElement(
'div',
{
key: i,
className: 'space-left1' },
_react2.default.createElement(_navigation_item2.default, {
href: '#' + child.data.id,
onClick: _this.props.navigationItemClicked,
active: active,
sectionName: sectionName })
);
}
}
}),
_react2.default.createElement(
'a',
{ href: '#origo-map', className: 'space-top2 pad1y dark keyline-top block small quiet' },
_custom.backLink
)
);
}
});
module.exports = Navigation; | origo-map/api-documentation | lib/components/navigation.js | JavaScript | isc | 3,787 |
export const lobbySubs = new SubsManager();
| ckiely91/acrofever | app/imports/subsManagers.js | JavaScript | isc | 44 |
import mod1214 from './mod1214';
var value=mod1214+1;
export default value;
| MirekSz/webpack-es6-ts | app/mods/mod1215.js | JavaScript | isc | 76 |
var painless = require('../../assertion/painless')
var test = painless.createGroup('Test lang/toBoolean')
var t = painless.assert
var toBoolean = require('../../../src/lang/toBoolean')
test('#toBoolean', function() {
t.is(toBoolean('false'), false)
t.is(toBoolean('false'), false)
t.is(toBoolean('False'), false)
t.is(toBoolean('Falsy',null,['false', 'falsy']), false)
t.is(toBoolean('true'), true)
t.is(toBoolean('the truth', 'the truth', 'this is falsy'), true)
t.is(toBoolean('this is falsy', 'the truth', 'this is falsy'), false)
t.is(toBoolean('true'), true)
t.is(toBoolean('trUe'), true)
t.is(toBoolean('trUe', /tru?/i), true)
t.is(toBoolean('something else'), undefined)
t.is(toBoolean(function(){}), true)
t.is(toBoolean(/regexp/), true)
t.is(toBoolean(''), undefined)
t.is(toBoolean(0), false)
t.is(toBoolean(1), true)
t.is(toBoolean('1'), true)
t.is(toBoolean('0'), false)
t.is(toBoolean(2), undefined)
t.is(toBoolean('foo true bar'), undefined)
t.is(toBoolean('foo true bar', /true/), true)
t.is(toBoolean('foo FALSE bar', null, /FALSE/), false)
t.is(toBoolean(' true '), true)
})
| akileez/toolz | test/spec/lang/toBoolean.js | JavaScript | isc | 1,141 |
/* eslint-env mocha */
'use strict'
const expect = require('chai').expect
const DAGNode = require('../src').DAGNode
const DAGService = require('../src').DAGService
const BlockService = require('ipfs-block-service')
const bs58 = require('bs58')
const series = require('run-series')
module.exports = function (repo) {
describe('DAGService', function () {
const bs = new BlockService(repo)
const dagService = new DAGService(bs)
it('add a mdag node', (done) => {
const node = new DAGNode(new Buffer('data data data'))
dagService.add(node, (err) => {
expect(err).to.not.exist
done()
})
})
it('get a mdag node from base58 encoded string', (done) => {
var encodedMh = 'QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG'
dagService.get(encodedMh, (err, fetchedNode) => {
expect(err).to.not.exist
expect(fetchedNode.data).to.deep.equal(new Buffer(bs58.decode('cL')))
// just picking the second link and comparing mhash buffer to expected
expect(fetchedNode.links[1].hash).to.deep.equal(new Buffer(bs58.decode('QmYCvbfNbCwFR45HiNP45rwJgvatpiW38D961L5qAhUM5Y')))
done()
})
})
it('get a mdag node from a multihash buffer', (done) => {
const mh = new Buffer(bs58.decode('QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG'))
dagService.get(mh, (err, fetchedNode) => {
expect(err).to.not.exist
expect(fetchedNode.data).to.deep.equal(new Buffer(bs58.decode('cL')))
expect(fetchedNode.links[1].hash).to.deep.equal(new Buffer(bs58.decode('QmYCvbfNbCwFR45HiNP45rwJgvatpiW38D961L5qAhUM5Y')))
done()
})
})
it('get a mdag node from a /ipfs/ path', (done) => {
const ipfsPath = '/ipfs/QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG'
dagService.get(ipfsPath, (err, fetchedNode) => {
expect(err).to.not.exist
expect(fetchedNode.data).to.deep.equal(new Buffer(bs58.decode('cL')))
expect(fetchedNode.links[1].hash).to.deep.equal(new Buffer(bs58.decode('QmYCvbfNbCwFR45HiNP45rwJgvatpiW38D961L5qAhUM5Y')))
done()
})
})
it('supply an improperly formatted string path', (done) => {
const mh = 'bad path'
const ipfsPath = '/ipfs/' + mh
dagService.get(ipfsPath, (err, fetchedNode) => {
const error = 'Error: Invalid Key'
expect(err.toString()).to.equal(error)
done()
})
})
it('supply improperly formatted multihash buffer', (done) => {
const mh = new Buffer('more data data data')
dagService.get(mh, (err, fetchedNode) => {
const error = 'Error: Invalid Key'
expect(err.toString()).to.equal(error)
done()
})
})
it('supply something weird', (done) => {
const mh = 3
dagService.get(mh, (err, fetchedNode) => {
const error = 'Error: Invalid Key'
expect(err.toString()).to.equal(error)
done()
})
})
it('get a dag recursively', (done) => {
// 1 -> 2 -> 3
const node1 = new DAGNode(new Buffer('1'))
const node2 = new DAGNode(new Buffer('2'))
const node3 = new DAGNode(new Buffer('3'))
series([
(cb) => { node2.addNodeLink('', node3); cb() },
(cb) => { node1.addNodeLink('', node2); cb() },
(cb) => { dagService.add(node1, cb) },
(cb) => { dagService.add(node2, cb) },
(cb) => { dagService.add(node3, cb) },
(cb) => {
dagService.getRecursive(node1.multihash(), (err, nodes) => {
expect(err).to.not.exist
expect(nodes.length).to.equal(3)
cb()
})
}
], (err) => {
expect(err).to.not.exist
done()
})
})
it('remove', (done) => {
const node = new DAGNode(new Buffer('not going to live enough'))
dagService.add(node, (err) => {
expect(err).to.not.exist
const mh = node.multihash()
dagService.get(mh, (err, fetchedNode) => {
expect(err).to.not.exist
dagService.remove(mh, (err) => {
expect(err).to.not.exist
dagService.get(mh, (err) => {
expect(err).to.exist
done()
})
})
})
})
})
// tests to see if we are doing the encoding well
it('cycle test', (done) => {
const dftHash = 'QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG'
const mh = new Buffer(bs58.decode(dftHash))
dagService.get(mh, (err, node) => {
expect(err).to.not.exist
expect(mh.equals(node.multihash())).to.equal(true)
const n = new DAGNode(node.data, node.links)
const cn = n.copy()
expect(mh.equals(cn.multihash())).to.equal(true)
dagService.add(cn, (err) => {
expect(err).to.not.exist
dagService.get(cn.multihash(), (err, nodeB) => {
expect(err).to.not.exist
expect(nodeB.data.equals(node.data)).to.equal(true)
expect(nodeB.links.length).to.equal(node.links.length)
expect(nodeB.data.equals(new Buffer('\u0008\u0001'))).to.equal(true)
done()
})
})
})
})
it('get a broken dag recursively', (done) => {
// 1 -> 2 -> 3
const node1 = new DAGNode(new Buffer('a'))
const node2 = new DAGNode(new Buffer('b'))
const node3 = new DAGNode(new Buffer('c'))
series([
(cb) => { node2.addNodeLink('', node3); cb() },
(cb) => { node1.addNodeLink('', node2); cb() },
(cb) => { dagService.add(node1, cb) },
// on purpose, do not add node2 (cb) => { dagService.add(node2, cb) },
(cb) => { dagService.add(node3, cb) },
(cb) => {
dagService.getRecursive(node1.multihash(), (err, nodes) => {
expect(err).to.exist
expect(nodes.length).to.equal(1)
cb()
})
}
], (err) => {
expect(err).to.not.exist
done()
})
})
})
}
| vijayee/js-ipfs-merkle-dag | test/dag-service-test.js | JavaScript | isc | 5,999 |
"use strict";
//# sourceMappingURL=menu.js.map | dileepa79/goeasy | node_modules_custom/primeng/components/api/menu.js | JavaScript | isc | 46 |
var types = require("./lib/types");
// This core module of AST types captures ES5 as it is parsed today by
// git://github.com/ariya/esprima.git#master.
require("./def/core");
// Feel free to add to or remove from this list of extension modules to
// configure the precise type hierarchy that you need.
require("./def/es6");
require("./def/es7");
require("./def/mozilla");
require("./def/e4x");
require("./def/fb-harmony");
types.finalize();
exports.Type = types.Type;
exports.builtInTypes = types.builtInTypes;
exports.namedTypes = types.namedTypes;
exports.builders = types.builders;
exports.defineMethod = types.defineMethod;
exports.getFieldValue = types.getFieldValue;
exports.eachField = types.eachField;
exports.someField = types.someField;
exports.traverse = require("./lib/traverse");
exports.finalize = types.finalize;
exports.NodePath = require("./lib/node-path");
| listochkin/EmberOverflow-OdessaJS-2014 | client/node_modules/ember-cli/node_modules/broccoli-es3-safe-recast/node_modules/es3-safe-recast/node_modules/recast/node_modules/ast-types/main.js | JavaScript | isc | 880 |
var app = app || {};
app.ItemView = Backbone.View.extend({
tagName: 'li',
template: _.template( $( '#list-template-simple' ).html() ),
render: function() {
this.$el.html( this.template( this.model.toJSON() ) );
return this;
},
events: {
}
}); | vancetran/derp | app/js/views/itemView.js | JavaScript | isc | 258 |
module.exports = {
setHelper: require('./lib/set_helper'),
Command: require('./lib/command'),
Runner: require('./lib/runner'),
runners: {
API: require('./lib/runners/api'),
CLI: require('./lib/runners/cli')
}
}
| nicolasmccurdy/final | index.js | JavaScript | isc | 229 |
/**
* The states were interested in
*/
import Users from "./users";
const slugify = require('slugify')
const _ = require('underscore')
const {
PARSE_POSTS,
PARSE_USERS,
PARSE_SETTINGS,
PARSE_TOPICS,
PARSE_COMMENTS,
PARSE_HISTORY,
PARSE_FLAGS,
// Edit form
MODEL_FORM_TYPE_NEW,
MODEL_FORM_TYPE_EDIT,
} = require('./constants').default
const {
getInstanceWithoutData,
appendGeoLocation,
createParseInstance,
} = require('../parse/objects').default
import Posts from "./posts";
import Comments from "./comments";
import Settings from "./settings";
import AppConstants from './appConstants'
import Topics from './topics'
import AppMaintainTasks from './appMaintainTasks'
import Flags from "./flags";
const UUID = require('../components/vendor/uuid');
const {
getFirstOnlineParseInstance
} = require('../parse/parseUtiles').default
const Records = {}
Records.toFirstUpperString = function (name) {
return name.charAt(0).toUpperCase() + name.slice(1);
}
Records.setParseObjectFieldWithoutData = function (parseType, instance, parseInstanceId) {
const {objectSchemaName} = AppConstants.realmObjects[parseType];
const instanceWithoutData = getInstanceWithoutData(objectSchemaName, parseInstanceId)
instance.set(parseType, instanceWithoutData);
}
Records.setParseObjectFieldWithoutDataBySchema = function (objectSchemaName, instance, parseInstanceId) {
const instanceWithoutData = getInstanceWithoutData(objectSchemaName, parseInstanceId)
const parseType = AppConstants.realmTypes[objectSchemaName]
instance.set(parseType, instanceWithoutData);
}
Records.setParseOnlineObjectStatus = function (objectSchemaName, onlineParseObject, tableSelectAction) {
switch (objectSchemaName) {
case PARSE_POSTS:
Posts.setParseOnlineObjectStatus(onlineParseObject, tableSelectAction)
break;
case PARSE_COMMENTS:
Comments.setParseOnlineObjectStatus(onlineParseObject, tableSelectAction)
break;
case PARSE_USERS:
Users.setParseOnlineObjectStatus(onlineParseObject, tableSelectAction)
break;
case PARSE_TOPICS:
Topics.setParseOnlineObjectStatus(onlineParseObject, tableSelectAction)
break;
case PARSE_FLAGS:
Flags.setParseOnlineObjectStatus(onlineParseObject, tableSelectAction)
break;
}
}
Records.createNewTopic = async function (object) {
// "_id" : "e01479a43f25cfc314346805385d0c17",
// "status" : NumberInt(1),
// "name" : "Ranjit Singh",
// "is_ignore" : false,
// "statistic" : {
// "postCount" : NumberInt(1)
// },
// "slug" : "ranjit-singh"
const onlineParseObject = createParseInstance(PARSE_TOPICS)
onlineParseObject.set("status", Topics.config.STATUS_APPROVED)
onlineParseObject.set("name", object.name)
onlineParseObject.set("slug", slugify(object.name, '_'))
onlineParseObject.set("is_ignore", false)
onlineParseObject.set("active", false)
onlineParseObject.set("statistic", {postCount: 1})
/**
* Must return the new topic parse online instance with it's objectId.
*/
return await onlineParseObject.save()
}
Records.getOnlineObjectDict = function (array) {
let dict = {}
array.map(function (item) {
dict[item.id] = item;
})
return dict;
}
Records.createOnlineParseInstance = async function (editModelType, onlineParseObject, objectSchemaName, localRecorder) {
switch (objectSchemaName) {
case PARSE_POSTS:
// Basic Fields
// Attributes
onlineParseObject.set('title', localRecorder.postTitle)
onlineParseObject.set('slug', localRecorder.postSlug)
onlineParseObject.set('status', localRecorder.postStatus)
const _postTopics = localRecorder.postTopics;
const _savedTopics = []
for (let i = 0; i < _postTopics.length; i++) {
if (Topics.checkNewTopic(_postTopics[i])) {
const newTopic = await Records.createNewTopic(_postTopics[i])
_savedTopics.push(newTopic.id)
} else {
_savedTopics.push(_postTopics[i].id)
}
}
onlineParseObject.set('topics', _savedTopics)
debugger
break;
case PARSE_TOPICS:
// Basic Fields
// Attributes
onlineParseObject.set('name', localRecorder.topicTitle)
onlineParseObject.set('slug', localRecorder.topicSlug)
break;
case PARSE_COMMENTS:
// Basic Fields
// Attributes
onlineParseObject.set('body', localRecorder.commentBody)
onlineParseObject.set('htmlBody', Comments.getHtmlBody(localRecorder.commentBody))
break;
case PARSE_FLAGS:
// Basic Fields
// Attributes
onlineParseObject.set('reason', localRecorder.flagReason)
break;
case PARSE_SETTINGS:
// Basic Fields
// Attributes
const settingsObjects = Settings.config.editTableDefaultObjects;
settingsObjects.map(function (object) {
onlineParseObject.set(object.columnValue, localRecorder[object.columnValue])
})
debugger
break;
}
}
Records.makeNewOnlineSiteInstance = async function (siteTag, siteField, siteStatus, localRecorder) {
const siteParseInstance = createParseInstance(PARSE_SITES)
const model = {
uniqueId: -1,
forTaskUniqueId: localRecorder.uniqueId,
validate: ( siteStatus === AppMaintainTasks.config.paginationOneRow.SITE_ALL_PAGINATION_STATUS_INVALID ? 0 : 1),
list: 0,
article: 0,
siteTag,
siteField,
siteStatus
}
await Records.createOnlineParseInstance(MODEL_FORM_TYPE_NEW, siteParseInstance, PARSE_SITES, model)
await siteParseInstance.save()
return siteParseInstance
}
export default Records;
| sidkarwal/politicl-wb-app | src/lib/records.js | JavaScript | mit | 5,631 |
!function(win, doc, $){
$(doc).ready(function() {
var html = doc.documentElement.innerHTML;
var m1 = html.match(/tbs[\'\"]?:\s*[\'\"](\w+)[\'\"]/); // tbs:'zzzz'
var m2 = html.match(/fname=[\'\"]([^\'\"]+)[\'\"]/); // fname="Zzz"
if (m1 && m2) {
var tbs = m1[1];
var kw = m2[1];
var status_key = "tieba_" + encodeURIComponent(kw) + "_status";
chrome.runtime.sendMessage({method: "getLocalStorage", key: status_key}, function(res) {
var status = res.data;
var today = (new Date()).toDateString();
if (! (status && today === status)) {
// need cookie
chrome.runtime.sendMessage({method: "tieba_qiandao", "tbs": tbs, "kw": kw}, function(res) {});
} else {
console.log("[qiandao][tieba][" + kw + "] already signIn today.");
}
});
}
});
}(window, document, Zepto); | fayland/qiandao_chrome_extension | js/qiandao/tieba.js | JavaScript | mit | 1,008 |
version https://git-lfs.github.com/spec/v1
oid sha256:c9303c970274f7217ff4ee67feece2eabc5e8c25689a6d3908255e035ddb381f
size 29756
| yogeshsaroya/new-cdnjs | ajax/libs/spf/2.1.0/spf.js | JavaScript | mit | 130 |
module.exports = (ctx) => ({
map: ctx.env === 'production' ? false : {},
syntax: 'postcss-scss',
plugins: {
'postcss-easy-import': {},
'postcss-sassy-mixins': {},
'postcss-nested': {},
'postcss-advanced-variables': {},
'postcss-color-function': {},
'postcss-calc': {},
'postcss-flexbugs-fixes': {},
'postcss-strip-inline-comments': {},
'autoprefixer': { browsers: ['last 2 version'] },
'css-mqpacker': {},
'cssnano': ctx.env === 'production' ? {} : false
}
});
| unys/uny | postcss.config.js | JavaScript | mit | 513 |
/* tslint:disable:no-console */
const cluster = require("cluster");
const control = require("strong-cluster-control");
const app = require("./build/binaryscanr");
control.start({ size: 1 })
.on("error", (err) => {
console.error(err);
});
if (cluster.isWorker) {
app.listen(process.env.PORT || "3000");
console.log(`Worker ${process.pid} started`);
}
| shuntksh/binaryscanr | index.js | JavaScript | mit | 377 |
var Multipart = require('multipart-stream')
var duplexify = require('duplexify')
var stream = require('stream')
var Path = require('path')
var collect = require('./collect')
var common = require('./common')
var randomString = common.randomString
module.exports = v2mpTree
// we'll create three streams:
// - w: a writable stream. it receives vinyl files
// - mps: a multipart stream in between.
// - r: a readable stream. it outputs text. needed to
// give the caller something, while w finishes.
//
// we do all processing on the incoming vinyl metadata
// before we transform to multipart, that's becasue we
// need a complete view of the filesystem. (/ the code
// i lifted did that and it's convoluted enough not to
// want to change it...)
function v2mpTree(opts) {
opts = opts || {}
opts.boundary = opts.boundary || randomString()
var r = new stream.PassThrough({objectMode: true})
var w = new stream.PassThrough({objectMode: true})
var out = duplexify.obj(w, r)
out.boundary = opts.boundary
collect(w, function(err, files) {
if (err) {
r.emit('error', err)
return
}
try {
// construct the multipart streams from these files
var mp = streamForCollection(opts.boundary, files)
// let the user know what the content-type header is.
// this is because multipart is such a grossly defined protocol :(
out.multipartHdr = "Content-Type: multipart/mixed; boundary=" + mp.boundary
if (opts.writeHeader) {
r.write(out.multipartHdr + "\r\n")
r.write("\r\n")
}
// now we pipe the multipart stream to
// the readable thing we returned.
// now the user will start receiving data.
mp.pipe(r)
} catch (e) {
r.emit('error', e)
}
})
return out
}
function streamForCollection(boundary, files) {
var parts = []
// walk through all the named files in order.
files.paths.sort()
for (var i = 0; i < files.paths.length; i++) {
var n = files.paths[i]
var s = streamForPath(files, n)
if (!s) continue // already processed.
parts.push({ body: s, headers: headersForFile(files.named[n])})
}
// then add all the unnamed files.
for (var i = 0; i < files.unnamed.length; i++) {
var f = files.unnamed[i] // raw vinyl files.
var s = streamForWrapped(files, f)
if (!s) continue // already processed.
parts.push({ body: s, headers: headersForFile(f)})
}
if (parts.length == 0) { // avoid multipart bug.
var s = streamForString("--" + boundary + "--\r\n") // close multipart.
s.boundary = boundary
return s
}
// write out multipart.
var mp = new Multipart(boundary)
for (var i = 0; i < parts.length; i++) {
mp.addPart(parts[i])
}
return mp
}
function streamForString(str) {
var s = new stream.PassThrough()
s.end(str)
return s
}
function streamForPath(files, path) {
var o = files.named[path]
if (!o) {
throw new Error("no object for path. lib error.")
}
if (!o.file) { // no vinyl file, so no need to process this one.
return
}
// avoid processing twice.
if (o.done) return null // already processed it
o.done = true // mark it as already processed.
return streamForWrapped(files, o)
}
function streamForWrapped(files, f) {
if (f.file.isDirectory()) {
return multipartForDir(files, f)
}
// stream for a file
return f.file.contents
}
function multipartForDir(files, dir) {
// we still write the boundary for the headers
dir.boundary = randomString()
if (!dir.children || dir.children.length < 1) {
// we have to intercept this here and return an empty stream.
// because multipart lib fails if there are no parts. see
// https://github.com/hendrikcech/multipart-stream/issues/1
return streamForString("--" + dir.boundary + "--\r\n") // close multipart.
}
var mp = new Multipart(dir.boundary)
for (var i = 0; i < dir.children.length; i++) {
var child = dir.children[i]
if (!child.file) {
throw new Error("child has no file. lib error")
}
var s = streamForPath(files, child.file.path)
mp.addPart({ body: s, headers: headersForFile(child) })
}
return mp
}
function headersForFile(o) {
var fpath = common.cleanPath(o.file.path, o.file.base)
var h = {}
h['Content-Disposition'] = 'file; filename="' + fpath + '"'
if (o.file.isDirectory()) {
h['Content-Type'] = 'multipart/mixed; boundary=' + o.boundary
} else {
h['Content-Type'] = 'application/octet-stream'
}
return h
}
| jbenet/node-vinyl-multipart-stream | mp2v_tree.js | JavaScript | mit | 4,512 |
var base = require("./events-base");
var extend = require("../../../utilities/extend");
var proto = {
onclick: function onclick(e) {
var elt = e.target;
var eltRect = elt.getBoundingClientRect(),
x = eltRect.left + ((eltRect.width) / 2),
y = eltRect.top + (eltRect.height / 2);
this.spewHearts(x, y);
},
ontouch: function ontouch(e) {
var elt = e.target;
var eltRect = elt.getBoundingClientRect(),
x = eltRect.left + ((eltRect.width) / 2),
y = eltRect.top + (eltRect.height / 2);
this.spewHearts(x, y);
},
};
module.exports = extend({}, base, proto); | brettimus/super-hearts | src/js/prototypes/animation/mixins/events-fixed.js | JavaScript | mit | 690 |
describe('Utils', function() {
beforeEach(module('bullhorn'));
var Utils;
beforeEach(inject(function (_Utils_) {
Utils = _Utils_;
}));
describe('#generateRandomString()', function() {
it('should return a string with the expected length', function() {
expect(Utils.generateRandomString(0).length).to.equal(0);
expect(Utils.generateRandomString(1).length).to.equal(1);
expect(Utils.generateRandomString(5).length).to.equal(5);
expect(Utils.generateRandomString(10).length).to.equal(10);
});
});
describe('#querystring()', function() {
it('should transform an object into a querystring', function() {
var obj = {
'first': 'foo',
'second': 'bar',
'third': false
};
var qs = Utils.querystring(obj);
expect(qs).to.equal('first=foo&second=bar&third=false');
});
it('should return an empty string if the passed object is undefined', function() {
var qs = Utils.querystring(undefined);
expect(qs).to.equal('');
});
});
});
| philipproplesch/bullhorn | test/spec/services/utils.spec.js | JavaScript | mit | 1,048 |
(function () {
'use strict';
angular.module('ramlEditorApp')
.service('confirmModal', function confirmModal($rootScope, $modal) {
var self = this;
/**
* @param {String} title
* @param {String} message
* @param {Object} [options = {canDiscard, closeButtonLabel, discardButtonLabel, dismissButtonLabel, closeButtonCssClass}]
*/
self.open = function open(message, title, options) {
options = angular.extend({
canDiscard: false,
closeButtonLabel: 'OK',
discardButtonLabel: 'Discard',
dismissButtonLabel: 'Cancel',
closeButtonCssClass: 'btn-primary'
}, options);
return $modal
.open({
templateUrl: 'views/confirm-modal.html',
controller: 'ConfirmController',
scope: angular.extend($rootScope.$new(), {
title: title,
message: message,
canDiscard: options.canDiscard,
closeButtonLabel: options.closeButtonLabel,
discardButtonLabel: options.discardButtonLabel,
dismissButtonLabel: options.dismissButtonLabel,
closeButtonCssClass: options.closeButtonCssClass
})
})
.result
;
};
return self;
})
.controller('ConfirmController', function ConfirmController($modalInstance, $scope) {
$scope.discard = function discard() {
$modalInstance.dismiss(angular.extend(new Error(), {discard: true}));
};
})
;
})();
| hadwinzhy/common_platform | rails5_api/public/docs-designer/app/scripts/services/confirm-modal.js | JavaScript | mit | 1,646 |
/**
* HTTP Cloud Function.
*
* @param {Object} req Cloud Function request context.
* @param {Object} res Cloud Function response context.
*/
exports.cadeOLeoVer = function cadeOLeoVer (req, res) {
const CadeOLeo = require("./cadeoleo.js");
var date1, date2;
var leoBirthday = new Date('2015-10-22');
var today = new Date(Date.UTC(
(new Date()).getUTCFullYear(),
(new Date()).getUTCMonth(),
(new Date()).getUTCDate()
));
var vLeo = false;
var vToday = false;
date1 = new Date(req.query.date1);
date2 = new Date(req.query.date2);
if (
isNaN(date1.getTime())
&& isNaN(date2.getTime())
) {
date1 = leoBirthday;
date2 = today;
vLeo = true;
vToday = true;
} else if (isNaN(date1.getTime()) ) {
date1 = today;
vToday = true;
} else if (isNaN(date2.getTime()) ) {
date2 = today;
vToday = true;
}
var v = CadeOLeo.Ver.v(date1, date2);
res.send(
{
"version": v,
"date1": date1,
"date2": date2,
"vLeo": vLeo,
"vToday": vToday
}
);
res.status(200).end();
};
| CadeOLeo/CadeOLeoBot | gcf_http/index.js | JavaScript | mit | 1,084 |
// ==UserScript==
// @name Sort Uploads Alphabetically
// @namespace pxgamer
// @version 0.2
// @description Sort user uploads alphabetically
// @author pxgamer
// @include *kat.cr/user/*/uploads/
// @grant none
// ==/UserScript==
(function() {
'use strict';
var rows = [];
$('tr.firstr th.width100perc.nopad').html(
'<a class="sortAlpha">torrent name</a>'
);
$('.data tr[id^="torrent_"]').each(function() {
var title = $('.cellMainLink', $(this)).text();
var html = $(this).html();
rows.push({"title":title, "html":html});
});
$('.sortAlpha').on('click', function() {
var sortName = 'title';
var sortType = 'desc';
sortTable(sortName, sortType);
});
function sortByKey(array, key) {
return array.sort(function(a, b) {
var x = a[key];
var y = b[key];
if (typeof x == "string") {
x = x.toLowerCase();
y = y.toLowerCase();
}
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
function sortTable(sortName, sortType) {
sortByKey(rows, sortName);
if (!sortType) {
rows.reverse();
}
$('.data tr[id^="torrent_"]').remove();
for (var i=0;i<rows.length;i++) {
$('.data').append('<tr id="torrent_'+i+'">'+rows[i].html+'</tr>');
}
}
})();
| PXgamer/PX-Scripts | User/Sort Uploads Alphabetically.user.js | JavaScript | mit | 1,453 |
module.exports = function(){
var restrict = {};
restrict.admin = function *(next) {
if (this.session.passport.user.type < 10){
this.status = 400;
this.body = {error:'restricted'};
}
else{
yield next;
}
}
return restrict;
}//end exports | justonpoints/koa-bookshelf-api-starter | lib/routes/restrict.js | JavaScript | mit | 288 |
'use strict';
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');
gulp.task('eslint', function eslintTask() {
return gulp.src(['**/*.js', '!node_modules/**'])
.pipe(excludeGitignore())
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('nsp', function nspTask(cb) {
nsp({package: path.resolve('package.json')}, cb);
});
gulp.task('pre-test', function preTestTask() {
return gulp.src('lib/**/*.js')
.pipe(excludeGitignore())
.pipe(istanbul({
includeUntested: true
}))
.pipe(istanbul.hookRequire());
});
gulp.task('test', ['pre-test'], function testTask(cb) {
var mochaErr;
gulp.src('test/**/*.js')
.pipe(plumber())
.pipe(mocha({reporter: 'spec'}))
.on('error', function onError(err) {
mochaErr = err;
})
.pipe(istanbul.writeReports())
.on('end', function onEnd() {
cb(mochaErr);
});
});
gulp.task('watch', function watchTask() {
gulp.watch(['generators/**/*.js', 'test/**'], ['test']);
});
gulp.task('coveralls', ['test'], function coverallsTask() {
return (process.env.CI) ? gulp.src(path.join(__dirname, 'coverage/lcov.info')).pipe(coveralls()) : {};
});
gulp.task('prepublish', ['nsp']);
gulp.task('default', ['eslint', 'test', 'coveralls']);
| mobulum/npm-yo-generator-spring-boot-application-from-swagger | gulpfile.js | JavaScript | mit | 1,567 |
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';
@inject(HttpClient)
export class Api{
heading = 'API Test';
images = [];
last_param = 's={"id": -1}&l=1';
myKey_param = 'apiKey=w4-9cpE__HevCb_VMd1UAlX3YvRZrBns';
collections_locator = '/collections';
url = 'https://api.mongolab.com/api/1/databases';
my_server_url = 'http://localhost:3000';
last_saved_twitterite = '';
backup_message = '';
constructor(http){
this.http = http;
}
activate(){
}
getLastSavedTwitterite() {
console.log('getting last saved twitter');
return requestLastSavedTwitterite.then(response => {
this.last_saved_twitterite = response.content[0].id;
});
}
requestLastSavedTwitterite() {
console.log('requesting from Twitter');
return this.http.get(this.url + '/twitterites/' + this.collections_locator + '/twitterites' + '?' + this.last_param + '&' + this.myKey_param);
}
getMyDatabases() {
console.log('getting databases...');
return this.http.get(this.url + '?' + this.myKey_param).then( (response, err) => {
if(err) {
console.log(err);
} else {
console.log(response.content);
}
});
}
getTwitteritesCollections() {
console.log('getting collections...');
return this.http.get(this.url + '/twitterites/' + this.collections_locator + '?' + this.myKey_param).then( (response, err) => {
if (err) {
console.log(err);
} else {
console.log(response.content);
}
});
}
getTwitteritesNotSaved() {
console.log('getting last tweets from twitter');
return this.requestLastSavedTwitterite().then( (response) => {
var last_saved_id = response.content[0].id.toString();
var last_saved_id_last_char = Number(last_saved_id.slice(-1));
last_saved_id_last_char++;
last_saved_id = (last_saved_id.slice(0,-1) + last_saved_id_last_char);
this.http.get(this.my_server_url + '/favorites/' + last_saved_id)
.then( (response, err) => {
if (err) {
console.log(err);
} else {
this.backup_message = 'Your have ' + response.content[0].length + ' twitterites not saved';
}
});
});
}
canDeactivate(){
return confirm('Are you sure you want to leave?');
}
}
| yesobo/twitterites_api_test | src/api.js | JavaScript | mit | 2,318 |
/**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*/
// Import stuff
import React, { Component } from 'react';
import { connect } from 'react-redux';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import Appbar from 'material-ui/AppBar';
import {deepOrange500} from 'material-ui/styles/colors';
import * as mui from 'material-ui';
// setting up material color
const muiTheme = getMuiTheme({
palette: {
accent1Color: deepOrange500,
},
});
class App extends Component {
render() {
return(
<MuiThemeProvider muiTheme={muiTheme}>
<div className="wrapper">
{ this.props.children }
</div>
</MuiThemeProvider>
)
}
}
export default App;
// REDUX STUFF
// Which props do we want to inject, given the global state?
function select(state) {
return {
data: state
};
}
// Wrap the component to inject dispatch and state into it
export default connect(select)(App);
| OktavianRS/react-boilerplate | js/components/App.react.js | JavaScript | mit | 1,124 |
var app = angular.module('osoApp', [
'ngRoute',
'dangle'
], function () {
}).config([
'$routeProvider',
'$locationProvider',
'$httpProvider',
function ($routeProvider, $locationProvider, $httpProvider) {
$locationProvider.html5Mode(true);
}
]);
app.controller('MainCtrl', [
'$scope',
'$http',
function ($scope, $http) {
$scope.mode = 'start';
$scope.weightUseRange = true;
$scope.hopeUseRange = true;
$scope.weightConfirm = false;
$scope.inputed = false;
$scope.selfInput = true;
$scope.selectedS = 'is-active';
$scope.selectedU = '';
$scope.theme = '';
$scope.todayWeight = 65;
$scope.hopeWeight = 65, userid = '';
$scope.goLogin = function () {
$scope.mode = 'start';
};
$scope.goLoginTwitter = function () {
location.href = '/auth/twitter';
};
$scope.goLoginGoogle = function () {
location.href = '/auth/google';
};
$scope.goLoginFacebook = function () {
location.href = '/auth/facebook';
};
$http({
method: 'GET',
url: '/user'
}).success(function (data) {
console.log(data[0]);
$scope.userName = data[0].name;
if (data[0].hope) {
$scope.hopeWeight = data[0].hope;
}
userid = data[0].id;
if (userid) {
$http({
method: 'GET',
url: '/getweight'
}).success(function (data) {
console.log(data);
if (data[0]) {
$scope.todayWeight = data[0].weight;
$scope.mode = 'myhome';
$http({
method: 'get',
url: '/getweightlist'
}).success(function (data) {
$scope.weightdata = {
_type: 'date_histogram',
entries: data
};
console.log(data);
});
}
});
}
});
$scope.changeStartInput = function (flag) {
if (flag === 'w') {
$scope.weightUseRange = !$scope.weightUseRange;
}
if (flag === 'h') {
$scope.hopeUseRange = !$scope.hopeUseRange;
}
};
$scope.goStart = function () {
$http.post('/setUser', {
userName: $scope.userName,
todayWeight: $scope.todayWeight,
hopeWeight: $scope.hopeWeight
}).success(function () {
$scope.mode = 'myhome';
$scope.theme = '';
});
};
$scope.showWeightConfirm = function () {
$scope.weightConfirm = true;
};
$scope.postWeight = function () {
$http.post('/setweight', { weight: $scope.todayWeight }).success(function (data) {
console.log(data);
$scope.result = data.result;
$scope.inputed = true;
});
};
$scope.goSetting = function () {
$scope.mode = 'setting';
$scope.theme = 'tm-dark';
};
$scope.goListInput = function () {
$scope.mode = 'listInput';
};
$scope.changeInputType = function (flag) {
console.log(flag, $scope.selfInput);
if (flag === 'u') {
$scope.selfInput = false;
$scope.selectedU = 'is-active';
$scope.selectedS = '';
} else {
$scope.selfInput = true;
$scope.selectedU = '';
$scope.selectedS = 'is-active';
}
};
$scope.isActivate = function (flag) {
console.log('activate', flag);
$scope.isactive = '';
};
$scope.goListInputConfirm = function () {
$scope.mode = 'listInputConfirm';
};
}
]); | OSO2014/oso2014 | dev/public/javascripts/app.js | JavaScript | mit | 3,498 |
var argv = require('minimist')(process.argv.slice(2));
var Yts = require('./nyaa')
var chalk = require('chalk');
var path = require('path');
var tmpdir = require('os-tmpdir');
var isOutdated = require('is-outdated');
var parseTorrent = require('parse-torrent');
var open = require('open');
var validURL = require('valid-url');
var spawn = require('child_process').spawn;
var showRecentMovies = function (options) {
options = options || {};
options.sort_by = options.sort_by || 'year';
options.order_by = options.order_by || 'desc';
Yts.listMovies(options, function (err, res) {
if (err) { console.log(err); }
res.data.movies.forEach(function (movie) {
console.log(chalk.underline.yellow(movie.id) + ': ' + movie.title_long);
});
});
};
var searchMovie = function (str) {
Yts.listMovies({ query_term: str }, function (err, res) {
if (err) { console.log(err); }
if (res.data.movies.length < 1) {
console.log('No movies found');
} else {
res.data.movies.forEach(function (movie) {
console.log(chalk.underline.yellow(movie.id) + ': ' + movie.title_long);
});
}
});
};
var getInfo = function (movieID) {
Yts.movieDetails({ movie_id: movieID }, function (err, res) {
if (err) { return console.log(err); }
if (res.status === 'error') {
return console.log(chalk.red(res.status_message));
}
console.log('Opening browser with movie info...');
if (validURL.isWebUri(res.data.url)) {
open(res.data.url);
} else {
console.log(chalk.yellow('Movie has invalid URL'));
}
});
}
var getMovie = function (movieID, quality, subs) {
quality = quality || '720p';
subs = subs || 'english';
Yts.movieDetails({ movie_id: movieID }, function (err, res) {
if (res.status === 'error') {
return console.log(chalk.red(res.status_message));
}
var subsSavePath = path.join(tmpdir(), res.data.slug + '.srt');
var torrInfo = res.data.torrents.filter(function (torr) {
return torr.quality === quality;
}).pop();
parseTorrent.remote(torrInfo.url, function (err, tinfo) {
var magnetURI = parseTorrent.toMagnetURI(tinfo);
var peerflixPath = path.join(__dirname, 'node_modules', '.bin', 'peerflix');
var peerflix = spawn(peerflixPath, [
'-t',
subsSavePath,
magnetURI,
'--vlc'
]);
peerflix.stdout.on('data', function (data) {
process.stdout.write(data);
});
peerflix.stderr.on('data', function (data) {
process.stdout.write(data);
});
});
Yts.getSubtitles(res.data.imdb_code, function (err, data) {
if (!data || !data[subs]) {
return console.log('No subtitles available in %s', subs);
}
var zipPath = data[subs].shift().url;
Yts.fetchSubtitle(zipPath, subsSavePath, function (err, data) {
if (err) { console.log(err); }
});
});
})
};
var showHelp = function () {
console.log('movees [options]');
console.log('Options:');
console.log('--search <search term> search for a movie');
console.log('--info <movie id> open web page with movie info');
console.log('--watch <movie id> [--quality <720p|1080p|3d> [--subs <subtitle language>] watch a movie');
console.log('--latest [--page <page number>] [--limit <number of movies p/page>] show latest movies available');
console.log('--version show version');
console.log('--help show usage help');
};
var showVersion = function () {
var version = require('./package.json').version;
console.log('Movees (version %s)', version);
};
var checkForUpdates = function () {
var currentVersion = require('./package.json').version;
isOutdated('movees', currentVersion, function (err, res) {
if (res) {
console.log('\n----------------------------------------');
console.log(chalk.bold('** UPDATE AVAILABLE **'));
console.log(chalk.underline('New version:') + ' ' + chalk.green(res.version));
console.log(chalk.underline('Current version:') + ' ' + chalk.red(currentVersion));
console.log('\nPlease update with: npm update -g movees');
console.log('----------------------------------------\n');
}
});
};
/**
* CLI arguments handling
*/
// avoid calling npm when testing
if (!argv.test) {
checkForUpdates();
}
if (argv.search) {
searchMovie(argv.search);
} else if (argv.watch) {
getMovie(argv.watch, argv.quality, argv.subs);
} else if (argv.info) {
getInfo(argv.info);
} else if (argv.latest) {
var opts = {};
opts.page = argv.page || 1;
opts.limit = argv.limit || '20';
showRecentMovies(opts);
} else if (argv.version) {
showVersion();
} else {
showHelp();
}
| fabiosantoscode/animees | index.js | JavaScript | mit | 4,698 |
var Todo = React.createClass({displayName: "Todo",
getInitialState: function() {
this.text = "";
return {text: ""};
},
componentWillUnmount: function() {
this.ref.off();
},
componentWillMount: function() {
this.ref = new Firebase("https://glaring-fire-5349.firebaseio.com/react_todos/" + this.props.todoKey);
// Update the todo's text when it changes.
this.ref.on("value", function(snap) {
if (snap.val() !== null) {
this.text = snap.val().text;
this.setState({
text: this.text
});
} else {
this.ref.update({
text: ""
});
}
}.bind(this));
},
onTextBlur: function(event) {
this.ref.update({
text: $(event.target).text()
});
},
render: function() {
return (
React.createElement("li", {id: this.props.todoKey, className: "list-group-item todo"},
React.createElement("a", {href: "#", className: "pull-left todo-check"},
React.createElement("span", {
className: "todo-check-mark glyphicon glyphicon-ok",
"aria-hidden": "true"}
)
),
React.createElement("span", {
onBlur: this.onTextBlur,
contentEditable: "true",
"data-ph": "Todo",
className: "todo-text"},
this.state.text
)
)
);
}
});
var TodoList = React.createClass({displayName: "TodoList",
getInitialState: function() {
this.todos = [];
return {todos: []};
},
componentWillMount: function() {
this.ref = new Firebase("https://glaring-fire-5349.firebaseio.com/react_todos/");
// Add an empty todo if none currently exist.
this.ref.on("value", function(snap) {
if (snap.val() === null) {
this.ref.push({
text: "",
checked: false,
});
}
}.bind(this));
// Add an added child to this.todos.
this.ref.on("child_added", function(childSnap) {
this.todos.push({
k: childSnap.key(),
val: childSnap.val()
});
this.setState({
todos: this.todos
});
}.bind(this));
this.ref.on("child_removed", function(childSnap) {
var key = childSnap.key();
var i;
for (i = 0; i < this.todos.length; i++) {
if (this.todos[i].k == key) {
break;
}
}
this.todos.splice(i, 1);
this.setState({
todos: this.todos
});
}.bind(this));
},
componentWillUnmount: function() {
this.ref.off();
},
render: function() {
var todos = this.state.todos.map(function (todo) {
return (
React.createElement(Todo, {todoKey: todo.k})
);
});
return (
React.createElement("div", null,
React.createElement("h1", {id: "list_title"}, this.props.title),
React.createElement("ul", {id: "todo-list", className: "list-group"},
todos
)
)
);
}
});
var ListPage = React.createClass({displayName: "ListPage",
render: function() {
return (
React.createElement("div", null,
React.createElement("div", {id: "list_page"},
React.createElement("a", {href: "?", id: "lists_link", className: "btn btn-primary"}, "Back to Lists")
),
React.createElement("div", {className: "page-header"},
this.props.children
)
)
);
}
});
var App = React.createClass({displayName: "App",
render: function() {
React.createElement("div", null,
React.createElement(Nav, null),
this.page
)
}
});
React.render(
React.createElement(ListPage, null,
React.createElement(TodoList, {todoListKey: "asdf", title: "hi", todos: []})
),
document.getElementById('content')
); | jasharpe/firebase-react-todo | build/.module-cache/30d7668d5e8244c1fc1ea063e85b2358f994e517.js | JavaScript | mit | 3,764 |
/**
* Custom application error
*/
module.exports = class APIError extends Error {
/**
* Instantiates a new APIError
* @param {Number} status The HTML status code
* @param {String} message The error description
* @param {Mixed} details Any other relative information
*/
constructor(module, status, message, details) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
this.module = module;
this.message = message;
this.status = status;
this.details = details;
}
toJSON() {
return {
status : this.status,
message: this.message,
details: this.details
};
}
};
| buckless-team/server | src/errors/APIError.js | JavaScript | mit | 768 |
version https://git-lfs.github.com/spec/v1
oid sha256:6c3d760745e486e8302ca3521f38c6bddace0554973d90e7aa504f6e4d227e8d
size 5153
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.15.0/series-combospline-stacked/series-combospline-stacked-coverage.js | JavaScript | mit | 129 |
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// schema
var userSchema = mongoose.Schema({
profile : {
name : {
first : String,
last : String
},
age : Number
},
local : {
email : String,
username : String,
password : String
},
facebook : {
id : String,
token : String,
email : String,
name : String
},
twitter : {
id : String,
token : String,
displayName : String,
username : String
},
google : {
id : String,
token : String,
email : String,
name : String
},
when : {
deletedOn : Date,
createdOn : {
type : Date,
default : Date.now
},
updatedOn : {
type : Date,
default : Date.now
}
}
});
// export
module.exports = mongoose.model('User', userSchema);
// create: hash
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// check: password for validity
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
| lalithmuthali/bootstrap-nodejs-console | console/models/user.js | JavaScript | mit | 1,103 |
import React from 'react';
import RouterHookContext from './RouterHookContext';
import RouterHookContainer from './RouterHookContainer';
function noop() {}
export default function useRouterHook(options) {
let container = null;
const {
locals = {},
onAborted = noop,
onCompleted = noop,
onError = noop,
onStarted = noop,
routerDidEnterHooks = [],
routerWillEnterHooks = [],
} = options;
return {
renderRouterContext: (child, renderProps) => {
const {
components,
location,
} = renderProps;
return (
<RouterHookContext
components={components}
location={location}
onAborted={onAborted}
onCompleted={onCompleted}
onError={onError}
onStarted={onStarted}
>
{child}
</RouterHookContext>
);
},
renderRouteComponent: (child, renderProps) => {
if (!child) {
return null;
}
if (!container) {
container = (
<RouterHookContainer
locals={locals}
renderProps={renderProps}
routerDidEnterHooks={routerDidEnterHooks}
routerWillEnterHooks={routerWillEnterHooks}
>
{child}
</RouterHookContainer>
);
return container;
}
return React.cloneElement(container, {
locals,
renderProps,
routerDidEnterHooks,
routerWillEnterHooks,
}, child);
},
};
}
| kouhin/react-router-hook | src/useRouterHook.js | JavaScript | mit | 1,502 |
(function() {
'use strict';
var pgp = require('pg-promise')();
var _ = require('underscore');
var util = require('./swimtrack-util');
var yearParser = require('./tdsystem/year-parser');
var meetParser = require('./tdsystem/meet-parser');
var raceParser = require('./tdsystem/result-parser-2008');
var getRecords = function(db, tableName, funcKey) {
return new Promise(function(resolve, reject) {
db.any('SELECT * FROM ' + tableName)
.then(function(rows) {
let ret = {};
ret.map = {};
ret.maxId = -1;
for (const row of rows) {
if (funcKey) {
ret.map[funcKey(row)] = row;
}
if (ret.maxId < row.id) {
ret.maxId = row.id;
}
}
return resolve(ret);
})
.catch(function(err) {
return reject(err);
});
});
};
var getName = function(obj) {
if (!obj) {
return '';
}
return obj.name;
};
var getEventKey = function(eventObj) {
return eventObj.sex + ':' + eventObj.distance + ':' + eventObj.style + ':' + eventObj.age;
};
var getRaceKey = function(raceObj) {
return raceObj.meet_id + ':' + raceObj.event_id;
};
/**
* Main process
*/
const YEAR_TOP_PAGES = [{
year: 2017,
url: 'http://www.tdsystem.co.jp/i2017.htm',
path: 'www.tdsystem.co.jp/i2017.htm'
}, {
year: 2016,
url: 'http://www.tdsystem.co.jp/i2016.htm',
path: 'www.tdsystem.co.jp/i2016.htm'
}, {
year: 2015,
url: 'http://www.tdsystem.co.jp/i2015.htm',
path: 'www.tdsystem.co.jp/i2015.htm'
}, {
year: 2014,
url: 'http://www.tdsystem.co.jp/i2014.htm',
path: 'www.tdsystem.co.jp/i2014.htm'
}, {
year: 2013,
url: 'http://www.tdsystem.co.jp/i2013.htm',
path: 'www.tdsystem.co.jp/i2013.htm'
}, {
year: 2012,
url: 'http://www.tdsystem.co.jp/i2012.htm',
path: 'www.tdsystem.co.jp/i2012.htm'
}, {
year: 2011,
url: 'http://www.tdsystem.co.jp/i2011.htm',
path: 'www.tdsystem.co.jp/i2011.htm'
}, {
year: 2010,
url: 'http://www.tdsystem.co.jp/i2010.htm',
path: 'www.tdsystem.co.jp/i2010.htm'
}, {
year: 2009,
url: 'http://www.tdsystem.co.jp/i2009.htm',
path: 'www.tdsystem.co.jp/i2009.htm'
}, {
year: 2008,
url: 'http://www.tdsystem.co.jp/i2008.htm',
path: 'www.tdsystem.co.jp/i2008.htm'
}];
let db = pgp({
host: process.env.PGHOST,
port: process.env.PGPORT,
database: process.env.PGDATABASE,
user: process.env.PGUSER,
password: process.env.PGPASSWORD
});
Promise.all([
getRecords(db, 'venues', getName),
getRecords(db, 'meets', getName),
getRecords(db, 'events', getEventKey),
getRecords(db, 'players', getName),
getRecords(db, 'teams', getName),
getRecords(db, 'races'),
getRecords(db, 'results')
])
.then(function(values) {
let venues = values[0].map;
let venueMaxId = values[0].maxId;
let meets = values[1].map;
let meetMaxId = values[1].maxId;
let events = values[2].map;
let eventMaxId = values[2].maxId;
let playerMaxId = values[3].maxId;
let teams = values[4].map;
let teamMaxId = values[4].maxId;
let raceMaxId = values[5].maxId;
let resultMaxId = values[6].maxId;
//
// Process each year index page
//
for (const yearIndex in YEAR_TOP_PAGES) {
const yearTopPage = YEAR_TOP_PAGES[yearIndex];
console.log('Parse ' + yearTopPage.year);
try {
let $ = util.parseLocalHtml(yearTopPage.path);
let yearParseResult = yearParser.parsePage(yearTopPage.year, $);
let meetsInYear = yearParseResult.meets;
if (!meetsInYear) {
console.log('No meet found.');
continue;
}
console.log(meetsInYear.length + ' meets found.');
//
// Process meets
//
for (let meet of meetsInYear) {
if (!meet.name || meets[meet.name]) { // No name or already in DB
continue;
}
console.log('Process ' + meet.name);
let races = {};
let results = [];
let players = {};
let playerResults = [];
//
// Define meet id
//
meet.id = ++meetMaxId;
//
// Define venue id
//
if (!meet.venue) {
console.log('Skipped by invalid venue info: name = ' + meet.name);
continue;
}
if (venues[meet.venue.name]) {
meet.venue.id = venues[meet.venue.name].id;
} else {
meet.venue.id = ++venueMaxId;
venues[meet.venue.name] = {
id: meet.venue.id,
name: meet.venue.name,
city: meet.venue.city
};
}
const meetPagePath = yearTopPage.path.substring(0, yearTopPage.path.lastIndexOf('/') + 1) + meet.url;
meets[meet.name] = {
id: meet.id,
name: meet.name,
start_date: meet.days[0],
dates: meet.days,
venue_id: meet.venue.id,
course: meet.venue.course,
url: 'http://' + meetPagePath
};
//
// Parse meet page (PRO.HTM)
//
if (!meet.url) {
continue;
}
try {
let meetParseResult = meetParser.parsePage(util.parseLocalHtml(meetPagePath));
for (let race of meetParseResult.races) {
let eventKey = getEventKey(race);
if (events[eventKey]) {
race.eventId = events[eventKey].id;
} else {
race.eventId = ++eventMaxId;
events[eventKey] = {
id: race.eventId,
sex: race.sex,
distance: race.distance,
style: race.style,
age: race.age,
relay: race.relay
};
}
//
// Define race id and generate a record for race table
//
const racePagePath = meetPagePath.substring(0, meetPagePath.lastIndexOf('/') + 1) + race.page;
let raceObj = {
meet_id: meet.id,
event_id: race.eventId,
url: 'http://' + racePagePath
};
let raceKey = getRaceKey(raceObj);
if (races[raceKey]) {
console.error('WARNING: Duplicated race keys: meet page = ' + meetPagePath + ', event = ' + eventKey);
race.id = races[raceKey].id;
} else {
race.id = ++raceMaxId;
raceObj.id = race.id;
races[raceKey] = raceObj;
}
//
// Parse race page (###.HTM)
//
try {
let raceParseResult = raceParser.parseDocument(util.parseLocalHtml(racePagePath));
for (let result of raceParseResult.results) {
result.id = ++resultMaxId;
results.push({
id: result.id,
race_id: race.id,
rank: result.rank,
record: result.record
});
if (players[result.player]) {
result.playerId = players[result.player].id;
} else {
result.playerId = ++playerMaxId;
}
if (teams[result.team]) {
result.teamId = teams[result.team].id;
} else {
result.teamId = ++teamMaxId;
teams[result.team] = {
id: result.teamId,
name: result.team
};
}
playerResults.push({
player_id: result.playerId,
result_id: result.id
});
players[result.player] = {
id: result.playerId,
name: result.player,
team_id: result.teamId,
meet_id: meet.id
};
}
} catch (err) {
console.error('Failed to parse race page: ' + racePagePath);
console.error(err.stack);
continue;
}
}
//
// Insert
//
if (results.length === 0) {
continue;
}
let raceCS = new pgp.helpers.ColumnSet(['id', 'meet_id', 'event_id', 'url'], {
table: 'races'
});
let resultCS = new pgp.helpers.ColumnSet(['id', 'race_id', 'rank', 'record'], {
table: 'results'
});
let playerResultCS = new pgp.helpers.ColumnSet(['player_id', 'result_id'], {
table: 'player_result'
});
let playerCS = new pgp.helpers.ColumnSet([
'id',
'name',
'team_id',
'meet_id'
], {
table: 'players'
});
//
// Insert players
//
db.tx(function(t) {
return this.none(pgp.helpers.insert(_.values(players), playerCS));
})
.then(data => {
console.log('Succeed to insert players');
})
.catch(err => {
console.error('Failed to insert players');
console.error(err.stack);
});
let raceValues = _.values(races);
db.tx(function(t) {
return this.batch([
this.none(pgp.helpers.insert(raceValues, raceCS)),
this.none(pgp.helpers.insert(results, resultCS)),
this.none(pgp.helpers.insert(playerResults, playerResultCS))
]);
})
.then(data => {
console.log('Succeed to insert races and results: ' + meetPagePath);
})
.catch(err => {
console.error('Failed to insert races and results: ' + meetPagePath);
console.error(err.stack);
});
} catch (err) {
console.error('Failed to parse meet page: ' + meetPagePath);
console.error(err.stack);
continue;
}
}
} catch (err) {
console.error('Failed to parse year top page: ' + yearTopPage);
console.error(err.stack);
continue;
}
}
//
// Insert venues
//
db.tx(function(t) {
return this.none(pgp.helpers.insert(
_.values(venues),
new pgp.helpers.ColumnSet(['id', 'name', 'city'], {
table: 'venues'
})));
})
.then(data => {
console.log('Succeed to insert venues');
})
.catch(err => {
console.error('Failed to insert venues');
console.error(err.stack);
});
//
// Insert meets
//
db.tx(function(t) {
return this.none(pgp.helpers.insert(
_.values(meets),
new pgp.helpers.ColumnSet([
'id',
'name',
'start_date', {
name: 'dates',
cast: 'date[]'
},
'venue_id',
'course',
'url'
], {
table: 'meets'
})));
})
.then(data => {
console.log('Succeed to insert meets');
})
.catch(err => {
console.error('Failed to insert meets');
console.error(err.stack);
});
//
// Insert events
//
db.tx(function(t) {
return this.none(pgp.helpers.insert(
_.values(events),
new pgp.helpers.ColumnSet([
'id',
'sex',
'distance',
'style',
'age',
'relay'
], {
table: 'events'
})));
})
.then(data => {
console.log('Succeed to insert events');
})
.catch(err => {
console.error('Failed to insert events');
console.error(err.stack);
});
//
// Insert teams
//
db.tx(function(t) {
return this.none(pgp.helpers.insert(
_.values(teams),
new pgp.helpers.ColumnSet([
'id',
'name'
], {
table: 'teams'
})));
})
.then(data => {
console.log('Succeed to insert teams');
})
.catch(err => {
console.error('Failed to insert teams');
console.error(err.stack);
});
})
.catch(function(err) {
console.error(err.stack);
});
}());
| chopstickexe/swimtrack | db/js/parse-local-year-pages.js | JavaScript | mit | 13,498 |
// @flow
import SimpleChanMsgPlugin from 'plugins/SimpleChanMsgPlugin';
import Norbert from 'lib/Norbert';
export default class HelpPlugin extends SimpleChanMsgPlugin {
meta:{
prefix: string,
version: string,
name: string
};
helpData:{
__commands: {
[K:string]: string
},
[plugin:string] : {
overview: string,
commands?: {
[K:string]: string
}
}
};
init(norbert:Norbert) {
super.init(norbert);
this.helpData = norbert.helpData;
this.meta = norbert.meta;
}
getName() {
return "Help";
}
getHelp() {
return {
overview: "Help and Hello Plugin",
commands: {
commands: "show a list of available _commands.",
hello: "say hello to the world.",
help: "tell you everything I know about a specific command."
}
}
}
specificCommandHelp(channel:string, sender:string, message:string, norbert:Norbert) {
const command = message.trim();
if(!command) {
return this.help(channel,sender,message,norbert);
}
if(!this.helpData['__commands'].hasOwnProperty(command)) {
norbert.client.say(channel, `I don't know anything about a command named ${message}.`);
return;
}
const msg = `${this.meta.prefix}${command}: ${this.helpData['__commands'][command]}`;
norbert.client.say(channel, msg);
}
getCommands() {
return {
'commands': this.commands,
'hello': this.help,
'help': this.specificCommandHelp,
'plugin': this.plugin,
'plugins': this.plugins
}
}
plugins(channel:string, sender:string, message:string, norbert:Norbert) {
const _plugins = {};
Object.assign(_plugins, this.helpData);
delete _plugins['__commands'];
const pluginsN = Object.keys(_plugins).length;
const pluginsS = Object.keys(_plugins).join(', ');
const msg = `${pluginsN} available: (${pluginsS}). For more information use the ${this.meta.prefix}plugin command.`
norbert.client.say(channel, msg);
}
plugin(channel:string, sender:string, message:string, norbert:Norbert) {
const _plugins = {};
Object.assign(_plugins, this.helpData);
delete _plugins['__commands'];
if(!_plugins.hasOwnProperty(message.trim())) {
norbert.client.say(channel, `I don't know anything about ${message}`);
return;
}
const plugin = _plugins[message.trim()].overview;
const msg = `${message.trim()} - ${plugin}`;
norbert.client.say(channel, msg);
}
commands(channel:string, sender:string, message:string, norbert:Norbert) {
const commandsN = Object.keys(this.helpData['__commands']).length;
const commandsS = Object.keys(this.helpData['__commands']).join(', ');
const msg = `${commandsN} available: (${commandsS}). For more information use ${this.meta.prefix}help command.`
norbert.client.say(channel, msg);
}
help(channel:string, sender:string, message:string, norbert:Norbert) {
const pluginN = Object.keys(this.helpData).length - 1;
const commandsN = Object.keys(this.helpData['__commands']).length;
const msg = `Hello! Currently running version ${this.meta.version} of ${this.meta.name} with ${pluginN} plugins loaded for a total`
+ ` of ${commandsN} commands. ${this.meta.prefix}plugins or ${this.meta.prefix}commands for more information.`
+ ` Contribute! https://github.com/EdwardDrapkin/norbert-bot`;
norbert.client.say(channel, msg);
}
} | EdwardDrapkin/norbert-bot | src/plugins/HelpPlugin.js | JavaScript | mit | 3,829 |
import React from 'react'
import PropTypes from 'prop-types'
import Circle from './circle'
const DragMarker = ({ type }) => {
const [color, shadow, opacity] = (() => {
switch (type) {
case 'can-drop': return ['red', '0px 0px 7px red', 1]
case 'can-drop-over': return ['red', '0px 0px 10px blue', 1]
case 'can-drop-hint': return ['blue', '0px 0px 10px blue', 1]
case 'is-move-possible': return ['red', '0px 0px 6px red', 0.3]
default: throw Error('What is your drag marker type?')
}
})()
if (!color || !shadow || !opacity) return null
return (
<div style={{ opacity }}>
<Circle color={color} shadow={shadow}>
<div style={{ margin: '10%' }}>
<Circle color='orange' blur='3px' />
</div>
</Circle>
</div>
)
}
export default DragMarker
DragMarker.propTypes = {
type: PropTypes.string.isRequired
}
| koscelansky/Dama | src/features/board/drag-marker.js | JavaScript | mit | 893 |
import "./styles.css";
import React from "react";
import {
TransitionGroup,
CSSTransition
} from "react-transition-group";
import {
BrowserRouter as Router,
Switch,
Route,
Link,
Redirect,
useLocation,
useParams
} from "react-router-dom";
export default function AnimationExample() {
return (
<Router>
<Switch>
<Route exact path="/">
<Redirect to="/hsl/10/90/50" />
</Route>
<Route path="*">
<AnimationApp />
</Route>
</Switch>
</Router>
);
}
function AnimationApp() {
let location = useLocation();
return (
<div style={styles.fill}>
<ul style={styles.nav}>
<NavLink to="/hsl/10/90/50">Red</NavLink>
<NavLink to="/hsl/120/100/40">Green</NavLink>
<NavLink to="/rgb/33/150/243">Blue</NavLink>
<NavLink to="/rgb/240/98/146">Pink</NavLink>
</ul>
<div style={styles.content}>
<TransitionGroup>
{/*
This is no different than other usage of
<CSSTransition>, just make sure to pass
`location` to `Switch` so it can match
the old location as it animates out.
*/}
<CSSTransition
key={location.pathname}
classNames="fade"
timeout={300}
>
<Switch location={location}>
<Route path="/hsl/:h/:s/:l" children={<HSL />} />
<Route path="/rgb/:r/:g/:b" children={<RGB />} />
</Switch>
</CSSTransition>
</TransitionGroup>
</div>
</div>
);
}
function NavLink(props) {
return (
<li style={styles.navItem}>
<Link {...props} style={{ color: "inherit" }} />
</li>
);
}
function HSL() {
let { h, s, l } = useParams();
return (
<div
style={{
...styles.fill,
...styles.hsl,
background: `hsl(${h}, ${s}%, ${l}%)`
}}
>
hsl({h}, {s}%, {l}%)
</div>
);
}
function RGB() {
let { r, g, b } = useParams();
return (
<div
style={{
...styles.fill,
...styles.rgb,
background: `rgb(${r}, ${g}, ${b})`
}}
>
rgb({r}, {g}, {b})
</div>
);
}
const styles = {};
styles.fill = {
position: "absolute",
left: 0,
right: 0,
top: 0,
bottom: 0
};
styles.content = {
...styles.fill,
top: "40px",
textAlign: "center"
};
styles.nav = {
padding: 0,
margin: 0,
position: "absolute",
top: 0,
height: "40px",
width: "100%",
display: "flex"
};
styles.navItem = {
textAlign: "center",
flex: 1,
listStyleType: "none",
padding: "10px"
};
styles.hsl = {
...styles.fill,
color: "white",
paddingTop: "20px",
fontSize: "30px"
};
styles.rgb = {
...styles.fill,
color: "white",
paddingTop: "20px",
fontSize: "30px"
};
| ReactTraining/react-router | packages/react-router-dom/examples/Animation/index.js | JavaScript | mit | 2,821 |
function init(shipit) {
require('@tryghost/deploy')(shipit);
shipit.initConfig({
default: {
yarn: true,
workspace: './',
deployTo: '/opt/gscan/',
ignores: ['.git', '.gitkeep', '.gitignore', '.eslintrc.js', '.eslintcache', 'node_modules', '/test', '/app/public/.eslintrc.js']
},
staging: {
servers: process.env.STG_USER + '@' + process.env.STG_SERVER,
sharedLinks: [{
name: 'node_modules',
type: 'directory'
}, {
name: 'uploads',
type: 'directory'
}, {
name: 'config.staging.json',
type: 'file'
}]
},
production: {
servers: process.env.PRD_USER + '@' + process.env.PRD_SERVER,
sharedLinks: [{
name: 'node_modules',
type: 'directory'
}, {
name: 'uploads',
type: 'directory'
}, {
name: 'config.production.json',
type: 'file'
}]
}
});
}
module.exports = init;
| EdwardStudy/myghostblog | versions/1.25.7/node_modules/gscan/shipitfile.js | JavaScript | mit | 1,177 |
var express = require('express');
var bodyParser = require('body-parser');
var grabber = require('./grabber');
var app = express();
app.use(bodyParser.json());
app.get('/', function(req, res) {
res.sendFile('/index.html', {root: __dirname })
});
app.post('/grab', function(req, res) {
grabber(req.body, function(data) {
//console.log(data);
res.send(data);
});
});
app.listen(process.env.PORT || 3000);
| prathamesh7pute/data-grabber | server.js | JavaScript | mit | 437 |
export type postcss$comment = {
text: string,
source: {
start: {
line: number,
column: number,
},
end: {
line: number,
column: number,
},
},
error(message: string, options: { plugin: string }): void,
}
| gaidarenko/stylelint | decls/postcss.js | JavaScript | mit | 250 |
import _ from 'lodash';
import { FETCH_POSTS, FETCH_POST, DELETE_POST } from '../actions';
export default function(state = {}, action) {
switch(action.type) {
case DELETE_POST:
return _.omit(state,action.payload)
case FETCH_POST:
//ES5 way
//const post = action.payload.data;
//const newState = { ...state}
//newState[post.id] = post;
//return newState;
return {...state, [action.payload.data.id]:action.payload.data };
case FETCH_POSTS:
//console.log(action.payload.data); // this will spit out an array
//transform into object
return _.mapKeys(action.payload.data, 'id');
default:
return state;
}
}
| murielg/react-redux | blog/src/reducers/reducer_posts.js | JavaScript | mit | 693 |
/**
@name config module
@description gets configurations from ndjs file according to the current installer stage. parses templates through the state module
**/
'use strict';
module.exports=createModule;
createModule.moduleName='$config';
createModule.$inject=['$backend','$state'];
var _ =require('lodash');
var path =require('path');
function createModule($backend,$state)
{
var installerStage='install';
var config={};
// loads the config object above
require($backend.getConfigPath())(getLoadingInterface());
var configModule={};
configModule.getConfig=getConfig;
configModule.getOutgoingDir=getOutgoingDir;
configModule.getInstallerStage=getInstallerStage;
return configModule;
/**
* @name getInstallerStage
* @return current installer stage ('install', 'uninstall' etc...)
**/
function getInstallerStage()
{
return installerStage;
}
function cloneDeepAndParse(val)
{
if(_.isPlainObject(val))
{
return _.mapValues(val,cloneDeepAndParse);
}
else if(_.isArray(val))
{
return _.map(val,cloneDeepAndParse);
}
else if (_.isString(val)) {
return parseStateStrings(val);
}
return val;
}
function parseStateStrings(val)
{
var parsed=$state.parseTemplate(val);
if(parsed!==val)
{
return parseStateStrings(parsed);
}
return val;
}
/**
* @name getConfig
* @param path {String} property path
* @return parsed value of the property if found
* @example getConfig('pages[2]') will return the 3rd page in the current install stage
**/
function getConfig(path)
{
return cloneDeepAndParse(_.get(config[installerStage],path));
}
/**
* @name getOutgoingDir
* @return outgoing dir (should not be used on production)
**/
function getOutgoingDir()
{
return path.resolve(config.options.outgoing);
}
function getLoadingInterface()
{
return {
initConfig:function(v){config=v;}
};
}
}
| asafamr/nd-node | src/core-modules/config/config.js | JavaScript | mit | 1,929 |
import {inject, customElement, bindable} from 'aurelia-framework';
import $ from 'jquery';
import 'Eonasdan/bootstrap-datetimepicker';
import 'Eonasdan/bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.css!';
import moment from 'moment';
@customElement('datepicker')
@inject(Element)
export class Datepicker {
@bindable value = null;
@bindable options = null;
@bindable disabled = false;
constructor(element) {
this.element = element;
}
bind() {
const defaultOpts = {
collapse: false,
useCurrent: false,
calendarWeeks: true,
locale: moment.locale(),
format: 'L'
};
var div = this.element.firstElementChild;
this.$element = $(div);
this.options = this.options || {};
if (this.options.format !== undefined) {
delete this.options.format;
}
this.options = $.extend({}, defaultOpts, this.options);
this.datepicker = this.$element.datetimepicker(this.options);
var self = this;
this.datepicker.on('dp.change', (event) => {
this.value = event.date;
//Find better way to invoke observable before function!!!
setTimeout(function () {
self.element.dispatchEvent(new Event("change"));
});
});
this.valueChanged(this.value);
}
valueChanged(newValue, oldValue) {
if (newValue === undefined) {
throw new Error('Do not use undefined!');
}
if (newValue === null) {
var input = this.element.firstElementChild.firstElementChild;
input.value = '';
return;
}
// check if date is valid and moment object
if (newValue.isValid() !== true) {
throw new Error('This has to be moment type!');
}
if (newValue.isSame(oldValue)) {
return;
}
this.$element.data('DateTimePicker').date(newValue);
}
}
| lubo-gadjev/aurelia-custom-common-files | src/custom-elements/datepicker/datepicker.js | JavaScript | mit | 1,812 |
'use strict';
// Altere o protótipo de Number para adicionar potencia
// e raiz quadrada;
Number.prototype.sqrt = function() {
return Math.sqrt(this);
}
console.log(new Number(144.0).sqrt());
| opensanca/trilha-javascript | 01.JavaScript/aula-05/exercicio-03.js | JavaScript | mit | 198 |
"use strict";
const AWS = require("aws-sdk");
const s3 = new AWS.S3();
const DELIM = "\n";
const bucketParams = {
Bucket: process.env.BUCKET,
Key: "unfollower_ids.txt",
};
const setFollowers = async (followerIDs = []) => {
console.log(`Saving ${followerIDs.length} follower IDs to S3`);
const Body = followerIDs.join(DELIM);
try {
await s3.putObject({ ...bucketParams, Body }).promise();
} catch (e) {
console.log("Error writing to S3:", e);
}
};
const getFollowers = async () => {
try {
const { Body } = await s3.getObject(bucketParams).promise();
const followers = Body ? Body.toString("utf-8").split(DELIM) : [];
console.log(`Previous followers: ${followers && followers.length}`);
return followers;
} catch (e) {
console.log("Error reading from S3:", e);
return [];
}
};
module.exports = { setFollowers, getFollowers };
| david-crespo/unfollowers | src/s3.js | JavaScript | mit | 882 |
import mongoose, { Schema } from 'mongoose';
// PHOTO SCHEMA
const photoSchema = new Schema({
public_id: {
type: String,
lowercase: true,
unique: true,
},
thumbnail_url: String,
url: String
}, { timestamps: true });
// PHOTO MODEL
const Photo = mongoose.model('photos', photoSchema);
export default Photo;
| rockchalkwushock/photography-backend | api/modules/Photo/model.js | JavaScript | mit | 329 |
"use strict";
const jsdom = require("../..");
exports["new DOMImplementation() is not allowed"] = t => {
const DOMImplementation = jsdom.jsdom().defaultView.DOMImplementation;
t.throws(() => new DOMImplementation(), /Illegal constructor/i);
t.done();
};
exports["create an empty document"] = t => {
const implementation = jsdom.jsdom().implementation;
const document = implementation.createDocument(null, null, null);
t.equal(document.childNodes.length, 0, "document should not contain any nodes");
t.done();
};
exports["doctype ownerDocument"] = t => {
const document = jsdom.jsdom();
const doctype = document.implementation.createDocumentType("bananas");
t.ok(doctype.ownerDocument === document, "doctype should belong to the document the implementation belongs to");
const newDocument = document.implementation.createDocument(null, null, doctype);
t.ok(doctype.ownerDocument === newDocument, "doctype should belong to the new document");
t.done();
};
exports["doctype child of ownerDocument"] = t => {
const document = jsdom.jsdom();
const doctype = document.implementation.createDocumentType("hatstand");
const newDocument = document.implementation.createDocument(null, null, doctype);
t.ok(newDocument.firstChild === doctype, "doctype should be a child of the document");
t.done();
};
exports["defaultView should be null"] = t => {
const document = jsdom.jsdom();
const newDocument = document.implementation.createDocument(null, null, null);
t.strictEqual(newDocument.defaultView, null, "defaultView should be null");
t.done();
};
exports["location should be null"] = t => {
const document = jsdom.jsdom();
const newDocument = document.implementation.createHTMLDocument();
t.strictEqual(newDocument.location, null, "location should be null");
t.done();
};
exports["setting proxied event handlers on the body should have no effect"] = t => {
const document = jsdom.jsdom();
const newDocument = document.implementation.createHTMLDocument();
const proxiedEventHandlers = ["onafterprint", "onbeforeprint", "onbeforeunload", "onblur", "onerror", "onfocus",
"onhashchange", "onload", "onmessage", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate",
"onresize", "onscroll", "onstorage", "onunload"];
for (const name of proxiedEventHandlers) {
newDocument.body[name] = "1 + 2";
t.strictEqual(newDocument.body[name], null, name + " should always be null because there is no window");
}
t.done();
};
exports["iframe added to a created Document should not load"] = t => {
const document = jsdom.jsdom();
const newDocument = document.implementation.createHTMLDocument();
const iframe = newDocument.createElement("iframe");
// iframe's with a name are added as a property to the window, this line is added to see if things crash
iframe.setAttribute("name", "foobar");
newDocument.body.appendChild(iframe);
t.strictEqual(iframe.contentWindow, null, "contentWindow should be null, the iframe should never load");
t.strictEqual(iframe.contentDocument, null, "contentDocument should be null, the iframe should never load");
iframe.src = "http://example.com/"; // try to trigger a load action
t.strictEqual(iframe.contentWindow, null, "contentWindow should be null, the iframe should never load");
t.strictEqual(iframe.contentDocument, null, "contentDocument should be null, the iframe should never load");
t.done();
};
| jeffcarp/jsdom | test/living-dom/dom-implementation.js | JavaScript | mit | 3,441 |
import React from 'react';
import {
createRendererWithUniDriver,
createRendererWithDriver,
cleanup,
} from '../../../test/utils/unit';
import BaseModalLayout from '../index';
import { baseModalLayoutPrivateDriverFactory } from './BaseModalLayout.private.uni.driver';
import { baseModalLayoutDriverFactory } from '../BaseModalLayout.legacy.driver';
import Text from '../../Text';
describe('BaseModalLayout', () => {
describe('[sync]', () => {
runTests(createRendererWithDriver(baseModalLayoutDriverFactory));
});
describe('[async]', () => {
runTests(createRendererWithUniDriver(baseModalLayoutPrivateDriverFactory));
});
function runTests(render) {
afterEach(() => cleanup());
it('should render', async () => {
const { driver } = render(<BaseModalLayout />);
expect(await driver.exists()).toBe(true);
});
it('should render children', async () => {
const children = <div data-hook="child">Child</div>;
const { driver } = render(<BaseModalLayout>{children}</BaseModalLayout>);
expect(await driver.childExists('child')).toBe(true);
});
it('should receive class name', async () => {
const expectedClass = 'classy';
const { driver } = render(<BaseModalLayout className={expectedClass} />);
expect(await driver._hasClass(expectedClass)).toBe(true);
});
it('should not render the close button when no `onCloseButtonClick` provided', async () => {
const { driver } = render(<BaseModalLayout />);
expect(await driver._closeButtonExists()).toBe(false);
});
it('should render the close button', async () => {
const { driver } = render(
<BaseModalLayout onCloseButtonClick={() => {}} />,
);
expect(await driver._closeButtonExists()).toBe(true);
});
it('should click on the close button', async () => {
const onCloseButtonClickSpy = jest.fn();
const { driver } = render(
<BaseModalLayout onCloseButtonClick={onCloseButtonClickSpy}>
Content
</BaseModalLayout>,
);
await driver.clickCloseButton();
expect(onCloseButtonClickSpy).toHaveBeenCalledTimes(1);
});
it('should not render the help button when no `onHelpButtonClick` provided', async () => {
const { driver } = render(<BaseModalLayout />);
expect(await driver._helpButtonExists()).toBe(false);
});
it('should render the help button', async () => {
const { driver } = render(
<BaseModalLayout onHelpButtonClick={() => {}} />,
);
expect(await driver._helpButtonExists()).toBe(true);
});
it('should click on the help button', async () => {
const onHelpButtonClickSpy = jest.fn();
const { driver } = render(
<BaseModalLayout onHelpButtonClick={onHelpButtonClickSpy}>
Content
</BaseModalLayout>,
);
await driver.clickHelpButton();
expect(onHelpButtonClickSpy).toHaveBeenCalledTimes(1);
});
it('should set the layout `theme`', async () => {
const theme = 'premium';
const { driver } = render(<BaseModalLayout theme={theme} />);
expect(await driver.getTheme()).toBe(theme);
});
it('should override the props of internal components that use the context consumer', async () => {
const theRightTitle = 'The right title';
const { driver } = render(
<BaseModalLayout title={theRightTitle}>
<BaseModalLayout.Header title={'The wrong title'} />
</BaseModalLayout>,
);
expect(await driver.getTitleText()).toEqual(theRightTitle);
});
/* Testing the BaseModalLayout Blocks here */
describe('Layout Blocks', () => {
describe('Header', () => {
it('should not render the header when `title` and `subtitle` are not provided', async () => {
const { driver } = render(
<BaseModalLayout>
<BaseModalLayout.Header dataHook={'header'} />
</BaseModalLayout>,
);
expect(await driver.childExists('header')).toBe(false);
});
it('should render the header when `title` is provided', async () => {
const { driver } = render(
<BaseModalLayout title={'title'}>
<BaseModalLayout.Header dataHook={'header'} />
</BaseModalLayout>,
);
expect(await driver.childExists('header')).toBe(true);
});
it('should render the provided `title` text', async () => {
const title = 'Modal Title';
const { driver } = render(
<BaseModalLayout title={title}>
<BaseModalLayout.Header />
</BaseModalLayout>,
);
expect(await driver.getTitleText()).toEqual(title);
});
it('should render the provided `title` node', async () => {
const titleNode = <div data-hook={'title'}>Title Text</div>;
const { driver } = render(
<BaseModalLayout title={titleNode}>
<BaseModalLayout.Header />
</BaseModalLayout>,
);
expect(await driver.childExists('title')).toBe(true);
});
it('should render the header when `subtitle` is provided', async () => {
const { driver } = render(
<BaseModalLayout subtitle={'subtitle'}>
<BaseModalLayout.Header dataHook={'header'} />
</BaseModalLayout>,
);
expect(await driver.childExists('header')).toBe(true);
});
it('should render `subtitle` text', async () => {
const subtitle = 'Subtitle here';
const { driver } = render(
<BaseModalLayout subtitle={subtitle}>
<BaseModalLayout.Header />
</BaseModalLayout>,
);
expect(await driver.getSubtitleText()).toEqual(subtitle);
});
});
describe('Content', () => {
it('should render the content with the provided `content` prop', async () => {
const contentNode = <div data-hook="content">Content Text</div>;
const { driver } = render(
<BaseModalLayout content={contentNode}>
<BaseModalLayout.Content />
</BaseModalLayout>,
);
expect(await driver.childExists('content')).toBe(true);
});
it('should render the content with the provided `children`', async () => {
const contentText = 'Content Text';
const contentNode = <div data-hook="content">{contentText}</div>;
const { driver } = render(
<BaseModalLayout>
<BaseModalLayout.Content>{contentNode}</BaseModalLayout.Content>
</BaseModalLayout>,
);
expect(await driver.childExists('content')).toBe(true);
});
it('should not render the content when no `content` passed', async () => {
const { driver } = render(
<BaseModalLayout>
<BaseModalLayout.Content dataHook={'content'} />
</BaseModalLayout>,
);
expect(await driver.childExists('content')).toBe(false);
});
});
describe('Footer', () => {
it('should not render `footer` when no actions-related props passed', async () => {
const { driver } = render(
<BaseModalLayout>
<BaseModalLayout.Footer dataHook={'footer'} />
</BaseModalLayout>,
);
expect(await driver.childExists('footer')).toBe(false);
});
it('should render `footer` when `sideActions` passed', async () => {
const sideActionsNode = (
<Text dataHook={'side-actions'}>Side Actions</Text>
);
const { driver } = render(
<BaseModalLayout sideActions={sideActionsNode}>
<BaseModalLayout.Footer />
</BaseModalLayout>,
);
expect(await driver.childExists('side-actions')).toBe(true);
});
it('should render `footer` when `secondaryButtonText` passed', async () => {
const secondaryButtonText = 'secondaryButtonText';
const { driver } = render(
<BaseModalLayout secondaryButtonText={secondaryButtonText}>
<BaseModalLayout.Footer />
</BaseModalLayout>,
);
const secondaryButtonDriver = await driver.getSecondaryButtonDriver();
expect(await secondaryButtonDriver.getButtonTextContent()).toBe(
secondaryButtonText,
);
});
it('should render `footer` and the secondary-button when `secondaryButtonOnClick` passed', async () => {
const secondaryButtonOnClickSpy = jest.fn();
const { driver } = render(
<BaseModalLayout secondaryButtonOnClick={secondaryButtonOnClickSpy}>
<BaseModalLayout.Footer />
</BaseModalLayout>,
);
const secondaryButtonDriver = await driver.getSecondaryButtonDriver();
await secondaryButtonDriver.click();
expect(secondaryButtonOnClickSpy).toHaveBeenCalled();
});
it('should render `footer` and the secondary-button when `secondaryButtonProps` passed', async () => {
const secondaryButtonProps = { disabled: true };
const { driver } = render(
<BaseModalLayout secondaryButtonProps={secondaryButtonProps}>
<BaseModalLayout.Footer />
</BaseModalLayout>,
);
const secondaryButtonDriver = await driver.getSecondaryButtonDriver();
expect(await secondaryButtonDriver.isButtonDisabled()).toBe(true);
});
it('should render `footer` and the primary-button when `primaryButtonText` passed', async () => {
const primaryButtonText = 'primaryButtonText';
const { driver } = render(
<BaseModalLayout primaryButtonText={primaryButtonText}>
<BaseModalLayout.Footer />
</BaseModalLayout>,
);
const primaryButtonDriver = await driver.getPrimaryButtonDriver();
expect(await primaryButtonDriver.getButtonTextContent()).toBe(
primaryButtonText,
);
});
it('should render `footer` and the primary-button when `primaryButtonOnClick` passed', async () => {
const primaryButtonOnClickSpy = jest.fn();
const { driver } = render(
<BaseModalLayout primaryButtonOnClick={primaryButtonOnClickSpy}>
<BaseModalLayout.Footer />
</BaseModalLayout>,
);
const primaryButtonDriver = await driver.getPrimaryButtonDriver();
await primaryButtonDriver.click();
expect(primaryButtonOnClickSpy).toHaveBeenCalled();
});
it('should render `footer` and the primary-button when `primaryButtonProps` passed', async () => {
const primaryButtonProps = { disabled: true };
const { driver } = render(
<BaseModalLayout primaryButtonProps={primaryButtonProps}>
<BaseModalLayout.Footer />
</BaseModalLayout>,
);
const primaryButtonDriver = await driver.getPrimaryButtonDriver();
expect(await primaryButtonDriver.isButtonDisabled()).toBe(true);
});
it('should render primary buttons children from `primaryButtonProps` when primaryTextButton is not passed', async () => {
const primaryButtonProps = {
children: <div data-hook="test-data-hook">test</div>,
};
const { driver } = render(
<BaseModalLayout primaryButtonProps={primaryButtonProps}>
<BaseModalLayout.Footer />
</BaseModalLayout>,
);
expect(await driver.childExists('test-data-hook')).toBe(true);
});
it('should render secondary buttons children from `secondaryButtonProps` when secondaryTextButton is not passed', async () => {
const secondaryButtonProps = {
children: <div data-hook="test-data-hook">test</div>,
};
const { driver } = render(
<BaseModalLayout secondaryButtonProps={secondaryButtonProps}>
<BaseModalLayout.Footer />
</BaseModalLayout>,
);
expect(await driver.childExists('test-data-hook')).toBe(true);
});
it('should render text as primary buttons children when both `primaryButtonProps` and primaryTextButton are passed', async () => {
const primaryButtonProps = {
children: <div data-hook="test-data-hook">test</div>,
};
const primaryButtonText = 'primaryButtonText';
const { driver } = render(
<BaseModalLayout
primaryButtonText={primaryButtonText}
primaryButtonProps={primaryButtonProps}
>
<BaseModalLayout.Footer />
</BaseModalLayout>,
);
const primaryButtonDriver = await driver.getPrimaryButtonDriver();
expect(await primaryButtonDriver.getButtonTextContent()).toBe(
primaryButtonText,
);
expect(await driver.childExists('test-data-hook')).toBe(false);
});
it('should render text as secondary buttons children when both `secondaryButtonProps` and secondaryTextButton are passed', async () => {
const secondaryButtonProps = {
children: <div data-hook="test-data-hook">test</div>,
};
const secondaryButtonText = 'primaryButtonText';
const { driver } = render(
<BaseModalLayout
secondaryButtonText={secondaryButtonText}
secondaryButtonProps={secondaryButtonProps}
>
<BaseModalLayout.Footer />
</BaseModalLayout>,
);
const secondaryButtonDriver = await driver.getSecondaryButtonDriver();
expect(await secondaryButtonDriver.getButtonTextContent()).toBe(
secondaryButtonText,
);
expect(await driver.childExists('test-data-hook')).toBe(false);
});
});
describe('Footnote', () => {
it('should not render `footnote` when prop is not provided', async () => {
const { driver } = render(
<BaseModalLayout>
<BaseModalLayout.Footnote dataHook={'footnote'} />
</BaseModalLayout>,
);
expect(await driver.childExists('footnote')).toBe(false);
});
it('should render `footnote` when prop is passed', async () => {
const footnoteNode = <div data-hook={'footnote'} />;
const { driver } = render(
<BaseModalLayout footnote={footnoteNode}>
<BaseModalLayout.Footnote />
</BaseModalLayout>,
);
expect(await driver.childExists('footnote')).toBe(true);
});
it('should render `footnote` when `children` was passed', async () => {
const footnoteNode = <div data-hook={'footnote'} />;
const { driver } = render(
<BaseModalLayout>
<BaseModalLayout.Footnote>
{footnoteNode}
</BaseModalLayout.Footnote>
</BaseModalLayout>,
);
expect(await driver.childExists('footnote')).toBe(true);
});
});
describe('Illustration', () => {
it('should not render `illustration` when prop is not provided', async () => {
const { driver } = render(
<BaseModalLayout>
<BaseModalLayout.Illustration dataHook={'illustration'} />
</BaseModalLayout>,
);
expect(await driver.childExists('illustration')).toBe(false);
});
it('should render `illustration` when text prop is passed', async () => {
const illustrationSrc = 'illustration-source';
const { driver } = render(
<BaseModalLayout illustration={illustrationSrc}>
<BaseModalLayout.Illustration />
</BaseModalLayout>,
);
expect(await driver.getIllustrationSrc()).toBe(illustrationSrc);
});
it('should render `illustration` when node prop is passed', async () => {
const illustrationNode = <img data-hook="illustration" />;
const { driver } = render(
<BaseModalLayout illustration={illustrationNode}>
<BaseModalLayout.Illustration />
</BaseModalLayout>,
);
expect(await driver.childExists('illustration')).toBe(true);
});
it('should render `illustration` when node is passed as children', async () => {
const illustrationNode = <img data-hook="illustration" />;
const { driver } = render(
<BaseModalLayout>
<BaseModalLayout.Illustration>
{illustrationNode}
</BaseModalLayout.Illustration>
</BaseModalLayout>,
);
expect(await driver.childExists('illustration')).toBe(true);
});
});
});
}
});
| wix/wix-style-react | packages/wix-style-react/src/BaseModalLayout/test/BaseModalLayout.spec.js | JavaScript | mit | 17,101 |
/**
* Copyright (c) 2015, Alexander Orzechowski.
*
* 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.
*/
/**
* Currently in beta stage. Changes can and will be made to the core mechanic
* making this not backwards compatible.
*
* Github: https://github.com/Need4Speed402/tessellator
*/
Tessellator.TextureModel.AttachmentDepth = function (){};
Tessellator.TextureModel.AttachmentDepth.prototype.setup = function (texture){
var gl = texture.tessellator.GL;
if (!this.buffers || this.width !== texture.width || this.height != texture.height){
this.dispose(texture);
this.buffer = gl.createRenderbuffer();
this.width = texture.width;
this.height = texture.height;
this.tessellator = texture.tessellator;
gl.bindRenderbuffer(gl.RENDERBUFFER, this.buffer);
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, this.width, this.height);
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
};
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this.buffer);
};
Tessellator.TextureModel.AttachmentDepth.prototype.configure = Tessellator.EMPTY_FUNC;
Tessellator.TextureModel.AttachmentDepth.prototype.dispose = function (){
if (this.buffer){
this.tessellator.GL.deleteRenderbuffer(this.buffer);
this.buffer = null;
};
}; | Need4Speed402/tessellator | src/textures/model/DepthAttachment.js | JavaScript | mit | 2,423 |
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var $ = require('gulp-load-plugins')({
pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del']
});
gulp.task('partials', function () {
return gulp.src([
path.join(conf.paths.src, '/app/**/*.html'),
path.join(conf.paths.tmp, '/serve/app/**/*.html')
])
.pipe($.minifyHtml({
empty: true,
spare: true,
quotes: true
}))
.pipe($.angularTemplatecache('templateCacheHtml.js', {
module: 'csvToHeatmap',
root: 'app'
}))
.pipe(gulp.dest(conf.paths.tmp + '/partials/'));
});
gulp.task('html', ['inject', 'partials'], function () {
var partialsInjectFile = gulp.src(path.join(conf.paths.tmp, '/partials/templateCacheHtml.js'), { read: false });
var partialsInjectOptions = {
starttag: '<!-- inject:partials -->',
ignorePath: path.join(conf.paths.tmp, '/partials'),
addRootSlash: false
};
var htmlFilter = $.filter('*.html', { restore: true });
var jsFilter = $.filter('**/*.js', { restore: true });
var cssFilter = $.filter('**/*.css', { restore: true });
var assets;
return gulp.src(path.join(conf.paths.tmp, '/serve/*.html'))
.pipe($.inject(partialsInjectFile, partialsInjectOptions))
.pipe(assets = $.useref.assets())
.pipe($.rev())
.pipe(jsFilter)
.pipe($.sourcemaps.init())
.pipe($.ngAnnotate())
.pipe($.uglify({ preserveComments: $.uglifySaveLicense })).on('error', conf.errorHandler('Uglify'))
.pipe($.sourcemaps.write('maps'))
.pipe(jsFilter.restore)
.pipe(cssFilter)
.pipe($.sourcemaps.init())
.pipe($.minifyCss({ processImport: false }))
.pipe($.sourcemaps.write('maps'))
.pipe(cssFilter.restore)
.pipe(assets.restore())
.pipe($.useref())
.pipe($.revReplace())
.pipe(htmlFilter)
.pipe($.minifyHtml({
empty: true,
spare: true,
quotes: true,
conditionals: true
}))
.pipe(htmlFilter.restore)
.pipe(gulp.dest(path.join(conf.paths.dist, '/')))
.pipe($.size({ title: path.join(conf.paths.dist, '/'), showFiles: true }));
});
// Only applies for fonts from bower dependencies
// Custom fonts are handled by the "other" task
gulp.task('fonts', function () {
return gulp.src($.mainBowerFiles())
.pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
.pipe($.flatten())
.pipe(gulp.dest(path.join(conf.paths.dist, '/fonts/')));
});
gulp.task('other', function () {
var fileFilter = $.filter(function (file) {
return file.stat.isFile();
});
return gulp.src([
path.join(conf.paths.src, '/**/*'),
path.join('!' + conf.paths.src, '/**/*.{html,css,js}')
])
.pipe(fileFilter)
.pipe(gulp.dest(path.join(conf.paths.dist, '/')));
});
gulp.task('clean', function () {
return $.del([path.join(conf.paths.dist, '/'), path.join(conf.paths.tmp, '/')]);
});
gulp.task('build', ['html', 'fonts', 'other']);
| Rutorika/csv-to-heatmap | gulp/build.js | JavaScript | mit | 2,950 |
var createTorrent = require('create-torrent')
var debug = require('debug')('instant.io')
var dragDrop = require('drag-drop')
var path = require('path')
var prettyBytes = require('pretty-bytes')
var throttle = require('throttleit')
var thunky = require('thunky')
var uploadElement = require('upload-element')
var WebTorrent = require('webtorrent')
var xhr = require('xhr')
var util = require('./util')
global.WEBTORRENT_ANNOUNCE = createTorrent.announceList
.map(function (arr) {
return arr[0]
})
.filter(function (url) {
return url.indexOf('wss://') === 0 || url.indexOf('ws://') === 0
})
if (!WebTorrent.WEBRTC_SUPPORT) {
util.error('This browser is unsupported. Please use a browser with WebRTC support.')
}
var getClient = thunky(function (cb) {
getRtcConfig('/rtcConfig', function (err, rtcConfig) {
if (err && window.location.hostname === 'instant.io') {
if (err) util.error(err)
createClient(rtcConfig)
} else if (err) {
getRtcConfig('https://instant.io/rtcConfig', function (err, rtcConfig) {
if (err) util.error(err)
createClient(rtcConfig)
})
} else {
createClient(rtcConfig)
}
})
function createClient (rtcConfig) {
var client = window.client = new WebTorrent({
tracker: {
rtcConfig: rtcConfig
}
})
client.on('warning', util.warning)
client.on('error', util.error)
cb(null, client)
}
})
// For performance, create the client immediately
getClient(function () {})
// Seed via upload input element
var upload = document.querySelector('input[name=upload]')
uploadElement(upload, function (err, files) {
if (err) return util.error(err)
files = files.map(function (file) { return file.file })
onFiles(files)
})
// Seed via drag-and-drop
dragDrop('body', onFiles)
// Download via input element
document.querySelector('form').addEventListener('submit', function (e) {
e.preventDefault()
downloadTorrent(document.querySelector('form input[name=torrentId]').value.trim())
})
// Download by URL hash
onHashChange()
window.addEventListener('hashchange', onHashChange)
function onHashChange () {
var hash = decodeURIComponent(window.location.hash.substring(1)).trim()
if (hash !== '') downloadTorrent(hash)
}
// Register a protocol handler for "magnet:" (will prompt the user)
navigator.registerProtocolHandler('magnet', window.location.origin + '#%s', 'Instant.io')
function getRtcConfig (url, cb) {
xhr(url, function (err, res) {
if (err || res.statusCode !== 200) {
cb(new Error('Could not get WebRTC config from server. Using default (without TURN).'))
} else {
var rtcConfig
try {
rtcConfig = JSON.parse(res.body)
} catch (err) {
return cb(new Error('Got invalid WebRTC config from server: ' + res.body))
}
debug('got rtc config: %o', rtcConfig)
cb(null, rtcConfig)
}
})
}
function onFiles (files) {
debug('got files:')
files.forEach(function (file) {
debug(' - %s (%s bytes)', file.name, file.size)
})
// .torrent file = start downloading the torrent
files.filter(isTorrentFile).forEach(downloadTorrentFile)
// everything else = seed these files
seed(files.filter(isNotTorrentFile))
}
function isTorrentFile (file) {
var extname = path.extname(file.name).toLowerCase()
return extname === '.torrent'
}
function isNotTorrentFile (file) {
return !isTorrentFile(file)
}
function downloadTorrent (torrentId) {
util.log('Downloading torrent from ' + torrentId)
getClient(function (err, client) {
if (err) return util.error(err)
client.add(torrentId, onTorrent)
})
}
function downloadTorrentFile (file) {
util.log('Downloading torrent from <strong>' + file.name + '</strong>')
getClient(function (err, client) {
if (err) return util.error(err)
client.add(file, onTorrent)
})
}
function seed (files) {
if (files.length === 0) return
util.log('Seeding ' + files.length + ' files')
// Seed from WebTorrent
getClient(function (err, client) {
if (err) return util.error(err)
client.seed(files, onTorrent)
})
}
function onTorrent (torrent) {
torrent.on('warning', util.warning)
torrent.on('error', util.error)
upload.value = upload.defaultValue // reset upload element
var torrentFileName = path.basename(torrent.name, path.extname(torrent.name)) + '.torrent'
util.log('"' + torrentFileName + '" contains ' + torrent.files.length + ' files:')
torrent.files.forEach(function (file) {
util.log(' - ' + file.name + ' (' + prettyBytes(file.length) + ')')
})
util.log(
'Torrent info hash: ' + torrent.infoHash + ' ' +
'<a href="/#' + torrent.infoHash + '" onclick="prompt(\'Share this link with anyone you want to download this torrent:\', this.href);return false;">[Share link]</a> ' +
'<a href="' + torrent.magnetURI + '" target="_blank">[Magnet URI]</a> ' +
'<a href="' + torrent.torrentFileBlobURL + '" target="_blank" download="' + torrentFileName + '">[Download .torrent]</a>'
)
function updateSpeed () {
var progress = (100 * torrent.progress).toFixed(1)
util.updateSpeed(
'<b>Peers:</b> ' + torrent.numPeers + ' ' +
'<b>Progress:</b> ' + progress + '% ' +
'<b>Download speed:</b> ' + prettyBytes(window.client.downloadSpeed) + '/s ' +
'<b>Upload speed:</b> ' + prettyBytes(window.client.uploadSpeed) + '/s'
)
}
torrent.on('download', throttle(updateSpeed, 250))
torrent.on('upload', throttle(updateSpeed, 250))
setInterval(updateSpeed, 5000)
updateSpeed()
torrent.files.forEach(function (file) {
// append file
file.appendTo(util.logElem, {
maxBlobLength: 2 * 1000 * 1000 * 1000 // 2 GB
}, function (err, elem) {
if (err) return util.error(err)
})
// append download link
file.getBlobURL(function (err, url) {
if (err) return util.error(err)
var a = document.createElement('a')
a.target = '_blank'
a.download = file.name
a.href = url
a.textContent = 'Download ' + file.name
util.log(a)
})
})
}
| bradparks/instant.io | client/index.js | JavaScript | mit | 6,088 |
// Initialize Phaser, and creates a 400x490px game
var game = new Phaser.Game(400, 490, Phaser.AUTO, 'game_div');
var game_state = {};
// Creates a new 'main' state that wil contain the game
game_state.main = function() { };
game_state.main.prototype = {
preload: function() {
// Change the background color of the game
this.game.stage.backgroundColor = '#71c5cf';
// Load the bird sprite
this.game.load.image('bird', 'assets/bird.png');
this.game.load.image('pipe', 'assets/pipe.png');
},
create: function() {
// Display the bird on the screen
this.bird = this.game.add.sprite(100, 245, 'bird');
// Add gravity to the bird to make it fall
this.bird.body.gravity.y = 1000;
this.pipes = game.add.group();
this.pipes.createMultiple(20, 'pipe');
// Call the 'jump' function when the spacekey is hit
var space_key = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
space_key.onDown.add(this.jump, this);
this.timer = this.game.time.events.loop(1500, this.add_row_of_pipes, this);
},
update: function() {
// If the bird is out of the world (too high or too low), call the 'restart_game' function
if (this.bird.inWorld == false)
this.restart_game();
},
jump: function() {
// Add a vertical velocity to the bird
this.bird.body.velocity.y = -350;
},
// Restart the game
restart_game: function() {
// Start the 'main' state, which restarts the game
this.game.state.start('main');
this.game.time.events.remove(this.timer);
},
add_one_pipe: function(x, y) {
// Get the first dead pipe of our group
var pipe = this.pipes.getFirstDead();
// Set the new position of the pipe
pipe.reset(x, y);
// Add velocity to the pipe to make it move left
pipe.body.velocity.x = -300;
// Kill the pipe when it's no longer visible
pipe.outOfBoundsKill = true;
},
add_row_of_pipes: function() {
var hole = Math.floor(Math.random()*5)+1;
for (var i = 0; i < 8; i++)
if (i != hole && i != hole +1)
this.add_one_pipe(400, i*60+10);
},
};
// Add and start the 'main' state to start the game
game.state.add('main', game_state.main);
game.state.start('main'); | cutehalo/cutehalo.github.com | lab/basic_template/main.js | JavaScript | mit | 2,295 |
Package.describe({
summary: "The Meteor command-line tool",
version: '1.3.4_1'
});
Package.includeTool();
| 4commerce-technologies-AG/meteor | packages/meteor-tool/package.js | JavaScript | mit | 111 |
define(function() {
'use strict';
return function($location, $modal, Rest) {
/**
* check if a time saving account is available
* @param {Object} user
*/
function getTimeSavingAccounts(user) {
if (undefined === user) {
return Rest.account.timesavingaccounts.getResource().query();
}
return Rest.admin.timesavingaccounts.getResource().query({ account: user.roles.account._id });
}
/**
* @param {Object} $scope
* @return {Function}
*/
return function getCreateRequest(parentScope) {
/**
* @param {Object} user Optional parameter
*/
return function(user) {
var templateUrl =
(undefined === user) ?
'partials/account/request/request-create-modal.html' :
'partials/admin/request/spoof-user-modal.html';
var $scope = parentScope.$new();
$scope.timeSavingAccounts = getTimeSavingAccounts(user);
$scope.user = user;
$scope.goto = function(requestType) {
if (undefined === user) {
$location.url('/account/requests/'+requestType+'-edit');
return;
}
$location.url('/admin/requests/'+requestType+'-edit?user='+user._id);
};
$modal({
scope: $scope,
templateUrl: templateUrl,
show: true
});
};
};
};
});
| gadael/gadael | public/js/services/getCreateRequest.js | JavaScript | mit | 1,677 |
import _ from 'lodash'
const optionsValidation = {
expectedType: 'object or function',
predicate({ options }) {
return _.isPlainObject(options)
},
}
const optionsTimeoutValidation = {
identifier: '"options.timeout"',
expectedType: 'integer',
predicate({ options }) {
return !options.timeout || _.isInteger(options.timeout)
},
}
const fnValidation = {
expectedType: 'function',
predicate({ code }) {
return _.isFunction(code)
},
}
const validations = {
defineTestRunHook: [
{ identifier: 'first argument', ...optionsValidation },
optionsTimeoutValidation,
{ identifier: 'second argument', ...fnValidation },
],
defineTestCaseHook: [
{ identifier: 'first argument', ...optionsValidation },
{
identifier: '"options.tags"',
expectedType: 'string',
predicate({ options }) {
return !options.tags || _.isString(options.tags)
},
},
optionsTimeoutValidation,
{ identifier: 'second argument', ...fnValidation },
],
defineStep: [
{
identifier: 'first argument',
expectedType: 'string or regular expression',
predicate({ pattern }) {
return _.isRegExp(pattern) || _.isString(pattern)
},
},
{ identifier: 'second argument', ...optionsValidation },
optionsTimeoutValidation,
{ identifier: 'third argument', ...fnValidation },
],
}
export default function validateArguments({ args, fnName, location }) {
validations[fnName].forEach(({ identifier, expectedType, predicate }) => {
if (!predicate(args)) {
throw new Error(
`${location}: Invalid ${identifier}: should be a ${expectedType}`
)
}
})
}
| mhoyer/cucumber-js | src/support_code_library_builder/validate_arguments.js | JavaScript | mit | 1,677 |
describe('Testing command controller', function () {
var controller, dashboardService, scope, commandService, userService,
$intervalSpy, deferredSave, deferredCommandLog, deferredCommandList,
deferredSend, deferredLock, deferredCommand;
var mission = {
missionName : 'ATest',
};
var email = "john.smith@gmail.com";
var list = [{
"value": "Null Command Echo",
"types": [
{
"value": "Get"
},
{
"value": "Set"
},
{
"value": "Invoke"
}]
},{
"value": "Pointing",
"types": [
{
"value": "Get"
},
{
"value": "Set"
}]
}];
beforeEach(function () {
// load the module
module('app');
inject(function($controller, $rootScope, $interval, _$q_, _commandService_){
commandService = _commandService_;
$intervalSpy = jasmine.createSpy('$interval', $interval);
dashboardService = jasmine.createSpyObj('dashboardService',
['getTime', 'getCurrentMission']);
userService = jasmine.createSpyObj('userService', ['getUserEmail']);
deferredSave = _$q_.defer();
deferredCommandLog = _$q_.defer();
deferredCommandList = _$q_.defer();
deferredSend = _$q_.defer();
deferredLock = _$q_.defer();
deferredCommand = _$q_.defer();
spyOn(commandService, "saveCommand").and.returnValue(deferredSave.promise);
spyOn(commandService, "getCommandLog").and.returnValue(deferredCommandLog.promise);
spyOn(commandService, "getCommandList").and.returnValue(deferredCommandList.promise);
spyOn(commandService, "sendCommand").and.returnValue(deferredSend.promise);
spyOn(commandService, "lockCommand").and.returnValue(deferredLock.promise);
spyOn(commandService, "getCommand").and.returnValue(deferredCommand.promise);
scope = $rootScope.$new();
scope.widget = {
name: "Command",
settings: {
active: false,
commandlog: true
}
};
dashboardService.getCurrentMission.and.callFake(function() {
return mission;
});
userService.getUserEmail.and.callFake(function() {
return email;
});
deferredCommandList.resolve({ data : list, status: 200 });
controller = $controller('CommandCtrl', {
$scope: scope,
dashboardService: dashboardService,
commandService: commandService,
userService: userService,
$interval: $intervalSpy
});
});
});
it('should define the command controller', function() {
expect(controller).toBeDefined();
});
it('should define function scope.initialise', function(){
expect(scope.initialise).toBeDefined();
})
it('should initialise the initial variables on scope.initialise call when controller is defined', function(){
var nullCommand = {
name : "",
arguments : "",
sent_timestamp : "",
time : "",
}
expect(scope.arguments).toEqual("");
expect(scope.entered).toEqual(false);
expect(scope.locked).toEqual(false);
expect(scope.disableEnter).toEqual(false);
expect(scope.disableInput).toEqual(false);
expect(scope.disableLock).toEqual(true);
expect(scope.command).toEqual(nullCommand);
expect(scope.lockModel).toEqual("LOCK");
})
it('should set the user email and current mission name', function(){
expect(dashboardService.getCurrentMission).toHaveBeenCalled();
expect(userService.getUserEmail).toHaveBeenCalled();
expect(scope.mission).toEqual({missionName : 'ATest'});
expect(scope.email).toEqual("john.smith@gmail.com");
})
it('should initialise scope.sent as false', function(){
expect(scope.sent).toEqual(false);
})
it('should define function scope.enter', function(){
expect(scope.enter).toBeDefined();
})
it('should update the scope.command when scope.enter is called', function(){
scope.cmd = "GET";
scope.arguments = "00";
deferredSave.resolve({ data : {}, status : 200 });
scope.enter();
// call digest cycle for this to work
scope.$digest();
expect(scope.command.name).toEqual('GET');
expect(scope.command.arguments).toEqual('00');
expect(scope.entered).toEqual(true);
expect(scope.disableEnter).toEqual(true);
})
it('should define function scope.lockCommand', function(){
expect(scope.lockCommand).toBeDefined();
})
it('should lock the command and disable it when scope.lockCommand is called', function(){
scope.command = {
name: "Null Command Echo",
argument: "00"
}
scope.entered = true;
deferredLock.resolve({ data : {}, status : 200 });
scope.lockCommand();
// call digest cycle for this to work
scope.$digest();
expect(scope.locked).toEqual(true);
expect(scope.disableLock).toEqual(true);
expect(scope.disableInput).toEqual(true);
})
it('should define function scope.changeInput', function(){
expect(scope.changeInput).toBeDefined();
})
it('should enable enter button when enter has been clicked before and scope.changeInput is called', function(){
scope.entered = true;
scope.changeInput();
expect(scope.entered).toEqual(false);
expect(scope.disableEnter).toEqual(false);
})
it('should enable enter and lock buttons when enter is diabled and scope.changeInput is called', function(){
scope.entered = false;
scope.changeInput();
expect(scope.disableLock).toEqual(false);
expect(scope.disableEnter).toEqual(false);
})
it('should define function scope.sendCommand', function(){
expect(scope.sendCommand).toBeDefined();
})
it('should update command timestamp when scope.sendCommand is called', function(){
var time = {
days : '070',
minutes : '10',
hours : '10',
seconds : '50',
utc : '070.10:10:50 UTC',
today : ''
};
scope.command = {
name: "Null Command Echo",
arguments: "00",
sent_timestamp: 1533066264232,
time: time.utc
};
dashboardService.getTime.and.callFake(function() {
return time;
});
scope.sendCommand();
expect(scope.command.time).toEqual(time.utc);
expect(scope.command.name).toEqual("Null Command Echo");
expect(scope.command.arguments).toEqual("00");
})
it('should call sendCommand route and reset all values when scope.sendCommand is called', function() {
var time = {
days : '070',
minutes : '10',
hours : '10',
seconds : '50',
utc : '070.10:10:50 UTC',
today : ''
};
scope.command = {
name: "Null Command Echo",
arguments: "00",
sent_timestamp: 1533066264232,
time: '070.10:10:50 UTC'
};
scope.commandForm = {
$setPristine: function(){
},
$setUntouched: function(){
}
};
dashboardService.getTime.and.callFake(function() {
return time;
});
deferredSend.resolve({ data : {}, status : 200 });
scope.sendCommand();
// call digest cycle for this to work
scope.$digest();
expect(commandService.sendCommand).toHaveBeenCalled();
//expect values to reset
expect(scope.command).toEqual({ name: '', arguments: '', sent_timestamp: '', time: ''});
expect(scope.entered).toEqual(false);
expect(scope.locked).toEqual(false);
expect(scope.disableEnter).toEqual(false);
expect(scope.disableInput).toEqual(false);
expect(scope.disableLock).toEqual(true);
});
it('should not reset variables when sendCommand status is other than 200', function() {
var time = {
days : '070',
minutes : '10',
hours : '10',
seconds : '50',
utc : '070.10:10:50 UTC',
today : ''
};
scope.command = {
name: "Null Command Echo",
arguments: "00",
sent_timestamp: 1533066264232,
time: '070.10:10:50 UTC'
};
dashboardService.getTime.and.callFake(function() {
return time;
});
deferredSend.resolve({ data : {}, status : 404 });
scope.sendCommand();
// call digest cycle for this to work
scope.$digest();
expect(commandService.sendCommand).toHaveBeenCalled();
//expect values not to reset
expect(scope.command.name).toEqual("Null Command Echo");
expect(scope.command.arguments).toEqual("00");
expect(scope.command.time).toEqual("070.10:10:50 UTC");
});
it('should define function scope.updateCommandlog', function(){
expect(scope.updateCommandlog).toBeDefined();
})
it('should get command list when scope.updateCommandlog is called', function() {
scope.mission = {
missionName : 'ATest',
};
var result = [{
arguments: "87",
mission: "ATest",
name: "Null Command Echo",
time: "010.16:52:44 UTC",
sent_timestamp:1533066264168,
user: "john.smith@gmail.com",
sent_to_satellite:true,
response: [
{
"status": "Parameter access sent",
"data": "",
"gwp_timestamp": 1533066264169,
"metadata_data":""
},
{
"status": "GET Parameter accessed successfully",
"metadata_data": "",
"gwp_timestamp": 1533066264231,
"data":""
},
{
"status": "success",
"metadata_data": 32,
"gwp_timestamp": 1533066264232,
"data":""
}
]
}, {
arguments: "00",
mission: "ATest",
name: "Dummy Command",
time: "010.22:52:44 UTC",
sent_timestamp:1533066264159,
user: "john.smith@gmail.com",
sent_to_satellite:true,
response: [
{
"status": "Parameter access sent",
"data": "",
"gwp_timestamp": 1533066264160,
"metadata_data":""
},
{
"status": "GET Parameter accessed successfully",
"data": "",
"gwp_timestamp": 1533066264230,
"metadata_data":""
},
{
"status": "success received",
"data": "",
"gwp_timestamp": 1533066264232,
"metadata_data":32
}
]
}];
deferredCommandLog.resolve({ data : result, status: 200 });
deferredCommand.resolve({ data : {}, status: 200 });
scope.updateCommandlog();
// call digest cycle for this to work
scope.$digest();
expect(commandService.getCommandLog).toHaveBeenCalledWith(scope.mission.missionName);
expect(scope.commandLog).toEqual(result);
expect(scope.commandLog[0].responseStatus).toEqual("success");
expect(scope.commandLog[0].responseData).toEqual(32);
expect(scope.commandLog[1].responseStatus).toEqual("success received");
expect(scope.commandLog[1].responseData).toEqual(32);
});
it('should call $interval one time', function(){
expect($intervalSpy).toHaveBeenCalled();
expect($intervalSpy.calls.count()).toBe(1);
})
it('should call $interval on updateClock function', function(){
expect($intervalSpy).toHaveBeenCalledWith(scope.updateCommandlog, 1000);
})
it('should cancel interval when scope is destroyed', function(){
spyOn($intervalSpy, 'cancel');
scope.$destroy();
expect($intervalSpy.cancel.calls.count()).toBe(1);
})
});
| quindar/quindar-ux | app/directives/command/command.spec.js | JavaScript | mit | 12,934 |
var build = {}
build.view = function(element, props, state) {
var link = function() {
var scripts = document.querySelectorAll('head script')
var string = ''
for (var k in scripts) {
var url = scripts[k].src
if (!url) continue
string += 'file=' + url + '&'
}
return 'http://reducisaurus.appspot.com/js?' + string
}()
state.a = {
_target: 'blank',
_href: link
}
}
var app = {}
app.controller = function(props) {
this.show = mag.prop(true)
this.name = '?'
this.onload = utils.onload
}
app.view = function(element, props, state) {
state.test = {
_class: 'test ' + (state.show() ? 'show' : 'hide'),
_html: 'Hello',
}
// nested
state.b = mag.module('build', build)
state.button = {
_onclick: function() {
state.show(!state.show())
}
}
setTimeout(function() {
state.name = 'world'
}, 1000)
}
mag.module("test", app, {
prop: true
})
| magnumjs/mag.js | examples/nested.js | JavaScript | mit | 934 |
var expect = require('chai').expect
var fixtures = require('../fixtures/electrum.json')
/**
* @param {Object} data
*/
function runElectrumTests(data) {
var transport
beforeEach(function () {
transport = data.transport
})
var exceptMethods = [
'blockchain.headers.subscribe',
'blockchain.numblocks.subscribe',
'blockchain.estimatefee',
'server.banner',
'server.donation_address',
'server.peers.subscribe'
]
Object.keys(fixtures[data.network]).forEach(function (method) {
fixtures[data.network][method].forEach(function (fixture) {
it(method, function (done) {
transport.request(method, fixture.params, function (response) {
if (exceptMethods.indexOf(method) !== -1) {
expect(response.result).to.be.not.undefined
} else {
expect(response.result).to.deep.equal(fixture.expect)
}
done()
})
})
})
})
}
module.exports = {
runElectrumTests: runElectrumTests
}
| fanatid/electrumjs-server | test/interface/electrum.js | JavaScript | mit | 1,008 |
/**
* pax
* https://github.com/reekoheek/pax
*
* Copyright (c) 2013 PT Sagara Xinix Solusitama
* Licensed under the MIT license.
* https://github.com/reekoheek/pax/blob/master/LICENSE
*
* Composer command
*
*/
var fs = require('fs'),
d = require('simply-deferred'),
logger;
var cmd = function(pax, args, opts) {
logger = pax.log;
opts = opts || {};
var deferred = d.Deferred(),
bowerFile = './bower.json',
log = opts.log || cmd.log;
log.data('start');
if (fs.existsSync(bowerFile)) {
var manifest = JSON.parse(fs.readFileSync(bowerFile, { encoding: 'utf8' }));
for(var i in manifest.dependencies) {
log.data('dependency', {
name: i,
version: manifest.dependencies[i]
});
}
}
log.data('end');
if (fs.existsSync(bowerFile)) {
deferred.resolve();
} else {
deferred.reject(new Error('No bower dependencies'));
}
return deferred.promise();
};
var logState = '';
cmd.log = {
data: function(state, data) {
if (state == 'start' || state == 'end') {
logState = '';
} else {
if (logState != state) {
logState = state;
logger.out('\nBower dependencies:'.bold);
}
logger.out(' - ' + data.name + '@' + data.version);
}
}
};
module.exports = cmd; | krisanalfa/pax | lib/commands/bower/index.js | JavaScript | mit | 1,430 |
var express = require('express')
, bookshelf = require('../bookshelf');
var notationsRouter = express.Router({mergeParams: true});
notationsRouter.route('/')
.get(function(request, response) {
request.feedback
.notations()
.fetch()
.then(function(notations){
response.status(200).json(notations);
});
})
.post(function(request, response) {
request.checkBody('value', 'Invalid value : it must be an integer -1, 0 or 1.')
.notEmpty().isInt().gte(-1).lte(1);
var errors = request.validationErrors();
if (errors) { response.status(422).send(errors); return; }
// YOU MAY CHANGE YOUR NOTATION
request.feedback
.notations()
.query({ where: { user_id: request.currentUser.id }})
.fetchOne()
.then(function (notation) {
if(notation) {
promise = notation
.save({ value: request.body.value }, { patch: true })
.then(function(notation){
response.status(200).json(notation);
});
} else {
promise = request.feedback
.notations()
.create({ user_id: request.currentUser.id, value: request.body.value })
.then(function(notation){
response.status(201).json(notation);
});
}
});
});
module.exports = notationsRouter;
| hlobit/backfeeds | routes/notations.js | JavaScript | mit | 1,362 |